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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import sys
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from typing import TypedDict, Optional, Tuple
|
| 5 |
+
import datetime
|
| 6 |
+
import math
|
| 7 |
+
import importlib.util
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
import pickle
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
"""
|
| 13 |
+
Data container class representing the data shape of the synapse coming into `run_inference`
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class ProcessedSynapse(TypedDict):
|
| 18 |
+
id: Optional[str]
|
| 19 |
+
property_id: Optional[str]
|
| 20 |
+
listing_id: Optional[str]
|
| 21 |
+
address: Optional[str]
|
| 22 |
+
city: Optional[str]
|
| 23 |
+
state: Optional[str]
|
| 24 |
+
zip: Optional[str]
|
| 25 |
+
price: Optional[float]
|
| 26 |
+
beds: Optional[int]
|
| 27 |
+
baths: Optional[float]
|
| 28 |
+
sqft: Optional[int]
|
| 29 |
+
lot_size: Optional[int]
|
| 30 |
+
year_built: Optional[int]
|
| 31 |
+
days_on_market: Optional[int]
|
| 32 |
+
latitude: Optional[float]
|
| 33 |
+
longitude: Optional[float]
|
| 34 |
+
property_type: Optional[str]
|
| 35 |
+
last_sale_date: Optional[str]
|
| 36 |
+
hoa_dues: Optional[float]
|
| 37 |
+
query_date: Optional[str]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
This class must do two things
|
| 42 |
+
1) The constructor must load the model
|
| 43 |
+
2) This class must implement a method called `run_inference` that takes the input data and returns a tuple
|
| 44 |
+
of float, str representing the predicted sale price and the predicted sale date.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MLBaseModelDriver:
|
| 49 |
+
|
| 50 |
+
def __init__(self):
|
| 51 |
+
self.model, self.label_encoder, self.scaler = self.load_model()
|
| 52 |
+
|
| 53 |
+
def load_model(self) -> Tuple[any, any, any]:
|
| 54 |
+
"""
|
| 55 |
+
load the model and model parameters
|
| 56 |
+
:return: model, label encoder, and scaler
|
| 57 |
+
"""
|
| 58 |
+
print(f"Loading model...")
|
| 59 |
+
model_file, scaler_file, label_encoders_file, model_class_file = self._download_model_files()
|
| 60 |
+
model_class = self._import_model_class(model_class_file)
|
| 61 |
+
|
| 62 |
+
model = model_class(input_dim=4)
|
| 63 |
+
state_dict = torch.load(model_file, weights_only=False)
|
| 64 |
+
model.load_state_dict(state_dict)
|
| 65 |
+
model.eval()
|
| 66 |
+
|
| 67 |
+
# Load additional artifacts
|
| 68 |
+
with open(scaler_file, 'rb') as f:
|
| 69 |
+
scaler = pickle.load(f)
|
| 70 |
+
|
| 71 |
+
with open(label_encoders_file, 'rb') as f:
|
| 72 |
+
label_encoders = pickle.load(f)
|
| 73 |
+
|
| 74 |
+
print(f"Model Loaded.")
|
| 75 |
+
return model, label_encoders, scaler
|
| 76 |
+
|
| 77 |
+
def _download_model_files(self) -> Tuple[str, str, str, str]:
|
| 78 |
+
"""
|
| 79 |
+
download files from hugging face
|
| 80 |
+
:return: downloaded files
|
| 81 |
+
"""
|
| 82 |
+
model_path = "Nickel5HF/NextPlace"
|
| 83 |
+
|
| 84 |
+
# Download the model files from the Hugging Face Hub
|
| 85 |
+
model_file = hf_hub_download(repo_id=model_path, filename="model_files/real_estate_model.pth")
|
| 86 |
+
scaler_file = hf_hub_download(repo_id=model_path, filename="model_files/scaler.pkl")
|
| 87 |
+
label_encoders_file = hf_hub_download(repo_id=model_path, filename="model_files/label_encoder.pkl")
|
| 88 |
+
model_class_file = hf_hub_download(repo_id=model_path, filename="MLBaseModel.py")
|
| 89 |
+
|
| 90 |
+
# Load the model and artifacts
|
| 91 |
+
return model_file, scaler_file, label_encoders_file, model_class_file
|
| 92 |
+
|
| 93 |
+
def _import_model_class(self, model_class_file):
|
| 94 |
+
"""
|
| 95 |
+
import the model class and instantiate it
|
| 96 |
+
:param model_class_file: file path to the model class
|
| 97 |
+
:return: None
|
| 98 |
+
"""
|
| 99 |
+
# Reference docs here: https://docs.python.org/3/library/importlib.html#importlib.util.spec_from_loader
|
| 100 |
+
module_name = "MLBaseModel"
|
| 101 |
+
spec = importlib.util.spec_from_file_location(module_name, model_class_file)
|
| 102 |
+
model_module = importlib.util.module_from_spec(spec)
|
| 103 |
+
sys.modules[module_name] = model_module
|
| 104 |
+
spec.loader.exec_module(model_module)
|
| 105 |
+
|
| 106 |
+
if hasattr(model_module, "MLBaseModel"):
|
| 107 |
+
return model_module.MLBaseModel
|
| 108 |
+
else:
|
| 109 |
+
raise AttributeError(f"The module does not contain a class named 'MLBaseModel'")
|
| 110 |
+
|
| 111 |
+
def run_inference(self, input_data: ProcessedSynapse) -> Tuple[float, str]:
|
| 112 |
+
"""
|
| 113 |
+
run inference using the MLBaseModel
|
| 114 |
+
:param input_data: synapse from the validator
|
| 115 |
+
:return: the predicted sale price and date
|
| 116 |
+
"""
|
| 117 |
+
input_tensor = self._preprocess_input(input_data)
|
| 118 |
+
|
| 119 |
+
with torch.no_grad():
|
| 120 |
+
prediction = self.model(input_tensor)
|
| 121 |
+
predicted_sale_price, predicted_days_on_market = prediction[0].numpy()
|
| 122 |
+
predicted_days_on_market = math.floor(predicted_days_on_market)
|
| 123 |
+
predicted_sale_date = self._sale_date_predictor(input_data['days_on_market'], predicted_days_on_market)
|
| 124 |
+
|
| 125 |
+
print(f"Predicted Sale Price: ${predicted_sale_price:.2f}")
|
| 126 |
+
print(f"Predicted Sale Date: {predicted_sale_date} ")
|
| 127 |
+
|
| 128 |
+
return predicted_sale_price, predicted_sale_date.strftime("%Y-%m-%d")
|
| 129 |
+
|
| 130 |
+
def _sale_date_predictor(self, days_on_market: int, predicted_days_on_market: int) -> datetime.date:
|
| 131 |
+
"""
|
| 132 |
+
convert predicted days on market to a sale date
|
| 133 |
+
:param days_on_market: number of days this home has been on the market
|
| 134 |
+
:param predicted_days_on_market: the predicted number of days for this home on the market
|
| 135 |
+
:return: the predicted sale date
|
| 136 |
+
"""
|
| 137 |
+
if days_on_market < predicted_days_on_market:
|
| 138 |
+
days_until_sale = predicted_days_on_market - days_on_market
|
| 139 |
+
sale_date = datetime.date.today() + datetime.timedelta(days=days_until_sale)
|
| 140 |
+
return sale_date
|
| 141 |
+
else:
|
| 142 |
+
return datetime.date.today() + datetime.timedelta(days=1)
|
| 143 |
+
|
| 144 |
+
def _preprocess_input(self, data: ProcessedSynapse) -> torch.tensor:
|
| 145 |
+
"""
|
| 146 |
+
preprocess the input for inference
|
| 147 |
+
:param data: synapse from the validator
|
| 148 |
+
:return: tensor representing the synapse
|
| 149 |
+
"""
|
| 150 |
+
df = pd.DataFrame([data])
|
| 151 |
+
default_beds = 3
|
| 152 |
+
default_sqft = 1500.0
|
| 153 |
+
default_property_type = '6'
|
| 154 |
+
df['beds'] = df['beds'].fillna(default_beds)
|
| 155 |
+
df['sqft'] = pd.to_numeric(df['sqft'], errors='coerce').fillna(default_sqft)
|
| 156 |
+
df['property_type'] = df['property_type'].fillna(default_property_type)
|
| 157 |
+
df['property_type'] = df['property_type'].astype(int)
|
| 158 |
+
df[['sqft', 'price']] = self.scaler.transform(df[['sqft', 'price']])
|
| 159 |
+
X = df[['beds', 'sqft', 'property_type', 'price']]
|
| 160 |
+
input_tensor = torch.tensor(X.values, dtype=torch.float32)
|
| 161 |
+
return input_tensor
|