Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -252,6 +252,17 @@ def extract_json_from_text(text):
|
|
252 |
return text[start:i+1]
|
253 |
return None
|
254 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
255 |
def call_gemini_api(prompt):
|
256 |
"""
|
257 |
Calls the Gemini API using the provided prompt.
|
@@ -302,14 +313,24 @@ def call_gemini_api(prompt):
|
|
302 |
if match:
|
303 |
final_json_text = match.group(1)
|
304 |
else:
|
305 |
-
# Fallback: extract using
|
306 |
final_json_text = extract_json_from_text(json_response_text)
|
307 |
-
if final_json_text:
|
308 |
-
insights = json.loads(final_json_text)
|
309 |
-
return insights, None
|
310 |
-
else:
|
311 |
st.warning("⚠️ Could not extract a valid JSON object.")
|
312 |
return {"raw_response": response.text}, "AI response did not contain clear JSON object."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
313 |
except json.JSONDecodeError as json_err:
|
314 |
st.error(f"🚨 Error parsing JSON: {json_err}")
|
315 |
st.code(response.text, language='text')
|
|
|
252 |
return text[start:i+1]
|
253 |
return None
|
254 |
|
255 |
+
def fix_json(text):
|
256 |
+
"""
|
257 |
+
Attempt to fix common JSON formatting issues.
|
258 |
+
This function removes trailing commas and inserts commas between adjacent objects.
|
259 |
+
"""
|
260 |
+
# Remove trailing commas before closing braces
|
261 |
+
text = re.sub(r',\s*}', "}", text)
|
262 |
+
# Insert missing commas between adjacent objects in an array if needed
|
263 |
+
text = re.sub(r'}\s*{', "},{", text)
|
264 |
+
return text
|
265 |
+
|
266 |
def call_gemini_api(prompt):
|
267 |
"""
|
268 |
Calls the Gemini API using the provided prompt.
|
|
|
313 |
if match:
|
314 |
final_json_text = match.group(1)
|
315 |
else:
|
316 |
+
# Fallback: extract using balanced braces method
|
317 |
final_json_text = extract_json_from_text(json_response_text)
|
318 |
+
if not final_json_text:
|
|
|
|
|
|
|
319 |
st.warning("⚠️ Could not extract a valid JSON object.")
|
320 |
return {"raw_response": response.text}, "AI response did not contain clear JSON object."
|
321 |
+
try:
|
322 |
+
insights = json.loads(final_json_text)
|
323 |
+
return insights, None
|
324 |
+
except json.JSONDecodeError as json_err:
|
325 |
+
# Attempt to fix the JSON string and re-parse
|
326 |
+
fixed_text = fix_json(final_json_text)
|
327 |
+
try:
|
328 |
+
insights = json.loads(fixed_text)
|
329 |
+
return insights, None
|
330 |
+
except json.JSONDecodeError as json_err2:
|
331 |
+
st.error(f"🚨 Error parsing JSON after fix attempt: {json_err2}")
|
332 |
+
st.code(response.text, language='text')
|
333 |
+
return None, f"AI response not valid JSON: {json_err2}"
|
334 |
except json.JSONDecodeError as json_err:
|
335 |
st.error(f"🚨 Error parsing JSON: {json_err}")
|
336 |
st.code(response.text, language='text')
|