Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
-
# app.py — Diag Studio AI Frontend (TR/EN, retries, warm-up, artifacts
|
| 2 |
import os
|
| 3 |
-
import io
|
| 4 |
import json
|
| 5 |
import time
|
| 6 |
import requests
|
|
@@ -38,7 +37,7 @@ HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
|
| 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",
|
|
@@ -49,8 +48,6 @@ L = {
|
|
| 49 |
"detailed": "Detailed analysis (always on)",
|
| 50 |
"use_data_uri": "Send as data:URI (safer for private backends)",
|
| 51 |
"model": "Commentary model (OpenAI)",
|
| 52 |
-
"mode": "Prompt Mode",
|
| 53 |
-
"mode_help": "Strict groups similar timbres to reduce mislabels; Full uses detailed taxonomy.",
|
| 54 |
"analyze": "Analyze",
|
| 55 |
"reset": "Reset",
|
| 56 |
"result": "Result",
|
|
@@ -73,14 +70,14 @@ L = {
|
|
| 73 |
"lang_help": "Output language for GPT-4o commentary",
|
| 74 |
"ok_false": "Request returned a controlled error from backend.",
|
| 75 |
"try_again": "Backend might be waking up or rate-limited. Try Analyze again or increase ‘Max total wait’.",
|
| 76 |
-
"
|
| 77 |
-
"
|
| 78 |
-
"
|
| 79 |
-
"
|
| 80 |
},
|
| 81 |
"tr": {
|
| 82 |
"title": "Diag Studio AI — Motor Sesi Teşhis",
|
| 83 |
-
"about": "Motor sesini (mp3/wav/ogg) yükleyin veya bir ses URL’si girin. Backend fal.ai ‘audio-understanding’
|
| 84 |
"backend_url": "Backend URL",
|
| 85 |
"lang": "Dil",
|
| 86 |
"upload": "Ses dosyası yükle",
|
|
@@ -91,8 +88,6 @@ L = {
|
|
| 91 |
"detailed": "Ayrıntılı analiz (her zaman açık)",
|
| 92 |
"use_data_uri": "data:URI olarak gönder (özel backend için güvenli)",
|
| 93 |
"model": "Yorum modeli (OpenAI)",
|
| 94 |
-
"mode": "Prompt Modu",
|
| 95 |
-
"mode_help": "Strict benzer tınıları gruplayıp karışmayı azaltır; Full detaylı taksonomi kullanır.",
|
| 96 |
"analyze": "Analiz Et",
|
| 97 |
"reset": "Sıfırla",
|
| 98 |
"result": "Sonuç",
|
|
@@ -105,7 +100,7 @@ L = {
|
|
| 105 |
"no_backend": "Bir backend URL girin (örn: http://127.0.0.1:7860)",
|
| 106 |
"health_ok": "Backend erişilebilir.",
|
| 107 |
"health_fail": "Backend’e erişilemedi.",
|
| 108 |
-
"upload_hint": "Streamlit yükleme sınırı ~200 MB; mp3/wav/ogg kullanın.",
|
| 109 |
"footer": "İpucu: Dosya yüklemek istemezseniz herkese açık bir ses URL’si de girebilirsiniz.",
|
| 110 |
"auto_retry": "429/500/502/503/504 için otomatik yeniden dene",
|
| 111 |
"warmup": "Analizden önce backend’i ısıt",
|
|
@@ -115,10 +110,10 @@ L = {
|
|
| 115 |
"lang_help": "GPT-4o yorum çıktısının dili",
|
| 116 |
"ok_false": "Backend kontrollü bir hata döndürdü.",
|
| 117 |
"try_again": "Backend uyanıyor veya sınırlandı. Yeniden Dene’ye basın ya da ‘Azami bekleme’ değerini artırın.",
|
| 118 |
-
"
|
| 119 |
-
"
|
| 120 |
-
"
|
| 121 |
-
"
|
| 122 |
}
|
| 123 |
}
|
| 124 |
|
|
@@ -127,8 +122,6 @@ if "lang" not in st.session_state:
|
|
| 127 |
st.session_state.lang = "tr"
|
| 128 |
if "last_response" not in st.session_state:
|
| 129 |
st.session_state.last_response = None
|
| 130 |
-
if "audio_mem" not in st.session_state:
|
| 131 |
-
st.session_state.audio_mem = None # keep last uploaded audio bytes for player
|
| 132 |
|
| 133 |
# ================= Header =================
|
| 134 |
col1, col2 = st.columns([0.6, 0.4])
|
|
@@ -150,12 +143,10 @@ api_base = st.text_input(t["backend_url"], value=backend_default)
|
|
| 150 |
|
| 151 |
# ================= Advanced options =================
|
| 152 |
with st.expander(t["adv"], expanded=False):
|
| 153 |
-
st.checkbox(t["detailed"], value=True, disabled=True)
|
| 154 |
use_data_uri = st.checkbox(t["use_data_uri"], value=True)
|
| 155 |
openai_model = st.text_input(t["model"], value="gpt-4o")
|
| 156 |
prompt_override = st.text_area(t["prompt"], value="", height=120)
|
| 157 |
-
# NEW: Full/Strict selector
|
| 158 |
-
mode = st.selectbox(t["mode"], ["FULL", "STRICT"], index=0, help=t["mode_help"])
|
| 159 |
auto_retry = st.checkbox(t["auto_retry"], value=True)
|
| 160 |
warmup = st.checkbox(t["warmup"], value=True)
|
| 161 |
max_wait = st.slider(t["max_wait"], 10, 180, 60, step=10)
|
|
@@ -166,21 +157,15 @@ st.markdown("---")
|
|
| 166 |
# ================= Upload / URL =================
|
| 167 |
st.write(t["upload_hint"])
|
| 168 |
file = st.file_uploader(t["upload"], type=["mp3", "wav", "ogg"])
|
| 169 |
-
st.write(f"**{t['or']}**")
|
| 170 |
-
audio_url = st.text_input(t["paste_url"], value="", placeholder="https://...")
|
| 171 |
-
|
| 172 |
-
# If a file was uploaded, stash bytes for inline audio preview
|
| 173 |
if file is not None:
|
| 174 |
try:
|
| 175 |
-
|
| 176 |
-
st.
|
| 177 |
-
# Reset file pointer for requests
|
| 178 |
-
file.seek(0)
|
| 179 |
except Exception:
|
| 180 |
-
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
|
| 185 |
# ================= Controls =================
|
| 186 |
c1, c2, c3 = st.columns([0.2, 0.2, 0.6])
|
|
@@ -227,14 +212,13 @@ def fetch_bytes(sess: requests.Session, base: str, url: str) -> bytes:
|
|
| 227 |
r.raise_for_status()
|
| 228 |
return r.content
|
| 229 |
|
| 230 |
-
def post_analyze(sess: requests.Session, base: str, _file, _audio_url: str, lang: str
|
| 231 |
url = f"{base.rstrip('/')}/analyze"
|
| 232 |
data = {
|
| 233 |
-
"detailed_analysis": "true", # backend
|
| 234 |
"use_data_uri": "true" if use_data_uri else "false",
|
| 235 |
"openai_model": openai_model or "gpt-4o",
|
| 236 |
-
"lang": lang, #
|
| 237 |
-
"prompt_mode": mode, # "FULL" | "STRICT"
|
| 238 |
}
|
| 239 |
if prompt_override.strip():
|
| 240 |
data["prompt"] = prompt_override.strip()
|
|
@@ -295,13 +279,7 @@ if go:
|
|
| 295 |
if warmup:
|
| 296 |
warm_up_backend(sess, api_base, total_budget=min(max_wait, 40))
|
| 297 |
with st.spinner(t["analyzing"]):
|
| 298 |
-
|
| 299 |
-
if file is not None:
|
| 300 |
-
try:
|
| 301 |
-
file.seek(0)
|
| 302 |
-
except Exception:
|
| 303 |
-
pass
|
| 304 |
-
res = post_analyze(sess, api_base, file, audio_url, st.session_state.lang, mode)
|
| 305 |
st.session_state.last_response = res
|
| 306 |
|
| 307 |
# ================= Results =================
|
|
@@ -311,71 +289,58 @@ if res:
|
|
| 311 |
st.error(t["ok_false"])
|
| 312 |
st.write(res.get("error"))
|
| 313 |
st.info(t["try_again"])
|
| 314 |
-
# Debug blokları varsa göster
|
| 315 |
if res.get("fal_debug"):
|
| 316 |
st.expander("Debug").code(json.dumps(res["fal_debug"], ensure_ascii=False, indent=2), language="json")
|
| 317 |
else:
|
| 318 |
st.subheader(t["result"])
|
| 319 |
-
|
| 320 |
-
# Anomaly Gate & Taxonomy quick view
|
| 321 |
-
parsed = res.get("fal_parsed") or {}
|
| 322 |
-
if isinstance(parsed, dict):
|
| 323 |
-
gate = parsed.get("anomaly_gate") or {}
|
| 324 |
-
colg1, colg2, colg3 = st.columns([0.33, 0.33, 0.34])
|
| 325 |
-
with colg1:
|
| 326 |
-
st.markdown(f"**{t['gate']}**")
|
| 327 |
-
is_anom = gate.get("is_anomaly")
|
| 328 |
-
score = gate.get("score")
|
| 329 |
-
ev = gate.get("evidence")
|
| 330 |
-
st.write(f"• is_anomaly: `{is_anom}`")
|
| 331 |
-
st.write(f"• score: `{score}`")
|
| 332 |
-
if ev: st.write(f"• evidence: `{ev}`")
|
| 333 |
-
with colg2:
|
| 334 |
-
st.markdown(f"**{t['taxonomy']}**")
|
| 335 |
-
tax = parsed.get("taxonomy_version") or res.get("taxonomy_version")
|
| 336 |
-
st.write(f"`{tax or '—'}`")
|
| 337 |
-
pmode = res.get("prompt_mode")
|
| 338 |
-
if pmode:
|
| 339 |
-
st.write(f"mode: `{pmode}`")
|
| 340 |
-
with colg3:
|
| 341 |
-
rules = (parsed.get("adjudication") or {}).get("applied_rules") or (res.get("adjudication") or {}).get("applied_rules")
|
| 342 |
-
st.markdown(f"**{t['applied_rules']}**")
|
| 343 |
-
if rules:
|
| 344 |
-
st.code(json.dumps(rules, ensure_ascii=False, indent=2), language="json")
|
| 345 |
-
conf_pairs = (parsed.get("notes") or {}).get("confusion_pairs")
|
| 346 |
-
if conf_pairs:
|
| 347 |
-
st.markdown(f"**{t['confusions']}**")
|
| 348 |
-
st.code(json.dumps(conf_pairs, ensure_ascii=False, indent=2), language="json")
|
| 349 |
-
|
| 350 |
-
# Driver-friendly commentary
|
| 351 |
comm = res.get("commentary") or ""
|
| 352 |
if comm:
|
| 353 |
st.markdown(f"**{t['commentary']}**")
|
| 354 |
st.write(comm)
|
| 355 |
|
| 356 |
-
#
|
|
|
|
| 357 |
if parsed:
|
| 358 |
st.markdown(f"**{t['json']}**")
|
| 359 |
st.json(parsed)
|
| 360 |
|
| 361 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
st.markdown(f"**{t['backend_artifacts']}**")
|
| 363 |
dls = res.get("downloads") or {}
|
| 364 |
col_a, col_b, col_c = st.columns(3)
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
| 379 |
|
| 380 |
# ===== Footer =====
|
| 381 |
-
st.caption("© 2025 Diag Studio AI — Streamlit frontend (TR/EN, retries, warm-up
|
|
|
|
| 1 |
+
# app.py — Diag Studio AI Frontend (TR/EN, retries, warm-up, artifacts download, audio preview)
|
| 2 |
import os
|
|
|
|
| 3 |
import json
|
| 4 |
import time
|
| 5 |
import requests
|
|
|
|
| 37 |
L = {
|
| 38 |
"en": {
|
| 39 |
"title": "Diag Studio AI — Engine Sound Diagnosis",
|
| 40 |
+
"about": "Upload an engine sound (mp3/wav/ogg) or paste an audio URL. Backend runs fal.ai audio-understanding with detailed analysis, then maps to labels and summarizes with GPT-4o.",
|
| 41 |
"backend_url": "Backend URL",
|
| 42 |
"lang": "Language",
|
| 43 |
"upload": "Upload audio file",
|
|
|
|
| 48 |
"detailed": "Detailed analysis (always on)",
|
| 49 |
"use_data_uri": "Send as data:URI (safer for private backends)",
|
| 50 |
"model": "Commentary model (OpenAI)",
|
|
|
|
|
|
|
| 51 |
"analyze": "Analyze",
|
| 52 |
"reset": "Reset",
|
| 53 |
"result": "Result",
|
|
|
|
| 70 |
"lang_help": "Output language for GPT-4o commentary",
|
| 71 |
"ok_false": "Request returned a controlled error from backend.",
|
| 72 |
"try_again": "Backend might be waking up or rate-limited. Try Analyze again or increase ‘Max total wait’.",
|
| 73 |
+
"preview": "Audio preview",
|
| 74 |
+
"raw_text": "Raw (model text)",
|
| 75 |
+
"prompt_used": "Prompt used (first 240 chars)",
|
| 76 |
+
"api_used": "Backend audio URL (truncated)"
|
| 77 |
},
|
| 78 |
"tr": {
|
| 79 |
"title": "Diag Studio AI — Motor Sesi Teşhis",
|
| 80 |
+
"about": "Motor sesini (mp3/wav/ogg) yükleyin veya bir ses URL’si girin. Backend fal.ai ‘audio-understanding’ ile ayrıntılı analiz yapar, etiketlere map eder ve GPT-4o ile özetler.",
|
| 81 |
"backend_url": "Backend URL",
|
| 82 |
"lang": "Dil",
|
| 83 |
"upload": "Ses dosyası yükle",
|
|
|
|
| 88 |
"detailed": "Ayrıntılı analiz (her zaman açık)",
|
| 89 |
"use_data_uri": "data:URI olarak gönder (özel backend için güvenli)",
|
| 90 |
"model": "Yorum modeli (OpenAI)",
|
|
|
|
|
|
|
| 91 |
"analyze": "Analiz Et",
|
| 92 |
"reset": "Sıfırla",
|
| 93 |
"result": "Sonuç",
|
|
|
|
| 100 |
"no_backend": "Bir backend URL girin (örn: http://127.0.0.1:7860)",
|
| 101 |
"health_ok": "Backend erişilebilir.",
|
| 102 |
"health_fail": "Backend’e erişilemedi.",
|
| 103 |
+
"upload_hint": "Streamlit varsayılan yükleme sınırı ~200 MB; mp3/wav/ogg kullanın.",
|
| 104 |
"footer": "İpucu: Dosya yüklemek istemezseniz herkese açık bir ses URL’si de girebilirsiniz.",
|
| 105 |
"auto_retry": "429/500/502/503/504 için otomatik yeniden dene",
|
| 106 |
"warmup": "Analizden önce backend’i ısıt",
|
|
|
|
| 110 |
"lang_help": "GPT-4o yorum çıktısının dili",
|
| 111 |
"ok_false": "Backend kontrollü bir hata döndürdü.",
|
| 112 |
"try_again": "Backend uyanıyor veya sınırlandı. Yeniden Dene’ye basın ya da ‘Azami bekleme’ değerini artırın.",
|
| 113 |
+
"preview": "Ses önizleme",
|
| 114 |
+
"raw_text": "Ham çıktı (model metni)",
|
| 115 |
+
"prompt_used": "Kullanılan prompt (ilk 240 karakter)",
|
| 116 |
+
"api_used": "Backend ses URL’si (kısaltılmış)"
|
| 117 |
}
|
| 118 |
}
|
| 119 |
|
|
|
|
| 122 |
st.session_state.lang = "tr"
|
| 123 |
if "last_response" not in st.session_state:
|
| 124 |
st.session_state.last_response = None
|
|
|
|
|
|
|
| 125 |
|
| 126 |
# ================= Header =================
|
| 127 |
col1, col2 = st.columns([0.6, 0.4])
|
|
|
|
| 143 |
|
| 144 |
# ================= Advanced options =================
|
| 145 |
with st.expander(t["adv"], expanded=False):
|
| 146 |
+
st.checkbox(t["detailed"], value=True, disabled=True) # backend already enforces True
|
| 147 |
use_data_uri = st.checkbox(t["use_data_uri"], value=True)
|
| 148 |
openai_model = st.text_input(t["model"], value="gpt-4o")
|
| 149 |
prompt_override = st.text_area(t["prompt"], value="", height=120)
|
|
|
|
|
|
|
| 150 |
auto_retry = st.checkbox(t["auto_retry"], value=True)
|
| 151 |
warmup = st.checkbox(t["warmup"], value=True)
|
| 152 |
max_wait = st.slider(t["max_wait"], 10, 180, 60, step=10)
|
|
|
|
| 157 |
# ================= Upload / URL =================
|
| 158 |
st.write(t["upload_hint"])
|
| 159 |
file = st.file_uploader(t["upload"], type=["mp3", "wav", "ogg"])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
if file is not None:
|
| 161 |
try:
|
| 162 |
+
st.markdown(f"**{t['preview']}**")
|
| 163 |
+
st.audio(file, format=file.type or "audio/mpeg")
|
|
|
|
|
|
|
| 164 |
except Exception:
|
| 165 |
+
pass
|
| 166 |
|
| 167 |
+
st.write(f"**{t['or']}**")
|
| 168 |
+
audio_url = st.text_input(t["paste_url"], value="", placeholder="https://...")
|
| 169 |
|
| 170 |
# ================= Controls =================
|
| 171 |
c1, c2, c3 = st.columns([0.2, 0.2, 0.6])
|
|
|
|
| 212 |
r.raise_for_status()
|
| 213 |
return r.content
|
| 214 |
|
| 215 |
+
def post_analyze(sess: requests.Session, base: str, _file, _audio_url: str, lang: str) -> dict:
|
| 216 |
url = f"{base.rstrip('/')}/analyze"
|
| 217 |
data = {
|
| 218 |
+
"detailed_analysis": "true", # backend pins True anyway
|
| 219 |
"use_data_uri": "true" if use_data_uri else "false",
|
| 220 |
"openai_model": openai_model or "gpt-4o",
|
| 221 |
+
"lang": lang, # pass language to backend (tr/en)
|
|
|
|
| 222 |
}
|
| 223 |
if prompt_override.strip():
|
| 224 |
data["prompt"] = prompt_override.strip()
|
|
|
|
| 279 |
if warmup:
|
| 280 |
warm_up_backend(sess, api_base, total_budget=min(max_wait, 40))
|
| 281 |
with st.spinner(t["analyzing"]):
|
| 282 |
+
res = post_analyze(sess, api_base, file, audio_url, st.session_state.lang)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
st.session_state.last_response = res
|
| 284 |
|
| 285 |
# ================= Results =================
|
|
|
|
| 289 |
st.error(t["ok_false"])
|
| 290 |
st.write(res.get("error"))
|
| 291 |
st.info(t["try_again"])
|
|
|
|
| 292 |
if res.get("fal_debug"):
|
| 293 |
st.expander("Debug").code(json.dumps(res["fal_debug"], ensure_ascii=False, indent=2), language="json")
|
| 294 |
else:
|
| 295 |
st.subheader(t["result"])
|
| 296 |
+
# driver-friendly commentary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
comm = res.get("commentary") or ""
|
| 298 |
if comm:
|
| 299 |
st.markdown(f"**{t['commentary']}**")
|
| 300 |
st.write(comm)
|
| 301 |
|
| 302 |
+
# parsed JSON
|
| 303 |
+
parsed = res.get("fal_parsed")
|
| 304 |
if parsed:
|
| 305 |
st.markdown(f"**{t['json']}**")
|
| 306 |
st.json(parsed)
|
| 307 |
|
| 308 |
+
# small extras: prompt used and fal audio url if present
|
| 309 |
+
extras_col1, extras_col2 = st.columns(2)
|
| 310 |
+
if res.get("prompt_used"):
|
| 311 |
+
with extras_col1:
|
| 312 |
+
st.caption(t["prompt_used"])
|
| 313 |
+
st.code(res["prompt_used"], language="text")
|
| 314 |
+
if res.get("fal_audio_url"):
|
| 315 |
+
with extras_col2:
|
| 316 |
+
st.caption(t["api_used"])
|
| 317 |
+
st.code(res["fal_audio_url"], language="text")
|
| 318 |
+
|
| 319 |
+
# backend artifacts
|
| 320 |
st.markdown(f"**{t['backend_artifacts']}**")
|
| 321 |
dls = res.get("downloads") or {}
|
| 322 |
col_a, col_b, col_c = st.columns(3)
|
| 323 |
|
| 324 |
+
if dls.get("summary_txt"):
|
| 325 |
+
try:
|
| 326 |
+
data = fetch_bytes(sess, api_base, dls["summary_txt"])
|
| 327 |
+
col_a.download_button(label=t["download_summary"], data=data, file_name="summary.txt")
|
| 328 |
+
except Exception:
|
| 329 |
+
col_a.error("summary.txt ✖")
|
| 330 |
+
|
| 331 |
+
if dls.get("fal_parsed_json"):
|
| 332 |
+
try:
|
| 333 |
+
data = fetch_bytes(sess, api_base, dls["fal_parsed_json"])
|
| 334 |
+
col_b.download_button(label=t["download_parsed"], data=data, file_name="parsed.json", mime="application/json")
|
| 335 |
+
except Exception:
|
| 336 |
+
col_b.error("parsed.json ✖")
|
| 337 |
|
| 338 |
+
if dls.get("fal_raw_txt"):
|
| 339 |
+
try:
|
| 340 |
+
data = fetch_bytes(sess, api_base, dls["fal_raw_txt"])
|
| 341 |
+
col_c.download_button(label=t["download_raw"], data=data, file_name="raw.txt")
|
| 342 |
+
except Exception:
|
| 343 |
+
col_c.error("raw.txt ✖")
|
| 344 |
|
| 345 |
# ===== Footer =====
|
| 346 |
+
st.caption("© 2025 Diag Studio AI — Streamlit frontend (TR/EN, retries, warm-up)")
|