Update app.py
Browse files
app.py
CHANGED
|
@@ -3,12 +3,6 @@
|
|
| 3 |
# PROVIDER=hf_model (default) -> calls HF Inference API for K2 (recommended for demo)
|
| 4 |
# PROVIDER=local -> loads model with transformers (requires GPU Space)
|
| 5 |
# PROVIDER=stub -> offline canned answers
|
| 6 |
-
#
|
| 7 |
-
# Space Secrets / Variables to set:
|
| 8 |
-
# HF_TOKEN -> your Hugging Face token (Read + Inference permissions)
|
| 9 |
-
# MODEL_ID -> default: MBZUAI-IFM/K2-Think-SFT (fallback: LLM360/K2-Think)
|
| 10 |
-
# PROVIDER -> "hf_model" | "local" | "stub"
|
| 11 |
-
# HF_HUB_DISABLE_TELEMETRY=1 (optional)
|
| 12 |
|
| 13 |
import os, time, json, random
|
| 14 |
import requests
|
|
@@ -19,7 +13,7 @@ PROVIDER = os.getenv("PROVIDER", "hf_model").strip()
|
|
| 19 |
MODEL_ID = os.getenv("MODEL_ID", "MBZUAI-IFM/K2-Think-SFT").strip()
|
| 20 |
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
|
| 21 |
|
| 22 |
-
# --------
|
| 23 |
def _get(url, params=None, headers=None, timeout=12, retries=2, backoff=1.6):
|
| 24 |
for i in range(retries + 1):
|
| 25 |
try:
|
|
@@ -31,6 +25,7 @@ def _get(url, params=None, headers=None, timeout=12, retries=2, backoff=1.6):
|
|
| 31 |
raise
|
| 32 |
time.sleep((backoff ** i) + random.random() * 0.25)
|
| 33 |
|
|
|
|
| 34 |
def geocode_city(city:str):
|
| 35 |
r = _get("https://nominatim.openstreetmap.org/search",
|
| 36 |
params={"q": city, "format": "json", "limit": 1},
|
|
@@ -40,6 +35,7 @@ def geocode_city(city:str):
|
|
| 40 |
raise RuntimeError("City not found")
|
| 41 |
return {"lat": float(j[0]["lat"]), "lon": float(j[0]["lon"]), "name": j[0]["display_name"]}
|
| 42 |
|
|
|
|
| 43 |
def fetch_open_meteo(lat, lon):
|
| 44 |
r = _get("https://api.open-meteo.com/v1/forecast", params={
|
| 45 |
"latitude": lat, "longitude": lon,
|
|
@@ -49,30 +45,32 @@ def fetch_open_meteo(lat, lon):
|
|
| 49 |
})
|
| 50 |
return r.json()
|
| 51 |
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
| 65 |
|
| 66 |
def fetch_factors(lat, lon):
|
| 67 |
wx = fetch_open_meteo(lat, lon)
|
| 68 |
-
cur = wx.get("current", {})
|
| 69 |
factors = {
|
| 70 |
"temp_c": cur.get("temperature_2m"),
|
| 71 |
"rh": cur.get("relative_humidity_2m"),
|
| 72 |
"wind_kmh": cur.get("wind_speed_10m"),
|
| 73 |
"precip_mm": cur.get("precipitation"),
|
| 74 |
"uv": cur.get("uv_index"),
|
| 75 |
-
"pm25":
|
| 76 |
}
|
| 77 |
return {"factors": factors, "raw": wx}
|
| 78 |
|
|
@@ -120,7 +118,6 @@ def call_stub(_prompt:str)->str:
|
|
| 120 |
})
|
| 121 |
|
| 122 |
def call_hf_model(prompt:str)->str:
|
| 123 |
-
# Hugging Face Inference API (serverless).
|
| 124 |
from huggingface_hub import InferenceClient
|
| 125 |
client = InferenceClient(model=MODEL_ID, token=(HF_TOKEN or None))
|
| 126 |
out = client.text_generation(
|
|
@@ -139,10 +136,9 @@ def _ensure_local_loaded():
|
|
| 139 |
if _local_loaded:
|
| 140 |
return
|
| 141 |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
| 142 |
-
import torch
|
| 143 |
bnb_cfg = BitsAndBytesConfig(
|
| 144 |
load_in_4bit=True,
|
| 145 |
-
bnb_4bit_compute_dtype=
|
| 146 |
bnb_4bit_use_double_quant=True,
|
| 147 |
bnb_4bit_quant_type="nf4",
|
| 148 |
)
|
|
@@ -158,7 +154,6 @@ def _ensure_local_loaded():
|
|
| 158 |
|
| 159 |
def call_local(prompt:str)->str:
|
| 160 |
_ensure_local_loaded()
|
| 161 |
-
import torch
|
| 162 |
if hasattr(tokenizer, "apply_chat_template"):
|
| 163 |
messages = [{"role":"user","content":prompt}]
|
| 164 |
inputs = tokenizer.apply_chat_template(messages, tokenize=True, return_tensors="pt").to(model.device)
|
|
@@ -193,7 +188,6 @@ def reason_answer(loc, coords, factors, query):
|
|
| 193 |
else:
|
| 194 |
raw = call_stub(prompt)
|
| 195 |
|
| 196 |
-
# Extract largest JSON block
|
| 197 |
start, end = raw.find("{"), raw.rfind("}")
|
| 198 |
if start == -1 or end == -1:
|
| 199 |
return {
|
|
@@ -247,10 +241,9 @@ demo = gr.Interface(
|
|
| 247 |
title="ClimaMind — K2-Think + Live Climate Data",
|
| 248 |
description="Provider = hf_model (Inference API) | local (GPU Space) | stub (offline). Configure env in Space settings.",
|
| 249 |
allow_flagging="never",
|
| 250 |
-
concurrency_limit=2,
|
| 251 |
)
|
| 252 |
|
| 253 |
-
# Optional queue for request buffering (no deprecated args)
|
| 254 |
demo.queue(max_size=8)
|
| 255 |
|
| 256 |
if __name__ == "__main__":
|
|
|
|
| 3 |
# PROVIDER=hf_model (default) -> calls HF Inference API for K2 (recommended for demo)
|
| 4 |
# PROVIDER=local -> loads model with transformers (requires GPU Space)
|
| 5 |
# PROVIDER=stub -> offline canned answers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
import os, time, json, random
|
| 8 |
import requests
|
|
|
|
| 13 |
MODEL_ID = os.getenv("MODEL_ID", "MBZUAI-IFM/K2-Think-SFT").strip()
|
| 14 |
HF_TOKEN = os.getenv("HF_TOKEN", "").strip()
|
| 15 |
|
| 16 |
+
# -------- HTTP helper --------
|
| 17 |
def _get(url, params=None, headers=None, timeout=12, retries=2, backoff=1.6):
|
| 18 |
for i in range(retries + 1):
|
| 19 |
try:
|
|
|
|
| 25 |
raise
|
| 26 |
time.sleep((backoff ** i) + random.random() * 0.25)
|
| 27 |
|
| 28 |
+
# -------- Geocode (free) --------
|
| 29 |
def geocode_city(city:str):
|
| 30 |
r = _get("https://nominatim.openstreetmap.org/search",
|
| 31 |
params={"q": city, "format": "json", "limit": 1},
|
|
|
|
| 35 |
raise RuntimeError("City not found")
|
| 36 |
return {"lat": float(j[0]["lat"]), "lon": float(j[0]["lon"]), "name": j[0]["display_name"]}
|
| 37 |
|
| 38 |
+
# -------- Weather (Open-Meteo, free) --------
|
| 39 |
def fetch_open_meteo(lat, lon):
|
| 40 |
r = _get("https://api.open-meteo.com/v1/forecast", params={
|
| 41 |
"latitude": lat, "longitude": lon,
|
|
|
|
| 45 |
})
|
| 46 |
return r.json()
|
| 47 |
|
| 48 |
+
# -------- PM2.5 (Open-Meteo Air-Quality, free; replaces OpenAQ v3 which now needs a key) --------
|
| 49 |
+
def fetch_pm25(lat, lon):
|
| 50 |
+
try:
|
| 51 |
+
r = _get("https://air-quality-api.open-meteo.com/v1/air-quality", params={
|
| 52 |
+
"latitude": lat, "longitude": lon, "hourly": "pm2_5", "timezone": "auto"
|
| 53 |
+
}, headers={"User-Agent": "climamind-space"})
|
| 54 |
+
j = r.json()
|
| 55 |
+
# take the most recent hour
|
| 56 |
+
hourly = j.get("hourly", {})
|
| 57 |
+
values = hourly.get("pm2_5") or []
|
| 58 |
+
if values:
|
| 59 |
+
return values[-1]
|
| 60 |
+
except Exception:
|
| 61 |
+
pass
|
| 62 |
+
return None # graceful fallback
|
| 63 |
|
| 64 |
def fetch_factors(lat, lon):
|
| 65 |
wx = fetch_open_meteo(lat, lon)
|
| 66 |
+
cur = wx.get("current", {}) or {}
|
| 67 |
factors = {
|
| 68 |
"temp_c": cur.get("temperature_2m"),
|
| 69 |
"rh": cur.get("relative_humidity_2m"),
|
| 70 |
"wind_kmh": cur.get("wind_speed_10m"),
|
| 71 |
"precip_mm": cur.get("precipitation"),
|
| 72 |
"uv": cur.get("uv_index"),
|
| 73 |
+
"pm25": fetch_pm25(lat, lon),
|
| 74 |
}
|
| 75 |
return {"factors": factors, "raw": wx}
|
| 76 |
|
|
|
|
| 118 |
})
|
| 119 |
|
| 120 |
def call_hf_model(prompt:str)->str:
|
|
|
|
| 121 |
from huggingface_hub import InferenceClient
|
| 122 |
client = InferenceClient(model=MODEL_ID, token=(HF_TOKEN or None))
|
| 123 |
out = client.text_generation(
|
|
|
|
| 136 |
if _local_loaded:
|
| 137 |
return
|
| 138 |
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
|
|
|
|
| 139 |
bnb_cfg = BitsAndBytesConfig(
|
| 140 |
load_in_4bit=True,
|
| 141 |
+
bnb_4bit_compute_dtype="bfloat16",
|
| 142 |
bnb_4bit_use_double_quant=True,
|
| 143 |
bnb_4bit_quant_type="nf4",
|
| 144 |
)
|
|
|
|
| 154 |
|
| 155 |
def call_local(prompt:str)->str:
|
| 156 |
_ensure_local_loaded()
|
|
|
|
| 157 |
if hasattr(tokenizer, "apply_chat_template"):
|
| 158 |
messages = [{"role":"user","content":prompt}]
|
| 159 |
inputs = tokenizer.apply_chat_template(messages, tokenize=True, return_tensors="pt").to(model.device)
|
|
|
|
| 188 |
else:
|
| 189 |
raw = call_stub(prompt)
|
| 190 |
|
|
|
|
| 191 |
start, end = raw.find("{"), raw.rfind("}")
|
| 192 |
if start == -1 or end == -1:
|
| 193 |
return {
|
|
|
|
| 241 |
title="ClimaMind — K2-Think + Live Climate Data",
|
| 242 |
description="Provider = hf_model (Inference API) | local (GPU Space) | stub (offline). Configure env in Space settings.",
|
| 243 |
allow_flagging="never",
|
| 244 |
+
concurrency_limit=2,
|
| 245 |
)
|
| 246 |
|
|
|
|
| 247 |
demo.queue(max_size=8)
|
| 248 |
|
| 249 |
if __name__ == "__main__":
|