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

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +110 -49
app.py CHANGED
@@ -1,14 +1,18 @@
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,22 +22,23 @@ try:
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.")
30
 
31
- if not API_BASE:
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
@@ -41,8 +46,10 @@ def check_health(url, headers):
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,12 +57,18 @@ def _post_analyze(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run_llm
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()
61
 
@@ -66,36 +79,53 @@ def _post_analyze_zip(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run
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")
84
- run_llm = st.toggle("Explain with AI", value=True, help="Adds an easy-to-read diagnosis and next steps.")
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()
@@ -109,52 +139,83 @@ if analyze_btn and audio_up is not None:
109
  status_ph.error(f"Request failed: {e}")
110
 
111
  res = st.session_state.get("last_result")
 
 
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()
@@ -167,4 +228,4 @@ if res:
167
  except Exception as e:
168
  st.error(f"ZIP build failed: {e}")
169
  else:
170
- st.info("Upload an engine recording, optionally add RPM CSV, then click Analyze.")
 
1
+ # app.py — DiagStudio AI (Streamlit frontend for the FastAPI backend with a single composite image)
2
+ # UI is end-user friendly (English). It calls your private backend's /analyze and /analyze_zip.
3
+ # Notes:
4
+ # - Set CARDIAG_AI_API (or AI_LIGHTBOX_API / LUXFIT_API) to your private FastAPI base URL.
5
+ # - Optional: set CARDIAG_AI_TOKEN (or AI_LIGHTBOX_TOKEN / LUXFIT_TOKEN) for auth header passthrough.
6
+ # - We disable Streamlit's telemetry writes and force a writable HOME to avoid /.streamlit permission issues.
7
+
8
+ import os, io, json, time, base64, requests, hashlib
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
  import streamlit as st
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 =================
26
  def _env(k): return (os.getenv(k) or "").strip().strip("'\"")
27
+
28
+ API_BASE = (
29
+ _env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")
30
+ ).rstrip("/") if (_env("CARDIAG_AI_API") or _env("AI_LIGHTBOX_API") or _env("LUXFIT_API")) else ""
31
+
32
  HF_TOKEN = _env("CARDIAG_AI_TOKEN") or _env("AI_LIGHTBOX_TOKEN") or _env("LUXFIT_TOKEN")
33
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
34
 
35
  st.set_page_config(page_title="DiagStudio AI", layout="wide")
36
  st.title("DiagStudio AI")
37
+ st.caption("Upload a short engine recording and get a clear diagnosis with visuals and notes.")
38
 
39
+ # ================= Helpers =================
40
+ @st.cache_data(show_spinner=False, ttl=20)
41
+ def _health(url, headers):
 
 
 
42
  try:
43
  r = requests.get(f"{url}/health", headers=headers, timeout=10)
44
  return r.status_code == 200
 
46
  return False
47
 
48
  def _nice_conf(x):
49
+ try:
50
+ return min(max(float(x), 0.0), 1.0)
51
+ except Exception:
52
+ return 0.0
53
 
54
  def _post_analyze(audio_file, rpm_file, sr_target, n_fft, hop, env_band, run_llm, notes):
55
  files = {}
 
57
  files["audio"] = (audio_file.name, audio_file.getvalue(), audio_file.type or "application/octet-stream")
58
  if rpm_file is not None:
59
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
60
+
61
  data = {
62
+ "sr_target": str(sr_target),
63
+ "n_fft": str(n_fft),
64
+ "hop": str(hop),
65
+ "env_band": env_band,
66
+ "run_llm": "true" if run_llm else "false",
67
  "extra_text": notes or "",
68
+ # cache-bypass hint for proxies/CDNs (backend already sets no-store)
69
+ "nonce": str(time.time())
70
  }
71
+ r = requests.post(f"{API_BASE}/analyze", headers=HEADERS, files=files, data=data, timeout=240)
72
  r.raise_for_status()
73
  return r.json()
74
 
 
79
  if rpm_file is not None:
80
  files["rpm_csv"] = (rpm_file.name, rpm_file.getvalue(), "text/csv")
81
  data = {
82
+ "sr_target": str(sr_target),
83
+ "n_fft": str(n_fft),
84
+ "hop": str(hop),
85
+ "env_band": env_band,
86
+ "run_llm": "true" if run_llm else "false",
87
  "extra_text": notes or "",
88
+ "nonce": str(time.time())
89
  }
90
+ r = requests.post(f"{API_BASE}/analyze_zip", headers=HEADERS, files=files, data=data, timeout=300, stream=True)
91
  r.raise_for_status()
92
  return r.content
93
 
94
+ # ================= Sidebar =================
95
  with st.sidebar:
96
  st.header("Upload")
97
+ audio_up = st.file_uploader("Engine recording (WAV/MP3/M4A)", type=["wav", "mp3", "m4a"])
98
  rpm_up = st.file_uploader("Optional RPM CSV (time_sec,rpm)", type=["csv"])
99
 
100
  st.header("Options")
101
+ run_llm = st.toggle("Explain with AI", value=True, help="Get a readable diagnosis and next steps.")
102
  user_notes = st.text_area("Context (optional)", placeholder="Vehicle, engine type, driving condition, symptoms…")
103
 
104
  with st.expander("Advanced (defaults are fine)"):
105
+ sr_target = st.select_slider("Sample rate (Hz)", options=[16000, 22050, 32000, 44100, 48000], value=22050)
106
+ n_fft = st.select_slider("Analysis window (n_fft)", options=[1024, 2048, 4096], value=2048)
107
+ hop = st.select_slider("Hop length", options=[128, 256, 512, 1024], value=512)
108
  env_band = st.text_input("Impact band (Hz low,high or 'auto')", value="auto")
109
 
110
+ if not API_BASE:
111
+ st.error("Backend URL is not set. Define CARDIAG_AI_API (or AI_LIGHTBOX_API / LUXFIT_API).")
112
+ ok = _health(API_BASE, HEADERS) if API_BASE else False
113
+ if not ok and API_BASE:
114
+ st.warning("Could not reach the backend. Verify your private Space URL.")
115
  analyze_btn = st.button("Analyze now", type="primary", disabled=(audio_up is None or not ok))
116
 
117
+ # Clear old result if user picks a different file (prevents “same result” confusion)
118
+ if "last_audio_id" not in st.session_state:
119
+ st.session_state["last_audio_id"] = None
120
+ if audio_up is not None:
121
+ _aid = hashlib.sha256(audio_up.getvalue()).hexdigest()[:12]
122
+ if st.session_state["last_audio_id"] != _aid:
123
+ st.session_state["last_audio_id"] = _aid
124
+ st.session_state.pop("last_result", None)
125
+
126
  status_ph = st.empty()
127
 
128
+ # ================= Action =================
129
  if analyze_btn and audio_up is not None:
130
  status_ph.info("Analyzing…")
131
  t0 = time.time()
 
139
  status_ph.error(f"Request failed: {e}")
140
 
141
  res = st.session_state.get("last_result")
142
+
143
+ # ================= Result =================
144
  if res:
145
  st.subheader("Result")
146
 
147
  llm = res.get("llm_report") or {}
148
+ model_name = llm.get("model", "unknown")
149
+ usage = llm.get("usage") or {}
150
+ params = res.get("params", {})
151
  st.caption(f"AI model: **{model_name}**")
152
  if usage:
153
  st.caption(f"Tokens — prompt: {usage.get('prompt_tokens')}, completion: {usage.get('completion_tokens')}")
154
+ if params.get("audio_id"):
155
+ st.caption(f"Audio ID: **{params['audio_id']}**")
156
+ if params.get("features"):
157
+ feat = params["features"]
158
+ st.caption(
159
+ f"Features — rms: {feat.get('rms'):.4f}, zcr: {feat.get('zcr'):.4f}, "
160
+ f"centroid: {feat.get('centroid'):.1f} Hz, rolloff: {feat.get('rolloff'):.1f} Hz, "
161
+ f"flux: {feat.get('flux'):.2f}"
162
+ )
163
  meta = llm.get("meta", {})
164
  if meta:
165
  st.caption(f"Vision meta — seen_images: {meta.get('seen_images')}, views: {meta.get('views')}")
166
 
167
+ col1, col2 = st.columns([1, 1])
168
  diag_list = llm.get("diagnosis", [])
169
+ notes = llm.get("notes", "")
170
+ next_tests = llm.get("next_tests", "")
171
 
172
  with col1:
173
  st.markdown("**Likely issues**")
174
  if diag_list:
175
  for item in diag_list:
176
+ st.text(str(item.get("label", "Issue")))
177
+ st.progress(_nice_conf(item.get("likelihood", 0)))
178
+ if item.get("evidence"):
179
+ st.caption(item["evidence"])
180
  else:
181
  st.info("No specific faults detected with high confidence.")
182
 
183
  with col2:
184
+ if notes:
185
+ st.markdown("**Mechanic-friendly notes**")
186
+ st.write(notes)
187
+ if next_tests:
188
+ st.markdown("**Suggested next checks**")
189
+ st.write(next_tests)
190
 
191
  st.subheader("Visual checks")
192
+ tabs = st.tabs(["Composite", "Energy over time", "Perceptual view", "Impact pattern", "Signal envelope", "Order view"])
193
+ imgs = res.get("images", {})
194
 
195
  with tabs[0]:
196
+ if imgs.get("composite"):
197
+ st.image(imgs["composite"], caption="Composite diagnostic figure")
198
+ else:
199
+ st.caption("Composite image is not available.")
200
+
201
  with tabs[1]:
202
+ if imgs.get("stft"): st.image(imgs["stft"], caption="Energy distribution across time.")
203
+ else: st.caption("Shown in composite.")
204
+
205
  with tabs[2]:
206
+ if imgs.get("mel"): st.image(imgs["mel"], caption="Perceptually-weighted overview.")
207
+ else: st.caption("Shown in composite.")
208
+
209
  with tabs[3]:
210
+ if imgs.get("envelope_spectrum"): st.image(imgs["envelope_spectrum"], caption="Repetitive impact signature.")
211
+ else: st.caption("Shown in composite.")
212
+
213
  with tabs[4]:
214
+ if imgs.get("envelope_trace"): st.image(imgs["envelope_trace"], caption="Overall intensity trace.")
215
+ else: st.caption("Shown in composite.")
216
+
217
+ with tabs[5]:
218
+ if imgs.get("order_map"): st.image(imgs["order_map"], caption="Patterns that track engine speed.")
219
  else: st.caption("Order view requires an RPM CSV (time_sec,rpm).")
220
 
221
  st.divider()
 
228
  except Exception as e:
229
  st.error(f"ZIP build failed: {e}")
230
  else:
231
+ st.info("Upload an engine recording, optionally add an RPM CSV, then click Analyze.")