Download MLbaseModelDriver.py from Pratham0712/NP: direct link, hf CLI and curl.
- Browser
- Download file 4.36 kB
-
https://huggingface.co/Pratham0712/NP/resolve/main/MLbaseModelDriver.py
- Command line
-
hf download hf://Pratham0712/NP/MLbaseModelDriver.py
-
curl -L -o MLbaseModelDriver.py https://huggingface.co/Pratham0712/NP/resolve/main/MLbaseModelDriver.py
4.36 kB
| import torch | |
| import sys | |
| import pandas as pd | |
| from typing import TypedDict, Optional, Tuple | |
| import datetime | |
| import math | |
| import importlib.util | |
| from huggingface_hub import hf_hub_download | |
| from MLmodel import MLmodel | |
| import numpy as np | |
| import pickle | |
| class ProcessedSynapse(TypedDict): | |
| property_id: Optional[str] | |
| nextplace_id: Optional[str] | |
| listing_id: Optional[str] | |
| address: Optional[str] | |
| city: Optional[str] | |
| state: Optional[str] | |
| zip_code: Optional[str] | |
| beds: Optional[int] | |
| baths: Optional[float] | |
| sqft: Optional[int] | |
| lot_size: Optional[int] | |
| year_built: Optional[int] | |
| latitude: Optional[float] | |
| longitude: Optional[float] | |
| property_type: Optional[str] | |
| last_sale_date: Optional[str] | |
| hoa_dues: Optional[float] | |
| market: Optional[str] | |
| listing_price: Optional[float] | |
| listing_date: Optional[str] | |
| sale_price: Optional[float] | |
| sale_date: Optional[str] | |
| class MLBaseModelDriver: | |
| def __init__(self): | |
| self.model, self.scaler1, self.scaler2 = self.load_model() | |
| def _download_model_files(self) -> Tuple[str, str, str, str]: | |
| model_path = "Pratham0712/NextPlace" | |
| model_file = hf_hub_download(repo_id=model_path, filename="model.pkl") | |
| model_class_file = hf_hub_download(repo_id=model_path, filename="MLmodel.py") | |
| scaler1 = hf_hub_download(repo_id=model_file, filename="scaler.pkl") | |
| scaler2 = hf_hub_download(repo_id=model_file, filename="scaler.pkl") | |
| return model_file, scaler1, scaler2, model_class_file | |
| def load_model(self) -> Tuple[any, any, any]: | |
| print(f"Loading the model") | |
| model_file, scaler_1, scaler_2, model_class_file = self._download_model_files() | |
| model_class = self._import_model_class(model_class_file) | |
| model = model_class(input_dim = 4) | |
| with open(model_file, 'rb') as f: | |
| state_dict = pickle.load(f) | |
| model.load_state_dict(state_dict) | |
| model.eval() | |
| with open(scaler_1, 'rb') as f: | |
| scaler1 = pickle.load(f) | |
| with open(scaler_2, 'rb') as f: | |
| scaler2 = pickle.load(f) | |
| print(f"Model is loaded") | |
| return model, scaler1, scaler2 | |
| def _import_model_class(self, model_class_file): | |
| module_name = "MLmodel" | |
| spec = importlib.util.spec_from_file_location(module_name, model_class_file) | |
| model_module = importlib.util.module_from_spec(spec) | |
| sys.modules[module_name] = model_module | |
| spec.loader.exec_module(model_module) | |
| if hasattr(model_module, "MLmodel"): | |
| return model_module.MLmodel | |
| else: | |
| raise AttributeError(f"Nope") | |
| def _preprocess_input(self, data: ProcessedSynapse) -> torch.tensor: | |
| """ | |
| preprocess the input for inference | |
| :param data: synapse from the validator | |
| :return: tensor representing the synapse | |
| beds baths sqft listing_price | |
| """ | |
| df = pd.DataFrame([data]) | |
| default_beds = 3 | |
| default_sqft = 1500.0 | |
| df['beds'] = df['beds'].fillna(default_beds) | |
| df['baths'] = df['baths'].fillna(default_beds) | |
| df['sqft'] = pd.to_numeric(df['sqft'], errors='coerce').fillna(default_sqft) | |
| X = df[['beds', 'baths', 'sqft', 'listing_price']] | |
| input_tensor = torch.tensor(X.values, dtype=torch.float32) | |
| return input_tensor | |
| def run_inference(self, input_data: ProcessedSynapse)-> Tuple[float, str]: | |
| input_tensor = self._preprocess_input(input_data) | |
| with torch.no_grad(): | |
| predict = self.model(input_tensor) | |
| predict_sale_scaled, predict_days_scaled = predict[0].numpy() | |
| predict_price = self._inverseScale_price(predict_sale_scaled) | |
| predict_date = self._inverseScale_date(input_data["listing_date"], input_data["last_sale_date"], predict_days_scaled) | |
| return float(predict_price), predict_date | |
| def _inverseScale_price(self, price): | |
| predict_price = self.scaler1.inverse_transform(price[:, 1].reshape(-1, 1)) | |
| return predict_price | |
| def _inverseScale_date(self, listing_date, last_sale_date, date): | |
| predict_date_inv = self.scaler2.inverse_transform(date[:, 0].reshape(-1, 1)) | |
| ref_date = pd.to_datetime('2024-11-01') | |
| return (predict_date_inv + ref_date) | |