Skip to content

Commit

Permalink
added docstring and typing
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinsingh committed Nov 10, 2024
1 parent 6de9013 commit 079cd0d
Show file tree
Hide file tree
Showing 11 changed files with 324 additions and 26 deletions.
16 changes: 16 additions & 0 deletions src/config/db.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
"""
This module setups the database configuration.
This module uses Pydantic's BaseSettings to manage configuration,
allowing settings to be read from environment variables and a .env file.
"""

from pydantic_settings import BaseSettings, SettingsConfigDict
from sqlalchemy import create_engine


class DbSettings(BaseSettings):
"""
Database configuration settings for the application.
Attributes:
model_config (SettingsConfigDict): Model config, loaded from .env file.
db_conn_str (str): Database connection string.
rent_apart_table_name (str): Name of the rental apartments table in DB.
"""

model_config = SettingsConfigDict(
env_file='config/.env',
env_encoding='utf-8',
Expand Down
20 changes: 19 additions & 1 deletion src/config/logger.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,23 @@
"""
This module is responsible for configuring the logger.
Pydantic is used to load the log level from the environment variables.
The logger is configured using the loguru library.
"""

from loguru import logger
from pydantic_settings import BaseSettings, SettingsConfigDict


class LoggerSettings(BaseSettings):
"""
Logger configuration settings for the application.
Attributes:
model_config (SettingsConfigDict): Model config, loaded from .env file.
log_level (str): Log level for the logger.
"""

model_config = SettingsConfigDict(
env_file='config/.env',
env_encoding='utf-8',
Expand All @@ -11,7 +26,10 @@ class LoggerSettings(BaseSettings):
log_level: str


def configure_logging(level: str):
def configure_logging(level: str) -> None:
"""
Configures the logger with the specified log level.
"""
logger.remove()
logger.add(
'logs/app.log',
Expand Down
16 changes: 16 additions & 0 deletions src/config/model.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
"""
This module contains the model configuration settings for the application.
This module uses Pydantic's BaseSettings to manage configuration,
allowing settings to be read from environment variables and a .env file.
"""

from pydantic import DirectoryPath
from pydantic_settings import BaseSettings, SettingsConfigDict


class ModelSettings(BaseSettings):
"""
Model configuration settings for the application.
Attributes:
model_config (SettingsConfigDict): Model config, loaded from .env file.
model_path (DirectoryPath): Path to the model directory.
model_name (str): Name of the model file.
"""

model_config = SettingsConfigDict(
env_file='config/.env',
env_encoding='utf-8',
Expand Down
33 changes: 33 additions & 0 deletions src/db/db_model.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,48 @@
"""
This module contains the SQLAlchemy model for the rent_apartments table.
The model is defined using SQLAlchemy's DeclarativeBase and Mapped classes.
Base is a subclass of DeclarativeBase, RentApartments is a subclass of Base.
Future models can be defined in a similar way.
"""

from sqlalchemy import INTEGER, REAL, VARCHAR
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

from config import db_settings


class Base(DeclarativeBase):
"""
Base class for the SQLAlchemy model.
"""

pass


class RentApartments(Base):
"""
rent_apartments table model for the SQLAlchemy ORM.
Attributes:
address (Mapped[str]): Address of the apartment.
area (Mapped[float]): Area of the apartment.
constraction_year (Mapped[int]): Year of construction of the apartment.
rooms (Mapped[int]): Number of rooms in the apartment.
bedrooms (Mapped[int]): Number of bedrooms in the apartment.
bathrooms (Mapped[int]): Number of bathrooms in the apartment.
balcony (Mapped[str]): Whether the apartment has a balcony.
storage (Mapped[str]): Whether the apartment has storage.
parking (Mapped[str]): Whether the apartment has parking.
furnished (Mapped[str]): Whether the apartment is furnished.
garage (Mapped[str]): Whether the apartment has a garage.
garden (Mapped[str]): Whether the apartment has a garden.
energy (Mapped[str]): Energy efficiency rating of the apartment.
facilities (Mapped[str]): Additional facilities in the apartment.
zip (Mapped[str]): ZIP code of the apartment.
neighborhood (Mapped[str]): Neighborhood of the apartment.
rent (Mapped[int]): Rent of the apartment.
"""

__tablename__ = db_settings.rent_apart_table_name

Expand Down
31 changes: 29 additions & 2 deletions src/model/model_builder.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,43 @@
"""
The module is responsible for building the model.
The model is built using the `build_model` function
from the `model` module.
"""

from loguru import logger

from config import model_settings
from model.pipeline.model import build_model


class ModelBuilderService:
"""
The service class for building the model.
The class provides functionalities to train
the model and save it to a specified path.
Attributes:
model_path (str): Path to the model directory.
model_name (str): Name of the model file.
Methods:
__init__: Initializes the ModelBuilderService.
train_model: Trains the model and saves it to a
specified directory.
"""

def __init__(self):
def __init__(self) -> None:
"""Initialize the ModelBuilderService."""
self.model_path = model_settings.model_path
self.model_name = model_settings.model_name

def load_model(self):
def train_model(self) -> None:
"""
Train the model from a specified path and
save to the model's directory.
"""
logger.info(
f'Building the model file at '
f'{self.model_path}/{self.model_name}',
Expand Down
38 changes: 35 additions & 3 deletions src/model/model_inference.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
"""
This module provides functionality for making
predictions using a ML model.
It contains the ModelInferenceService class that offers
methods to load a model and make predictions.
"""

from pathlib import Path
import pickle as pkl

Expand All @@ -7,13 +15,36 @@


class ModelInferenceService:
"""
The service class for making predictions using a ML model.
The class provides functionalities to load a model and make
predictions using the model.
def __init__(self):
Attributes:
model (object): The ML model object.
model_path (str): Path to the model directory.
model_name (str): Name of the model file.
Methods:
__init__: Initializes the ModelInferenceService.
load_model: Loads the model from a specified path.
predict: Makes predictions using the loaded model.
"""

def __init__(self) -> None:
"""Initialize the ModelInferenceService."""
self.model = None
self.model_path = model_settings.model_path
self.model_name = model_settings.model_name

def load_model(self):
def load_model(self) -> None:
"""
Load the model from a specified path
Raises:
FileNotFoundError: If the model file does not exist.
"""
logger.info(
f'Checking for existing model file at '
f'{self.model_path}/{self.model_name}',
Expand All @@ -31,6 +62,7 @@ def load_model(self):
with open(model_path, 'rb') as model_file:
self.model = pkl.load(model_file)

def predict(self, input_parameters):
def predict(self, input_parameters: list) -> list:
"""Make predictions using the loaded model."""
logger.info('Making predictions')
return self.model.predict([input_parameters])
17 changes: 16 additions & 1 deletion src/model/pipeline/collection.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
"""
This module is responsible for extracting data from the database.
It uses a function to extract data from the RentApartments table in
the database and load it into a pandas DataFrame.
It uses SqlAlchemy to retrieve data from the database for further
analysis or processing.
"""

from loguru import logger
import pandas as pd
from sqlalchemy import select
Expand All @@ -6,7 +15,13 @@
from db.db_model import RentApartments


def load_data_from_db():
def load_data_from_db() -> pd.DataFrame:
"""
Load data from the RentApartments table in the database.
Returns:
pd.DataFrame: DataFrame containing the RentApartments data
"""
logger.info("Extracting data from database")
query = select(RentApartments)
return pd.read_sql(query, engine)
Loading

0 comments on commit 079cd0d

Please sign in to comment.