mgbam commited on
Commit
6dd3ffc
Β·
verified Β·
1 Parent(s): f25bc7a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -46
app.py CHANGED
@@ -6,6 +6,7 @@ import json
6
  import os # For API key usage
7
  from pathlib import Path
8
  import time
 
9
  import plotly.express as px
10
  import pandas as pd
11
 
@@ -275,54 +276,33 @@ def call_gemini_api(prompt):
275
  api_status.success(f"βœ… Response received from AI ({model.model_name}) in {end_time - start_time:.2f}s.")
276
  time.sleep(1)
277
  api_status.empty()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  try:
279
- json_response_text = response.text.strip()
280
- if json_response_text.startswith("```json"):
281
- json_response_text = json_response_text[7:]
282
- if json_response_text.startswith("```"):
283
- json_response_text = json_response_text[3:]
284
- if json_response_text.endswith("```"):
285
- json_response_text = json_response_text[:-3]
286
- json_start = json_response_text.find('{')
287
- json_end = json_response_text.rfind('}') + 1
288
- if json_start != -1 and json_end != -1 and json_end > json_start:
289
- final_json_text = json_response_text[json_start:json_end]
290
- insights = json.loads(final_json_text)
291
- return insights, None
292
- else:
293
- st.warning("⚠️ Could not find valid JSON object.")
294
- return {"raw_response": response.text}, "AI response did not contain clear JSON object."
295
- except json.JSONDecodeError as json_err:
296
- st.error(f"🚨 Error parsing JSON: {json_err}")
297
- st.code(response.text, language='text')
298
- return None, f"AI response not valid JSON: {json_err}"
299
- except AttributeError:
300
- st.error("🚨 Unexpected API response structure (AttributeError).")
301
  st.code(f"Response object: {response}", language='text')
302
- return None, "Unexpected response structure (AttributeError)."
303
- except Exception as e:
304
- st.error(f"🚨 Unexpected issue processing response: {e}")
305
- try:
306
- st.code(f"Response object: {response}", language='text')
307
- except Exception:
308
- pass
309
- return None, f"Unexpected response structure: {e}"
310
- except Exception as e:
311
- api_status.empty()
312
- st.error(f"🚨 API call error: {e}")
313
- error_msg = f"API call failed: {e}"
314
- if hasattr(e, 'message'):
315
- if "429" in e.message:
316
- error_msg = "API Quota Exceeded or Rate Limit hit."
317
- elif "API key not valid" in e.message:
318
- error_msg = "Invalid Gemini API Key."
319
- elif "permission denied" in e.message.lower():
320
- error_msg = f"Permission Denied for model '{st.session_state.selected_model_name}'. Check API key access."
321
- elif "blocked" in e.message.lower():
322
- error_msg = "Content blocked due to safety settings."
323
- elif "block_reason: SAFETY" in str(e):
324
- error_msg = "Content blocked due to safety settings."
325
- return None, error_msg
326
 
327
  def display_results(results_json, requested_analyses):
328
  """
 
6
  import os # For API key usage
7
  from pathlib import Path
8
  import time
9
+ import re
10
  import plotly.express as px
11
  import pandas as pd
12
 
 
276
  api_status.success(f"βœ… Response received from AI ({model.model_name}) in {end_time - start_time:.2f}s.")
277
  time.sleep(1)
278
  api_status.empty()
279
+
280
+ # Improved JSON extraction using regex
281
+ json_response_text = response.text.strip()
282
+ json_response_text = json_response_text.replace("```json", "").replace("```", "")
283
+ match = re.search(r'({.*})', json_response_text, re.DOTALL)
284
+ if match:
285
+ final_json_text = match.group(1)
286
+ insights = json.loads(final_json_text)
287
+ return insights, None
288
+ else:
289
+ st.warning("⚠️ Could not find valid JSON object.")
290
+ return {"raw_response": response.text}, "AI response did not contain clear JSON object."
291
+ except json.JSONDecodeError as json_err:
292
+ st.error(f"🚨 Error parsing JSON: {json_err}")
293
+ st.code(response.text, language='text')
294
+ return None, f"AI response not valid JSON: {json_err}"
295
+ except AttributeError:
296
+ st.error("🚨 Unexpected API response structure (AttributeError).")
297
+ st.code(f"Response object: {response}", language='text')
298
+ return None, "Unexpected response structure (AttributeError)."
299
+ except Exception as e:
300
+ st.error(f"🚨 Unexpected issue processing response: {e}")
301
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  st.code(f"Response object: {response}", language='text')
303
+ except Exception:
304
+ pass
305
+ return None, f"Unexpected response structure: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
  def display_results(results_json, requested_analyses):
308
  """