File size: 1,592 Bytes
fc41845
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import os
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
import joblib
import pandas as pd
import uvicorn

app = FastAPI(title="Morocco Real Estate API")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Load Model
MODEL_PATH = "morocco_re_model_pro.joblib"
model = None
if os.path.exists(MODEL_PATH):
    model = joblib.load(MODEL_PATH)

class PropertyFeatures(BaseModel):
    City: str
    Neighborhood: str
    Type: str
    Surface: float
    Rooms: int
    Bedrooms: int
    Standing: str
    Residency: str
    Orientation: str
    View: str
    Condition: str
    Floor: int
    Lift: int
    Pool: int
    Garden: int
    Parking_Spots: int
    Proximity_Tram: int
    Proximity_University: int
    Proximity_Mosque: int

@app.post("/predict")
async def predict_price(features: PropertyFeatures):
    if model is None:
        raise HTTPException(status_code=500, detail="Model not loaded")
    
    input_data = pd.DataFrame([features.dict()])
    prediction = model.predict(input_data)[0]
    
    return {"estimated_price": round(prediction, 2), "currency": "MAD"}

# Serve Frontend
if os.path.exists("static"):
    app.mount("/", StaticFiles(directory="static", html=True), name="static")

if __name__ == "__main__":
    # Hugging Face Spaces usually uses port 7860
    port = int(os.environ.get("PORT", 8000))
    uvicorn.run(app, host="0.0.0.0", port=port)