renderfy commited on
Commit
3ef8fba
·
verified ·
1 Parent(s): 1abbf79

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -137
app.py CHANGED
@@ -1,21 +1,14 @@
1
- # app.py — DiagStudio AI (Streamlit frontend, public HF Space)
2
- # Kök dizine yazma girişimlerini engellemek için HOME ve headless/statistics env'lerini set ediyoruz.
3
- # Streamlit konfig/env yöntemleri belgeli. # :contentReference[oaicite:6]{index=6}
4
-
5
  import os
6
- # ---- set BEFORE importing streamlit ----
7
  os.environ.setdefault("HOME", "/tmp")
8
- os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false") # :contentReference[oaicite:7]{index=7}
9
  os.environ.setdefault("STREAMLIT_SERVER_HEADLESS", "true")
10
 
11
- import io
12
- import json
13
- import time
14
- import base64
15
- import requests
16
  import streamlit as st
17
 
18
- # ================= Theme =================
19
  try:
20
  st._config.set_option("theme.base", "dark")
21
  st._config.set_option("theme.primaryColor", "#ff7a1a")
@@ -25,22 +18,12 @@ try:
25
  except Exception:
26
  pass
27
 
28
- # ================= Env & API =================
29
- def _env(k):
30
- return (os.getenv(k) or "").strip().strip("'\"")
31
-
32
- API_BASE = (
33
- _env("CARDIAG_AI_API")
34
- or _env("AI_LIGHTBOX_API")
35
- or _env("LUXFIT_API")
36
- ).rstrip("/") if (
37
- _env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")
38
- ) else ""
39
-
40
  HF_TOKEN = _env("CARDIAG_AI_TOKEN") or _env("AI_LIGHTBOX_TOKEN") or _env("LUXFIT_TOKEN")
41
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
42
 
43
- # ================= App Header =================
44
  st.set_page_config(page_title="DiagStudio AI", layout="wide")
45
  st.title("DiagStudio AI")
46
  st.caption("Upload a short engine recording and get a clear, visual, and textual diagnosis report.")
@@ -49,21 +32,17 @@ if not API_BASE:
49
  st.error("Backend URL is not set. Define CARDIAG_AI_API (or AI_LIGHTBOX_API / LUXFIT_API).")
50
  st.stop()
51
 
52
- # ================= Helpers =================
53
  @st.cache_data(show_spinner=False, ttl=30)
54
- def check_health(url: str, headers: dict):
55
  try:
56
  r = requests.get(f"{url}/health", headers=headers, timeout=10)
57
  return r.status_code == 200
58
  except Exception:
59
  return False
60
 
61
- def _nice_conf(p):
62
- try:
63
- v = float(p)
64
- return min(max(v, 0.0), 1.0)
65
- except Exception:
66
- return 0.0
67
 
68
  def _post_analyze(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run_llm, notes):
69
  files = {}
@@ -71,17 +50,11 @@ def _post_analyze(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run_llm
71
  files["audio"] = (audio_file.name, audio_file.getvalue(), audio_file.type or "application/octet-stream")
72
  if rpm_file is not None:
73
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
74
-
75
  data = {
76
- "sr_target": str(sr_target),
77
- "n_fft": str(n_fft),
78
- "hop": str(hop),
79
- "env_band": env_band,
80
- "run_llm": "true" if run_llm else "false",
81
  "extra_text": notes or "",
82
  }
83
-
84
- # multipart/form-data upload akışı FastAPI UploadFile'a uygun # :contentReference[oaicite:8]{index=8}
85
  r = requests.post(f"{API_BASE}/analyze", headers=HEADERS, files=files, data=data, timeout=180)
86
  r.raise_for_status()
87
  return r.json()
@@ -92,28 +65,19 @@ def _post_analyze_zip(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run
92
  files["audio"] = (audio_file.name, audio_file.getvalue(), audio_file.type or "application/octet-stream")
93
  if rpm_file is not None:
94
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
95
-
96
  data = {
97
- "sr_target": str(sr_target),
98
- "n_fft": str(n_fft),
99
- "hop": str(hop),
100
- "env_band": env_band,
101
- "run_llm": "true" if run_llm else "false",
102
  "extra_text": notes or "",
103
  }
104
-
105
  r = requests.post(f"{API_BASE}/analyze_zip", headers=HEADERS, files=files, data=data, timeout=240, stream=True)
106
  r.raise_for_status()
107
  return r.content
108
 
109
- def dataurl_to_bytes(data_url: str) -> bytes:
110
- b64 = data_url.split(",", 1)[1]
111
- return base64.b64decode(b64)
112
-
113
- # ================= Sidebar =================
114
  with st.sidebar:
115
  st.header("Upload")
116
- audio_up = st.file_uploader("Engine recording (WAV/MP3/M4A)", type=["wav", "mp3", "m4a"])
117
  rpm_up = st.file_uploader("Optional RPM CSV (time_sec,rpm)", type=["csv"])
118
 
119
  st.header("Options")
@@ -121,33 +85,24 @@ with st.sidebar:
121
  user_notes = st.text_area("Context (optional)", placeholder="Vehicle, engine type, driving condition, symptoms…")
122
 
123
  with st.expander("Advanced (defaults are fine)"):
124
- sr_target = st.select_slider("Sample rate (Hz)", options=[16000, 22050, 32000, 44100, 48000], value=22050)
125
- n_fft = st.select_slider("Analysis window (n_fft)", options=[1024, 2048, 4096], value=2048)
126
- hop = st.select_slider("Hop length", options=[128, 256, 512, 1024], value=512)
127
- env_band = st.text_input("Impact band (Hz low,high)", value="1000,8000")
128
 
129
  ok = check_health(API_BASE, HEADERS)
130
- if not ok:
131
- st.warning("Could not reach the backend. Verify your private Space is running and reachable.")
132
-
133
- disabled = (audio_up is None) or (not ok)
134
- analyze_btn = st.button("Analyze now", type="primary", disabled=disabled)
135
 
136
- # ================= Main =================
137
  status_ph = st.empty()
138
 
139
  if analyze_btn and audio_up is not None:
140
  status_ph.info("Analyzing…")
141
  t0 = time.time()
142
  try:
143
- data = _post_analyze(
144
- audio_file=audio_up, rpm_file=rpm_up,
145
- sr_target=sr_target, n_fft=n_fft, hop=hop,
146
- env_band=env_band, run_llm=run_llm, notes=user_notes
147
- )
148
- elapsed = time.time() - t0
149
- status_ph.success(f"Done in {elapsed:.1f}s")
150
  st.session_state["last_result"] = data
 
151
  except requests.HTTPError as e:
152
  status_ph.error(f"Backend error: {e.response.status_code} — {e.response.text[:300]}")
153
  except Exception as e:
@@ -157,97 +112,58 @@ res = st.session_state.get("last_result")
157
  if res:
158
  st.subheader("Result")
159
 
160
- # ---- Model & usage meta (proof that GPT-4o Vision ran) ----
161
  llm = res.get("llm_report") or {}
162
- model_name = llm.get("model", "unknown")
163
- usage = llm.get("usage") or {}
164
- with st.container():
165
- st.caption(f"AI model: **{model_name}**")
166
- if usage:
167
- st.caption(f"Tokens — prompt: {usage.get('prompt_tokens')}, completion: {usage.get('completion_tokens')}")
168
-
169
- # ---- Diagnosis summary ----
 
 
170
  col1, col2 = st.columns([1,1])
171
  diag_list = llm.get("diagnosis", [])
172
- notes = llm.get("notes", "")
173
- next_tests = llm.get("next_tests", "")
174
 
175
  with col1:
176
  st.markdown("**Likely issues**")
177
  if diag_list:
178
  for item in diag_list:
179
- label = str(item.get("label", "Issue"))
180
- conf = item.get("likelihood", 0)
181
- evidence = str(item.get("evidence", ""))
182
- st.text(label)
183
- try:
184
- st.progress(min(max(float(conf), 0.0), 1.0))
185
- except Exception:
186
- st.progress(0.0)
187
- if evidence:
188
- st.caption(evidence)
189
  else:
190
  st.info("No specific faults detected with high confidence.")
191
 
192
  with col2:
193
- if notes:
194
- st.markdown("**Mechanic-friendly notes**")
195
- st.write(notes)
196
- if next_tests:
197
- st.markdown("**Suggested next checks**")
198
- st.write(next_tests)
199
-
200
- # ---- Visuals ----
201
- st.subheader("Visual checks")
202
- tabs = st.tabs([
203
- "Energy over time",
204
- "Perceptual view",
205
- "Impact pattern",
206
- "Signal envelope",
207
- "Detail view",
208
- "Order view"
209
- ])
210
 
211
- imgs = res.get("images", {})
 
 
212
 
213
  with tabs[0]:
214
- if "stft" in imgs:
215
- st.image(imgs["stft"], caption="Energy distribution across time.")
216
  with tabs[1]:
217
- if "mel" in imgs:
218
- st.image(imgs["mel"], caption="Perceptually-weighted overview.")
219
  with tabs[2]:
220
- if "envelope_spectrum" in imgs:
221
- st.image(imgs["envelope_spectrum"], caption="Repetitive impact signature.")
222
  with tabs[3]:
223
- if "envelope_trace" in imgs:
224
- st.image(imgs["envelope_trace"], caption="Overall intensity trace.")
225
  with tabs[4]:
226
- if "cwt" in imgs:
227
- st.image(imgs["cwt"], caption="Fine details and short events.")
228
- with tabs[5]:
229
- if "order_map" in imgs:
230
- st.image(imgs["order_map"], caption="Patterns that track engine speed.")
231
- else:
232
- st.caption("Order view requires an RPM CSV (time_sec,rpm).")
233
 
234
  st.divider()
235
-
236
  st.subheader("Download")
237
  st.caption("Get all visuals and the diagnosis as a single ZIP.")
238
  if st.button("Prepare ZIP"):
239
  try:
240
- zbytes = _post_analyze_zip(
241
- audio_file=audio_up, rpm_file=rpm_up,
242
- sr_target=sr_target, n_fft=n_fft, hop=hop,
243
- env_band=env_band, run_llm=run_llm, notes=user_notes
244
- )
245
- st.download_button(
246
- "Download results (ZIP)",
247
- data=zbytes,
248
- file_name="diagstudio_results.zip",
249
- mime="application/zip"
250
- )
251
  except Exception as e:
252
  st.error(f"ZIP build failed: {e}")
253
  else:
 
1
+ # app.py — DiagStudio AI (Streamlit frontend, Vision meta-visible)
 
 
 
2
  import os
3
+ # must be set before importing streamlit (avoid /.streamlit writes)
4
  os.environ.setdefault("HOME", "/tmp")
5
+ os.environ.setdefault("STREAMLIT_BROWSER_GATHER_USAGE_STATS", "false") # :contentReference[oaicite:8]{index=8}
6
  os.environ.setdefault("STREAMLIT_SERVER_HEADLESS", "true")
7
 
8
+ import io, json, time, base64, requests
 
 
 
 
9
  import streamlit as st
10
 
11
+ # ============ Theme ============
12
  try:
13
  st._config.set_option("theme.base", "dark")
14
  st._config.set_option("theme.primaryColor", "#ff7a1a")
 
18
  except Exception:
19
  pass
20
 
21
+ # ============ Env & API ============
22
+ def _env(k): return (os.getenv(k) or "").strip().strip("'\"")
23
+ API_BASE = (_env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")).rstrip("/") if (_env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")) else ""
 
 
 
 
 
 
 
 
 
24
  HF_TOKEN = _env("CARDIAG_AI_TOKEN") or _env("AI_LIGHTBOX_TOKEN") or _env("LUXFIT_TOKEN")
25
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
26
 
 
27
  st.set_page_config(page_title="DiagStudio AI", layout="wide")
28
  st.title("DiagStudio AI")
29
  st.caption("Upload a short engine recording and get a clear, visual, and textual diagnosis report.")
 
32
  st.error("Backend URL is not set. Define CARDIAG_AI_API (or AI_LIGHTBOX_API / LUXFIT_API).")
33
  st.stop()
34
 
 
35
  @st.cache_data(show_spinner=False, ttl=30)
36
+ def check_health(url, headers):
37
  try:
38
  r = requests.get(f"{url}/health", headers=headers, timeout=10)
39
  return r.status_code == 200
40
  except Exception:
41
  return False
42
 
43
+ def _nice_conf(x):
44
+ try: return min(max(float(x), 0.0), 1.0)
45
+ except: return 0.0
 
 
 
46
 
47
  def _post_analyze(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run_llm, notes):
48
  files = {}
 
50
  files["audio"] = (audio_file.name, audio_file.getvalue(), audio_file.type or "application/octet-stream")
51
  if rpm_file is not None:
52
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
 
53
  data = {
54
+ "sr_target": str(sr_target), "n_fft": str(n_fft), "hop": str(hop),
55
+ "env_band": env_band, "run_llm": "true" if run_llm else "false",
 
 
 
56
  "extra_text": notes or "",
57
  }
 
 
58
  r = requests.post(f"{API_BASE}/analyze", headers=HEADERS, files=files, data=data, timeout=180)
59
  r.raise_for_status()
60
  return r.json()
 
65
  files["audio"] = (audio_file.name, audio_file.getvalue(), audio_file.type or "application/octet-stream")
66
  if rpm_file is not None:
67
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
 
68
  data = {
69
+ "sr_target": str(sr_target), "n_fft": str(n_fft), "hop": str(hop),
70
+ "env_band": env_band, "run_llm": "true" if run_llm else "false",
 
 
 
71
  "extra_text": notes or "",
72
  }
 
73
  r = requests.post(f"{API_BASE}/analyze_zip", headers=HEADERS, files=files, data=data, timeout=240, stream=True)
74
  r.raise_for_status()
75
  return r.content
76
 
77
+ # ============ Sidebar ============
 
 
 
 
78
  with st.sidebar:
79
  st.header("Upload")
80
+ audio_up = st.file_uploader("Engine recording (WAV/MP3/M4A)", type=["wav","mp3","m4a"])
81
  rpm_up = st.file_uploader("Optional RPM CSV (time_sec,rpm)", type=["csv"])
82
 
83
  st.header("Options")
 
85
  user_notes = st.text_area("Context (optional)", placeholder="Vehicle, engine type, driving condition, symptoms…")
86
 
87
  with st.expander("Advanced (defaults are fine)"):
88
+ sr_target = st.select_slider("Sample rate (Hz)", options=[16000,22050,32000,44100,48000], value=22050)
89
+ n_fft = st.select_slider("Analysis window (n_fft)", options=[1024,2048,4096], value=2048)
90
+ hop = st.select_slider("Hop length", options=[128,256,512,1024], value=512)
91
+ env_band = st.text_input("Impact band (Hz low,high or 'auto')", value="auto")
92
 
93
  ok = check_health(API_BASE, HEADERS)
94
+ if not ok: st.warning("Could not reach the backend. Verify your private Space is running and reachable.")
95
+ analyze_btn = st.button("Analyze now", type="primary", disabled=(audio_up is None or not ok))
 
 
 
96
 
 
97
  status_ph = st.empty()
98
 
99
  if analyze_btn and audio_up is not None:
100
  status_ph.info("Analyzing…")
101
  t0 = time.time()
102
  try:
103
+ data = _post_analyze(audio_up, rpm_up, sr_target, n_fft, hop, env_band, run_llm, user_notes)
 
 
 
 
 
 
104
  st.session_state["last_result"] = data
105
+ status_ph.success(f"Done in {time.time()-t0:.1f}s")
106
  except requests.HTTPError as e:
107
  status_ph.error(f"Backend error: {e.response.status_code} — {e.response.text[:300]}")
108
  except Exception as e:
 
112
  if res:
113
  st.subheader("Result")
114
 
 
115
  llm = res.get("llm_report") or {}
116
+ model_name = llm.get("model","unknown"); usage = llm.get("usage") or {}
117
+ st.caption(f"AI model: **{model_name}**")
118
+ if usage:
119
+ st.caption(f"Tokens — prompt: {usage.get('prompt_tokens')}, completion: {usage.get('completion_tokens')}")
120
+
121
+ # Vision meta proof (did it see images?)
122
+ meta = llm.get("meta", {})
123
+ if meta:
124
+ st.caption(f"Vision meta — seen_images: {meta.get('seen_images')}, views: {meta.get('views')}")
125
+
126
  col1, col2 = st.columns([1,1])
127
  diag_list = llm.get("diagnosis", [])
128
+ notes = llm.get("notes",""); next_tests = llm.get("next_tests","")
 
129
 
130
  with col1:
131
  st.markdown("**Likely issues**")
132
  if diag_list:
133
  for item in diag_list:
134
+ st.text(str(item.get("label","Issue")))
135
+ st.progress(_nice_conf(item.get("likelihood",0)))
136
+ if item.get("evidence"): st.caption(item["evidence"])
 
 
 
 
 
 
 
137
  else:
138
  st.info("No specific faults detected with high confidence.")
139
 
140
  with col2:
141
+ if notes: st.markdown("**Mechanic-friendly notes**"); st.write(notes)
142
+ if next_tests: st.markdown("**Suggested next checks**"); st.write(next_tests)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ st.subheader("Visual checks")
145
+ tabs = st.tabs(["Energy over time","Perceptual view","Impact pattern","Signal envelope","Order view"])
146
+ imgs = res.get("images",{})
147
 
148
  with tabs[0]:
149
+ if "stft" in imgs: st.image(imgs["stft"], caption="Energy distribution across time.")
 
150
  with tabs[1]:
151
+ if "mel" in imgs: st.image(imgs["mel"], caption="Perceptually-weighted overview.")
 
152
  with tabs[2]:
153
+ if "envelope_spectrum" in imgs: st.image(imgs["envelope_spectrum"], caption="Repetitive impact signature.")
 
154
  with tabs[3]:
155
+ if "envelope_trace" in imgs: st.image(imgs["envelope_trace"], caption="Overall intensity trace.")
 
156
  with tabs[4]:
157
+ if "order_map" in imgs: st.image(imgs["order_map"], caption="Patterns that track engine speed.")
158
+ else: st.caption("Order view requires an RPM CSV (time_sec,rpm).")
 
 
 
 
 
159
 
160
  st.divider()
 
161
  st.subheader("Download")
162
  st.caption("Get all visuals and the diagnosis as a single ZIP.")
163
  if st.button("Prepare ZIP"):
164
  try:
165
+ zbytes = _post_analyze_zip(audio_up, rpm_up, sr_target, n_fft, hop, env_band, run_llm, user_notes)
166
+ st.download_button("Download results (ZIP)", data=zbytes, file_name="diagstudio_results.zip", mime="application/zip")
 
 
 
 
 
 
 
 
 
167
  except Exception as e:
168
  st.error(f"ZIP build failed: {e}")
169
  else: