Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,18 @@
|
|
| 1 |
-
# app.py — Streamlit Frontend (
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import time
|
| 5 |
import requests
|
| 6 |
import streamlit as st
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# ---- container-safe defaults
|
| 9 |
os.environ.setdefault("HOME", "/tmp")
|
| 10 |
os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false")
|
| 11 |
os.environ.setdefault("STREAMLIT_SERVER_HEADLESS", "true")
|
| 12 |
|
| 13 |
-
# ================= Theme
|
| 14 |
try:
|
| 15 |
st._config.set_option("theme.base", "dark")
|
| 16 |
st._config.set_option("theme.primaryColor", "#ff7a1a")
|
|
@@ -20,22 +22,23 @@ try:
|
|
| 20 |
except Exception:
|
| 21 |
pass
|
| 22 |
|
| 23 |
-
# ================= Env & API
|
| 24 |
def _env(k: str) -> str:
|
| 25 |
return (os.getenv(k) or "").strip().strip("'\"")
|
| 26 |
|
| 27 |
-
|
| 28 |
_env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")
|
| 29 |
-
)
|
|
|
|
| 30 |
|
| 31 |
HF_TOKEN = _env("CARDIAG_AI_TOKEN") or _env("AI_LIGHTBOX_TOKEN") or _env("LUXFIT_TOKEN")
|
| 32 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 33 |
|
| 34 |
-
# ================= i18n
|
| 35 |
L = {
|
| 36 |
"en": {
|
| 37 |
"title": "Diag Studio AI — Engine Sound Diagnosis",
|
| 38 |
-
"about": "Upload an engine sound (mp3/wav/ogg) or paste an audio URL. Backend runs fal.ai audio-understanding, then GPT-4o
|
| 39 |
"backend_url": "Backend URL",
|
| 40 |
"lang": "Language",
|
| 41 |
"upload": "Upload audio file",
|
|
@@ -58,15 +61,17 @@ L = {
|
|
| 58 |
"no_backend": "Enter a backend URL (e.g., http://127.0.0.1:7860)",
|
| 59 |
"health_ok": "Backend is reachable.",
|
| 60 |
"health_fail": "Backend not reachable.",
|
| 61 |
-
"upload_hint": "Max ~200 MB; use mp3/wav/ogg.",
|
| 62 |
-
"footer": "Tip: You can also paste a public audio URL.",
|
| 63 |
-
"
|
| 64 |
-
"
|
| 65 |
-
"
|
|
|
|
|
|
|
| 66 |
},
|
| 67 |
"tr": {
|
| 68 |
"title": "Diag Studio AI — Motor Sesi Teşhis",
|
| 69 |
-
"about": "Motor sesini (mp3/wav/ogg) yükleyin veya bir ses URL’si verin. Backend fal.ai
|
| 70 |
"backend_url": "Backend URL",
|
| 71 |
"lang": "Dil",
|
| 72 |
"upload": "Ses dosyası yükle",
|
|
@@ -89,21 +94,23 @@ L = {
|
|
| 89 |
"no_backend": "Bir backend URL girin (örn: http://127.0.0.1:7860)",
|
| 90 |
"health_ok": "Backend erişilebilir.",
|
| 91 |
"health_fail": "Backend’e erişilemedi.",
|
| 92 |
-
"upload_hint": "Varsayılan
|
| 93 |
"footer": "İpucu: Dosya yüklemek istemezseniz herkese açık bir ses URL’si de girebilirsiniz.",
|
| 94 |
-
"
|
| 95 |
-
"
|
| 96 |
-
"
|
|
|
|
|
|
|
| 97 |
}
|
| 98 |
}
|
| 99 |
|
| 100 |
-
# ================= Session State
|
| 101 |
if "lang" not in st.session_state:
|
| 102 |
st.session_state.lang = "tr"
|
| 103 |
if "last_response" not in st.session_state:
|
| 104 |
st.session_state.last_response = None
|
| 105 |
|
| 106 |
-
# ================= UI
|
| 107 |
col1, col2 = st.columns([0.65, 0.35])
|
| 108 |
with col1:
|
| 109 |
st.title(L[st.session_state.lang]["title"])
|
|
@@ -114,41 +121,29 @@ with col2:
|
|
| 114 |
index=(0 if st.session_state.lang == "tr" else 1),
|
| 115 |
key="lang_selector",
|
| 116 |
)
|
| 117 |
-
|
| 118 |
t = L[st.session_state.lang]
|
| 119 |
st.caption(t["about"])
|
| 120 |
|
| 121 |
-
backend_default =
|
| 122 |
api_base = st.text_input(t["backend_url"], value=backend_default)
|
| 123 |
|
| 124 |
-
# Health check
|
| 125 |
-
hc1, _ = st.columns([0.28, 0.72])
|
| 126 |
-
with hc1:
|
| 127 |
-
if st.button("🔄 Health"):
|
| 128 |
-
try:
|
| 129 |
-
r = requests.get(f"{api_base}/health", headers=HEADERS, timeout=10)
|
| 130 |
-
st.success(t["health_ok"] if r.ok else t["health_fail"])
|
| 131 |
-
except Exception:
|
| 132 |
-
st.error(t["health_fail"])
|
| 133 |
-
|
| 134 |
-
st.markdown("---")
|
| 135 |
-
|
| 136 |
-
# Upload or URL input
|
| 137 |
-
st.write(t["upload_hint"])
|
| 138 |
-
file = st.file_uploader(t["upload"], type=["mp3", "wav", "ogg"])
|
| 139 |
-
st.write(f"**{t['or']}**")
|
| 140 |
-
audio_url = st.text_input(t["paste_url"], value="", placeholder="https://...")
|
| 141 |
-
|
| 142 |
with st.expander(t["adv"], expanded=False):
|
| 143 |
detailed = st.checkbox(t["detailed"], value=True)
|
| 144 |
use_data_uri = st.checkbox(t["use_data_uri"], value=True)
|
| 145 |
openai_model = st.text_input(t["model"], value="gpt-4o")
|
| 146 |
-
prompt_override = st.text_area(
|
| 147 |
-
|
| 148 |
-
)
|
|
|
|
| 149 |
st.caption(t["footer"])
|
| 150 |
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
go = c1.button(f"▶ {t['analyze']}", type="primary")
|
| 153 |
reset = c2.button(f"↩ {t['reset']}")
|
| 154 |
|
|
@@ -156,25 +151,50 @@ if reset:
|
|
| 156 |
st.session_state.last_response = None
|
| 157 |
st.rerun()
|
| 158 |
|
| 159 |
-
# ============== HTTP
|
| 160 |
-
def
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
-
def
|
| 167 |
-
url = f"{
|
| 168 |
-
|
|
|
|
|
|
|
| 169 |
"openai_model": openai_model or "gpt-4o",
|
| 170 |
}
|
| 171 |
if prompt_override.strip():
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
# Attempt #1: user settings
|
| 175 |
-
data = dict(base_data)
|
| 176 |
-
data["detailed_analysis"] = "true" if detailed else "false"
|
| 177 |
-
data["use_data_uri"] = "true" if use_data_uri else "false"
|
| 178 |
|
| 179 |
files = None
|
| 180 |
if _file is not None:
|
|
@@ -183,106 +203,100 @@ def post_analyze_resilient(_api_base: str, _headers: dict, _file, _audio_url: st
|
|
| 183 |
elif _audio_url.strip():
|
| 184 |
data["audio_url"] = _audio_url.strip()
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
try:
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
return r3.json()
|
| 209 |
-
except Exception as e3:
|
| 210 |
-
# Surface last error
|
| 211 |
-
raise RuntimeError(f"All attempts failed. Last error: {e3}") from e3
|
| 212 |
|
| 213 |
-
# ============== Submission ==============
|
| 214 |
if go:
|
| 215 |
if not api_base:
|
| 216 |
st.error(t["no_backend"])
|
| 217 |
elif not file and not audio_url.strip():
|
| 218 |
st.error(t["upload"])
|
| 219 |
else:
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
st.error(f"Request failed: {e}")
|
| 227 |
-
# Try to fetch raw error body if available
|
| 228 |
-
try:
|
| 229 |
-
# If the exception carried a response, print it
|
| 230 |
-
if hasattr(e, "response") and e.response is not None:
|
| 231 |
-
st.code(e.response.text, language="json")
|
| 232 |
-
except Exception:
|
| 233 |
-
pass
|
| 234 |
-
st.stop()
|
| 235 |
|
| 236 |
-
# ==============
|
| 237 |
res = st.session_state.last_response
|
| 238 |
if res:
|
| 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 |
-
col_a.error(f"{t['download_summary']} ✖")
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
col_b.error(f"{t['download_parsed']} ✖")
|
| 279 |
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
col_c.error(f"{t['download_raw']} ✖")
|
| 287 |
|
| 288 |
-
st.caption("© 2025 Diag Studio AI — Streamlit frontend")
|
|
|
|
| 1 |
+
# app.py — Streamlit Frontend (robust retries + warmup)
|
| 2 |
import os
|
| 3 |
import json
|
| 4 |
import time
|
| 5 |
import requests
|
| 6 |
import streamlit as st
|
| 7 |
+
from requests.adapters import HTTPAdapter
|
| 8 |
+
from urllib3.util.retry import Retry
|
| 9 |
|
| 10 |
# ---- container-safe defaults
|
| 11 |
os.environ.setdefault("HOME", "/tmp")
|
| 12 |
os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false")
|
| 13 |
os.environ.setdefault("STREAMLIT_SERVER_HEADLESS", "true")
|
| 14 |
|
| 15 |
+
# ================= Theme (no extra files)
|
| 16 |
try:
|
| 17 |
st._config.set_option("theme.base", "dark")
|
| 18 |
st._config.set_option("theme.primaryColor", "#ff7a1a")
|
|
|
|
| 22 |
except Exception:
|
| 23 |
pass
|
| 24 |
|
| 25 |
+
# ================= Env & API pickers
|
| 26 |
def _env(k: str) -> str:
|
| 27 |
return (os.getenv(k) or "").strip().strip("'\"")
|
| 28 |
|
| 29 |
+
API_BASE_ENV = (
|
| 30 |
_env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")
|
| 31 |
+
)
|
| 32 |
+
API_BASE_ENV = API_BASE_ENV.rstrip("/") if API_BASE_ENV else ""
|
| 33 |
|
| 34 |
HF_TOKEN = _env("CARDIAG_AI_TOKEN") or _env("AI_LIGHTBOX_TOKEN") or _env("LUXFIT_TOKEN")
|
| 35 |
HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 36 |
|
| 37 |
+
# ================= i18n
|
| 38 |
L = {
|
| 39 |
"en": {
|
| 40 |
"title": "Diag Studio AI — Engine Sound Diagnosis",
|
| 41 |
+
"about": "Upload an engine sound (mp3/wav/ogg) or paste an audio URL. Backend runs fal.ai audio-understanding with detailed analysis, then summarizes with GPT-4o.",
|
| 42 |
"backend_url": "Backend URL",
|
| 43 |
"lang": "Language",
|
| 44 |
"upload": "Upload audio file",
|
|
|
|
| 61 |
"no_backend": "Enter a backend URL (e.g., http://127.0.0.1:7860)",
|
| 62 |
"health_ok": "Backend is reachable.",
|
| 63 |
"health_fail": "Backend not reachable.",
|
| 64 |
+
"upload_hint": "Max ~200 MB per Streamlit docs; use mp3/wav/ogg.",
|
| 65 |
+
"footer": "Tip: You can also paste a public audio URL if you don’t want to upload the file.",
|
| 66 |
+
"auto_retry": "Auto-retry on 429/500/502/503/504",
|
| 67 |
+
"warmup": "Warm up backend before analysis",
|
| 68 |
+
"max_wait": "Max total wait (sec) for retries",
|
| 69 |
+
"warming": "Warming up backend…",
|
| 70 |
+
"analyzing": "Analyzing…"
|
| 71 |
},
|
| 72 |
"tr": {
|
| 73 |
"title": "Diag Studio AI — Motor Sesi Teşhis",
|
| 74 |
+
"about": "Motor sesini (mp3/wav/ogg) yükleyin veya bir ses URL’si verin. Backend fal.ai detailed analysis ile çalışır, sonra GPT-4o özetler.",
|
| 75 |
"backend_url": "Backend URL",
|
| 76 |
"lang": "Dil",
|
| 77 |
"upload": "Ses dosyası yükle",
|
|
|
|
| 94 |
"no_backend": "Bir backend URL girin (örn: http://127.0.0.1:7860)",
|
| 95 |
"health_ok": "Backend erişilebilir.",
|
| 96 |
"health_fail": "Backend’e erişilemedi.",
|
| 97 |
+
"upload_hint": "Varsayılan yükleme sınırı ~200 MB; mp3/wav/ogg kullanın.",
|
| 98 |
"footer": "İpucu: Dosya yüklemek istemezseniz herkese açık bir ses URL’si de girebilirsiniz.",
|
| 99 |
+
"auto_retry": "429/500/502/503/504 için otomatik yeniden dene",
|
| 100 |
+
"warmup": "Analizden önce backend’i ısıt",
|
| 101 |
+
"max_wait": "Retry için maksimum toplam bekleme (sn)",
|
| 102 |
+
"warming": "Backend ısıtılıyor…",
|
| 103 |
+
"analyzing": "Analiz ediliyor…"
|
| 104 |
}
|
| 105 |
}
|
| 106 |
|
| 107 |
+
# ================= Session State
|
| 108 |
if "lang" not in st.session_state:
|
| 109 |
st.session_state.lang = "tr"
|
| 110 |
if "last_response" not in st.session_state:
|
| 111 |
st.session_state.last_response = None
|
| 112 |
|
| 113 |
+
# ================= UI
|
| 114 |
col1, col2 = st.columns([0.65, 0.35])
|
| 115 |
with col1:
|
| 116 |
st.title(L[st.session_state.lang]["title"])
|
|
|
|
| 121 |
index=(0 if st.session_state.lang == "tr" else 1),
|
| 122 |
key="lang_selector",
|
| 123 |
)
|
|
|
|
| 124 |
t = L[st.session_state.lang]
|
| 125 |
st.caption(t["about"])
|
| 126 |
|
| 127 |
+
backend_default = API_BASE_ENV or "https://renderfy-diagstudio-ai-backend.hf.space"
|
| 128 |
api_base = st.text_input(t["backend_url"], value=backend_default)
|
| 129 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
with st.expander(t["adv"], expanded=False):
|
| 131 |
detailed = st.checkbox(t["detailed"], value=True)
|
| 132 |
use_data_uri = st.checkbox(t["use_data_uri"], value=True)
|
| 133 |
openai_model = st.text_input(t["model"], value="gpt-4o")
|
| 134 |
+
prompt_override = st.text_area(t["prompt"], value="", height=120)
|
| 135 |
+
auto_retry = st.checkbox(t["auto_retry"], value=True)
|
| 136 |
+
warmup = st.checkbox(t["warmup"], value=True)
|
| 137 |
+
max_wait = st.slider(t["max_wait"], 10, 180, 60, step=10)
|
| 138 |
st.caption(t["footer"])
|
| 139 |
|
| 140 |
+
st.markdown("---")
|
| 141 |
+
st.write(t["upload_hint"])
|
| 142 |
+
file = st.file_uploader(t["upload"], type=["mp3", "wav", "ogg"]) # 200 MB default limit. :contentReference[oaicite:3]{index=3}
|
| 143 |
+
st.write(f"**{t['or']}**")
|
| 144 |
+
audio_url = st.text_input(t["paste_url"], value="", placeholder="https://...")
|
| 145 |
+
|
| 146 |
+
c1, c2, c3 = st.columns([0.2, 0.2, 0.6])
|
| 147 |
go = c1.button(f"▶ {t['analyze']}", type="primary")
|
| 148 |
reset = c2.button(f"↩ {t['reset']}")
|
| 149 |
|
|
|
|
| 151 |
st.session_state.last_response = None
|
| 152 |
st.rerun()
|
| 153 |
|
| 154 |
+
# ================= HTTP session with retries
|
| 155 |
+
def build_session(_auto_retry: bool) -> requests.Session:
|
| 156 |
+
s = requests.Session()
|
| 157 |
+
s.headers.update(HEADERS)
|
| 158 |
+
if _auto_retry:
|
| 159 |
+
# Retry on common transient errors: 429, 500, 502, 503, 504. Backoff = 0.8s, exponential. :contentReference[oaicite:4]{index=4}
|
| 160 |
+
retry = Retry(
|
| 161 |
+
total=6,
|
| 162 |
+
connect=6,
|
| 163 |
+
read=6,
|
| 164 |
+
backoff_factor=0.8,
|
| 165 |
+
status_forcelist=[429, 500, 502, 503, 504],
|
| 166 |
+
allowed_methods=frozenset(["GET", "POST"]),
|
| 167 |
+
raise_on_status=False,
|
| 168 |
+
)
|
| 169 |
+
adapter = HTTPAdapter(max_retries=retry)
|
| 170 |
+
s.mount("http://", adapter)
|
| 171 |
+
s.mount("https://", adapter)
|
| 172 |
+
return s
|
| 173 |
+
|
| 174 |
+
def warm_up_backend(s: requests.Session, base: str, total_budget: int = 30):
|
| 175 |
+
start = time.time()
|
| 176 |
+
with st.spinner(t["warming"]):
|
| 177 |
+
# Many Spaces need a wake-up; hit GET / then /health with short timeouts. Cold boot ~1–2 min typical. :contentReference[oaicite:5]{index=5}
|
| 178 |
+
for path in ["/", "/health"]:
|
| 179 |
+
try:
|
| 180 |
+
r = s.get(f"{base.rstrip('/')}{path}", timeout=8)
|
| 181 |
+
if r.ok:
|
| 182 |
+
continue
|
| 183 |
+
except Exception:
|
| 184 |
+
pass
|
| 185 |
+
if time.time() - start > total_budget:
|
| 186 |
+
break
|
| 187 |
+
time.sleep(2)
|
| 188 |
|
| 189 |
+
def post_analyze(s: requests.Session, base: str, _file, _audio_url: str, timeout_sec: int = 120) -> dict:
|
| 190 |
+
url = f"{base.rstrip('/')}/analyze"
|
| 191 |
+
data = {
|
| 192 |
+
"detailed_analysis": "true" if detailed else "false",
|
| 193 |
+
"use_data_uri": "true" if use_data_uri else "false",
|
| 194 |
"openai_model": openai_model or "gpt-4o",
|
| 195 |
}
|
| 196 |
if prompt_override.strip():
|
| 197 |
+
data["prompt"] = prompt_override.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
files = None
|
| 200 |
if _file is not None:
|
|
|
|
| 203 |
elif _audio_url.strip():
|
| 204 |
data["audio_url"] = _audio_url.strip()
|
| 205 |
|
| 206 |
+
# Guard: nothing to send
|
| 207 |
+
if not files and "audio_url" not in data:
|
| 208 |
+
raise RuntimeError("No file or URL provided")
|
| 209 |
+
|
| 210 |
+
# Try within a total budget (for bad gateway/cold start); break if succeeded
|
| 211 |
+
deadline = time.time() + max_wait
|
| 212 |
+
last_err = None
|
| 213 |
+
attempts = 0
|
| 214 |
+
while True:
|
| 215 |
+
attempts += 1
|
| 216 |
try:
|
| 217 |
+
resp = s.post(url, data=data, files=files, timeout=timeout_sec)
|
| 218 |
+
# Accept 200 only; other statuses will be retried by the Session if enabled
|
| 219 |
+
resp.raise_for_status()
|
| 220 |
+
return resp.json()
|
| 221 |
+
except Exception as e:
|
| 222 |
+
last_err = e
|
| 223 |
+
if not auto_retry or time.time() > deadline:
|
| 224 |
+
# Return controlled error payload instead of exploding UI
|
| 225 |
+
return {
|
| 226 |
+
"ok": False,
|
| 227 |
+
"error": f"All attempts failed. Last error: {e}",
|
| 228 |
+
"attempts": attempts,
|
| 229 |
+
"api_base": base,
|
| 230 |
+
}
|
| 231 |
+
time.sleep(1.2) # small manual delay between loops; Session handles backoff too
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
|
|
|
| 233 |
if go:
|
| 234 |
if not api_base:
|
| 235 |
st.error(t["no_backend"])
|
| 236 |
elif not file and not audio_url.strip():
|
| 237 |
st.error(t["upload"])
|
| 238 |
else:
|
| 239 |
+
sess = build_session(auto_retry)
|
| 240 |
+
if warmup:
|
| 241 |
+
warm_up_backend(sess, api_base, total_budget=min(max_wait, 40))
|
| 242 |
+
with st.spinner(t["analyzing"]):
|
| 243 |
+
res = post_analyze(sess, api_base, file, audio_url, timeout_sec=180)
|
| 244 |
+
st.session_state.last_response = res
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
+
# ================= Results
|
| 247 |
res = st.session_state.last_response
|
| 248 |
if res:
|
| 249 |
+
# If backend returned controlled error (instead of raising), show nice message
|
| 250 |
+
if not res.get("ok", True) and res.get("error"):
|
| 251 |
+
st.error(res["error"])
|
| 252 |
+
st.info("Backend might be waking up or rate-limited. Try Analyze again, or increase ‘Max total wait’.")
|
| 253 |
+
else:
|
| 254 |
+
st.subheader(t["result"])
|
| 255 |
|
| 256 |
+
# Commentary
|
| 257 |
+
comm = res.get("commentary") or ""
|
| 258 |
+
if comm:
|
| 259 |
+
st.markdown(f"**{t['commentary']}**")
|
| 260 |
+
st.write(comm)
|
| 261 |
|
| 262 |
+
# JSON pretty
|
| 263 |
+
parsed = res.get("fal_parsed")
|
| 264 |
+
if parsed:
|
| 265 |
+
st.markdown(f"**{t['json']}**")
|
| 266 |
+
st.json(parsed)
|
| 267 |
|
| 268 |
+
# Backend artifacts
|
| 269 |
+
st.markdown(f"**{t['backend_artifacts']}**")
|
| 270 |
+
dls = res.get("downloads") or {}
|
| 271 |
+
col_a, col_b, col_c = st.columns(3)
|
| 272 |
|
| 273 |
+
def fetch_bytes(url: str) -> bytes:
|
| 274 |
+
if not url:
|
| 275 |
+
raise RuntimeError("empty url")
|
| 276 |
+
full = url if url.startswith("http") else f"{api_base.rstrip('/')}{url}"
|
| 277 |
+
r = requests.get(full, headers=HEADERS, timeout=60)
|
| 278 |
+
r.raise_for_status()
|
| 279 |
+
return r.content
|
| 280 |
|
| 281 |
+
if dls.get("summary_txt"):
|
| 282 |
+
try:
|
| 283 |
+
data = fetch_bytes(dls["summary_txt"])
|
| 284 |
+
col_a.download_button(label=t["download_summary"], data=data, file_name="summary.txt")
|
| 285 |
+
except Exception:
|
| 286 |
+
col_a.error("summary.txt ✖")
|
|
|
|
| 287 |
|
| 288 |
+
if dls.get("fal_parsed_json"):
|
| 289 |
+
try:
|
| 290 |
+
data = fetch_bytes(dls["fal_parsed_json"])
|
| 291 |
+
col_b.download_button(label=t["download_parsed"], data=data, file_name="parsed.json", mime="application/json")
|
| 292 |
+
except Exception:
|
| 293 |
+
col_b.error("parsed.json ✖")
|
|
|
|
| 294 |
|
| 295 |
+
if dls.get("fal_raw_txt"):
|
| 296 |
+
try:
|
| 297 |
+
data = fetch_bytes(dls["fal_raw_txt"])
|
| 298 |
+
col_c.download_button(label=t["download_raw"], data=data, file_name="raw.txt")
|
| 299 |
+
except Exception:
|
| 300 |
+
col_c.error("raw.txt ✖")
|
|
|
|
| 301 |
|
| 302 |
+
st.caption("© 2025 Diag Studio AI — Streamlit frontend (robust)")
|