Spaces:
Configuration error
Configuration error
File size: 10,016 Bytes
bc32b90 | 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | import json
import os
import pickle
from pathlib import Path
import gradio as gr
import numpy as np
import pandas as pd
import anthropic
MODEL_PATH = Path("random_forest_regression.pkl")
DATA_PATH = Path("bfs_municipality_and_tax_data.csv")
# Hugging Face Secrets / local environment variables
# Required secret on Hugging Face: ANTHROPIC_API_KEY
LLM_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
LLM_MODEL = os.getenv("ANTHROPIC_MODEL", "claude-sonnet-4-5")
def load_model_and_data():
if not MODEL_PATH.exists():
raise FileNotFoundError(
f"Missing model file: {MODEL_PATH}. Upload random_forest_regression.pkl to the same folder as app.py."
)
if not DATA_PATH.exists():
raise FileNotFoundError(
f"Missing data file: {DATA_PATH}. Upload bfs_municipality_and_tax_data.csv to the same folder as app.py."
)
with open(MODEL_PATH, "rb") as model_file:
loaded_model = pickle.load(model_file)
bfs_data = pd.read_csv(DATA_PATH, sep=",", encoding="utf-8")
bfs_data["tax_income"] = (
bfs_data["tax_income"].astype(str).str.replace("'", "", regex=False).astype(float)
)
bfs_data["emp"] = bfs_data["emp"].fillna(bfs_data["emp"].median())
return loaded_model, bfs_data
model, df_bfs_data = load_model_and_data()
town_to_row = {
str(row["bfs_name"]).strip().lower(): row
for _, row in df_bfs_data.iterrows()
}
valid_towns = list(df_bfs_data["bfs_name"].sort_values().unique())
def match_town(user_town: str):
"""Match user town text to the canonical bfs_name in the CSV."""
if not user_town:
return None
query = str(user_town).strip().lower()
if not query:
return None
# 1) Exact lower-case match
if query in town_to_row:
return town_to_row[query]["bfs_name"]
# 2) Relaxed contains matching
matches = []
for town in valid_towns:
town_lower = str(town).strip().lower()
if query == town_lower:
return town
if query in town_lower or town_lower in query:
matches.append(town)
if len(matches) == 1:
return matches[0]
return None
def call_llm_json(system_prompt: str, user_prompt: str) -> str:
"""Call Anthropic Claude and require a JSON object response."""
if not LLM_API_KEY:
raise RuntimeError(
"ANTHROPIC_API_KEY fehlt. Bitte unter Hugging Face Settings -> Variables and secrets hinzufügen."
)
client = anthropic.Anthropic(api_key=LLM_API_KEY)
message = client.messages.create(
model=LLM_MODEL,
max_tokens=512,
system=system_prompt,
messages=[
{"role": "user", "content": user_prompt},
],
)
return message.content[0].text
def parse_json_response(raw: str, required_keys: tuple) -> dict:
cleaned = (raw or "").strip()
# Remove markdown code fences if present
if cleaned.startswith("```"):
cleaned = cleaned.split("```")[1]
if cleaned.startswith("json"):
cleaned = cleaned[4:]
cleaned = cleaned.strip()
if not cleaned:
raise ValueError("LLM hat eine leere Antwort zurückgegeben.")
try:
parsed = json.loads(cleaned)
except json.JSONDecodeError as exc:
raise ValueError(
f"LLM hat kein gültiges JSON zurückgegeben. Erhalten: {cleaned[:300]}"
) from exc
missing_keys = [key for key in required_keys if key not in parsed]
if missing_keys:
raise ValueError(
f"JSON fehlt folgende Schlüssel: {', '.join(missing_keys)}."
)
return parsed
def extract_preferences(user_text: str) -> dict:
"""Extract rooms, area_m2 and town from German free text using an LLM."""
if not user_text or not user_text.strip():
raise ValueError(
"Bitte gib einen Wohnungswunsch mit Zimmeranzahl, Fläche und Ort ein."
)
system_prompt = """Du bist ein Extraktionssystem für Schweizer Wohnungswünsche.
Extrahiere aus dem Nutzereingabetext exakt diese Informationen:
- rooms: Anzahl Zimmer als Zahl, zum Beispiel 3.5
- area_m2: Wohnfläche in Quadratmetern als Zahl, zum Beispiel 85
- town: Schweizer Gemeinde / Ort als String, zum Beispiel "Winterthur"
Antworte ausschliesslich mit gültigem JSON.
Keine Markdown-Codeblöcke.
Keine Erklärungen.
Keine zusätzlichen Schlüssel.
Wenn ein Wert fehlt, verwende null.
Erwartetes Format:
{"rooms": 3.5, "area_m2": 85, "town": "Winterthur"}"""
user_prompt = f"""Extrahiere rooms, area_m2 und town aus folgendem deutschen Wohnungswunsch:
{user_text}"""
raw = call_llm_json(system_prompt, user_prompt)
parsed = parse_json_response(raw, required_keys=("rooms", "area_m2", "town"))
rooms = parsed["rooms"]
area_m2 = parsed["area_m2"]
town = parsed["town"]
if rooms is None or area_m2 is None or town is None:
raise ValueError("Bitte gib Zimmeranzahl, Wohnfläche in m2 und Ort an.")
try:
rooms = float(rooms)
area_m2 = float(area_m2)
except (TypeError, ValueError) as exc:
raise ValueError(
"Zimmeranzahl und Wohnfläche müssen als Zahlen erkannt werden."
) from exc
if rooms <= 0:
raise ValueError("Die Zimmeranzahl muss grösser als 0 sein.")
if area_m2 <= 0:
raise ValueError("Die Wohnfläche muss grösser als 0 sein.")
canonical_town = match_town(town)
if canonical_town is None:
raise ValueError(
f"Ort '{town}' wurde nicht eindeutig in den BFS-Daten gefunden. "
"Bitte verwende einen gültigen Schweizer Gemeindenamen."
)
return {
"rooms": rooms,
"area_m2": area_m2,
"town": canonical_town,
}
def predict_apartment_price(rooms: float, area_m2: float, town: str) -> float:
"""Predict monthly rent with exactly these model features:
[rooms, area_m2, pop, pop_dens, frg_pct, emp, tax_income]
"""
canonical_town = match_town(town)
if canonical_town is None:
raise ValueError(f"Ort '{town}' wurde nicht gefunden.")
row = town_to_row[canonical_town.lower()]
features = np.array(
[[
float(rooms),
float(area_m2),
float(row["pop"]),
float(row["pop_dens"]),
float(row["frg_pct"]),
float(row["emp"]),
float(row["tax_income"]),
]]
)
prediction = model.predict(features)[0]
return round(float(prediction), 2)
def generate_explanation(preferences: dict, prediction: float) -> str:
"""Generate a concise German explanation with one uncertainty note using an LLM."""
system_prompt = """Du bist ein hilfreicher Assistent für Wohnungsmietpreise in der Schweiz.
Deine Aufgabe:
Erkläre die gegebene Modellschätzung kurz und verständlich auf Deutsch.
Wichtige Regeln:
- Verwende die angegebene Prediction.
- Berechne keinen neuen Preis.
- Erfinde keine zusätzlichen Daten.
- Erwähne Zimmeranzahl, Fläche und Ort.
- Füge einen kurzen Unsicherheitshinweis hinzu.
- Sage, dass es sich um eine Schätzung handelt.
- Antworte ausschliesslich mit gültigem JSON ohne Markdown.
- Verwende exakt den Schlüssel "answer".
Erwartetes Format:
{"answer": "Für eine 3.5-Zimmer-Wohnung mit 85 m2 in Winterthur schätzt das Modell die Monatsmiete auf rund 2145 CHF. Die Schätzung ist unsicher, weil Faktoren wie Zustand, Mikrolage und Ausstattung nicht direkt berücksichtigt werden."}"""
user_prompt = f"""Wohnungsdaten:
{json.dumps(preferences, ensure_ascii=False)}
Modellschätzung der monatlichen Miete in CHF:
{prediction}
Formuliere eine kurze deutsche Antwort."""
raw = call_llm_json(system_prompt, user_prompt)
parsed = parse_json_response(raw, required_keys=("answer",))
answer = parsed["answer"]
if not answer:
raise ValueError("LLM Erklärung war leer.")
return str(answer)
def run_pipeline(user_text: str):
"""End-to-end app pipeline."""
try:
preferences = extract_preferences(user_text)
prediction = predict_apartment_price(
rooms=preferences["rooms"],
area_m2=preferences["area_m2"],
town=preferences["town"],
)
final_answer = generate_explanation(
preferences=preferences,
prediction=prediction,
)
return preferences, prediction, final_answer
except Exception as exc:
return (
{
"error": str(exc),
"hint": "Bitte gib Zimmeranzahl, Wohnfläche in m2 und einen Schweizer Ort an.",
},
None,
f"Fehler: {exc}",
)
with gr.Blocks(title="🏠 Schweizer Wohnungspreisschätzer") as demo:
gr.Markdown(
"""
# 🏠 Schweizer Wohnungspreisschätzer
Beschreibe deinen **Wohnungswunsch auf Deutsch**.
**Beispiele:**
- *„Ich suche eine 3.5-Zimmer-Wohnung mit etwa 85 m2 in Winterthur."*
- *„Wie viel kostet eine 2-Zimmer-Wohnung mit 55 m2 in Zürich?"*
- *„Ich brauche eine 4.5-Zimmer-Wohnung mit 110 m2 in Bern."*
"""
)
user_text = gr.Textbox(
label="Wohnungswunsch",
lines=3,
placeholder="Beschreibe Zimmer, Fläche in m2 und Ort auf Deutsch...",
)
submit = gr.Button("🔍 Schätzen", variant="primary")
with gr.Row():
extracted = gr.JSON(label="📋 Extrahierte Eingaben")
price = gr.Number(label="💰 Geschätzte Monatsmiete (CHF)")
response = gr.Textbox(label="💬 Erklärung", lines=5)
submit.click(
fn=run_pipeline,
inputs=[user_text],
outputs=[extracted, price, response],
)
gr.Markdown(
"""
---
*Hinweis: Diese Schätzung basiert auf einem Random-Forest-Modell mit BFS-Gemeindedaten.
Sie dient nur zur Orientierung und ersetzt keine professionelle Mietberatung.*
"""
)
if __name__ == "__main__":
demo.launch()
|