szili2011's picture
Update app.py
993bb5b verified
raw
history blame
2.87 kB
# app.py - The code that runs on the Hugging Face server
import gradio as gr
import joblib
import pandas as pd
import os
# --- Load the Model and Columns ONCE when the app starts ---
# This is efficient because the model stays loaded in memory on the server.
try:
model = joblib.load("housing_model.joblib")
model_columns = joblib.load("model_columns.joblib")
except FileNotFoundError:
# Handle the case where files are in a subdirectory (sometimes happens on HF)
model = joblib.load(os.path.join(os.path.dirname(__file__), "housing_model.joblib"))
model_columns = joblib.load(os.path.join(os.path.dirname(__file__), "model_columns.joblib"))
# --- This is the core prediction function ---
def predict_price(sqft, bedrooms, house_age, condition, year_sold, interest_rate, region, sub_type, style, has_garage, has_pool):
# 1. Create a DataFrame from the input data
input_data = {
'SquareFootage': sqft, 'Bedrooms': bedrooms, 'HouseAge': house_age,
'PropertyCondition': condition, 'HasGarage': has_garage, 'HasPool': has_pool,
'YearSold': year_sold, 'InterestRate': interest_rate,
'Region': region, 'SubType': sub_type, 'ArchitecturalStyle': style
}
input_df = pd.DataFrame([input_data])
# 2. Preprocess the data exactly like in training
input_processed = pd.get_dummies(input_df)
final_input = input_processed.reindex(columns=model_columns, fill_value=0)
# 3. Make the prediction
predicted_price = model.predict(final_input)[0]
# 4. Return a nicely formatted string
return f"${predicted_price:,.0f}"
# --- Create the Gradio Interface ---
# This automatically creates a simple web UI and a usable API endpoint.
demo = gr.Interface(
fn=predict_price,
inputs=[
gr.Number(label="Square Footage", value=2500),
gr.Number(label="Bedrooms", value=4),
gr.Number(label="House Age (years)", value=15),
gr.Slider(label="Property Condition", minimum=1, maximum=10, step=1, value=8),
gr.Number(label="Year Sold", value=2024),
gr.Number(label="Interest Rate (%)", value=5.5),
gr.Radio(['Sunbelt', 'Pacific Northwest', 'Rust Belt', 'New England', 'Mountain West'], label="Region", value="Sunbelt"),
gr.Radio(['Urban', 'Suburban', 'Rural', 'Historic District'], label="Sub-Type", value="Suburban"),
gr.Radio(['Modern', 'Ranch', 'Colonial', 'Craftsman', 'Victorian'], label="Architectural Style", value="Colonial"),
gr.Checkbox(label="Has Garage?", value=True),
gr.Checkbox(label="Has Pool?", value=False)
],
outputs=gr.Textbox(label="Predicted Price"),
title="AI House Price Predictor",
description="Describe a property, and our AI will estimate its market value. Powered by a model trained on 9.2GB of simulated data."
)
# Launch the app
demo.launch()