hmgill commited on
Commit
f412687
·
verified ·
1 Parent(s): 320325e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -31
app.py CHANGED
@@ -12,6 +12,7 @@ from pathlib import Path
12
  from PIL import Image
13
 
14
  # --- Safe Input Mocking ---
 
15
  builtins.input = lambda *args: "y"
16
 
17
  # GenAI & ADK Imports
@@ -28,7 +29,7 @@ except ImportError as e:
28
  Sam3Model = None
29
  Sam3Processor = None
30
  root_agent = None
31
- AnalysisDeps = None # <--- FIX: Indented inside except block
32
 
33
  # Optional: Distinctipy for better colors
34
  try:
@@ -268,30 +269,41 @@ async def run_analysis(image_path_str, user_prompt, session_id_state):
268
  yield [{"role": "assistant", "content": error_msg}], None, None, [], None, waiting_df, waiting_df, waiting_df, *empty_slider_updates
269
  return
270
 
271
- # FIX: Add safety check for AnalysisDeps
272
  if AnalysisDeps is None:
273
  error_msg = "❌ Project imports failed. 'AnalysisDeps' is missing. Check your 'cellemetry' package installation."
274
  yield [{"role": "assistant", "content": error_msg}], None, None, [], None, waiting_df, waiting_df, waiting_df, *empty_slider_updates
275
  return
276
 
277
- deps = AnalysisDeps(
278
- sam_model=MODEL_CACHE["model"],
279
- sam_processor=MODEL_CACHE["processor"],
280
- image_path=image_path,
281
- device=MODEL_CACHE["device"],
282
- pixel_size_microns=None
283
- )
284
-
285
- global ACTIVE_RUNNER
286
- ACTIVE_RUNNER = InMemoryRunner(agent=root_agent, app_name="cellemetry_demo")
287
-
288
- session = await ACTIVE_RUNNER.session_service.create_session(
289
- app_name="cellemetry_demo",
290
- user_id="demo_user",
291
- state=deps.to_state_dict()
292
- )
293
-
294
- session_id = session.id
 
 
 
 
 
 
 
 
 
 
 
295
  image_bytes = image_path.read_bytes()
296
  content = types.Content(
297
  role="user",
@@ -394,16 +406,22 @@ async def unified_chat_handler(message, history, session_id, current_img_path):
394
  yield history, session_id, image_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
395
 
396
  final_result = None
397
- async for result in run_analysis(image_path, user_text, session_id):
398
- final_result = result
399
- updated_history = result[0].copy()
400
- if files and len(updated_history) > 0:
401
- # Ensure the user message in history also uses the encoded path
402
- updated_history[0] = {"role": "user", "content": f"![](file={display_path})\n\n{user_text}"}
403
-
404
- # Yield Loop: Pass gr.update() to prevent flickering
405
- yield (updated_history, result[1], image_path, *result[2:], None, gr.update(), gr.update(), gr.update())
406
-
 
 
 
 
 
 
407
  if final_result:
408
  updated_history = final_result[0].copy()
409
  if files and len(updated_history) > 0:
@@ -420,7 +438,7 @@ async def unified_chat_handler(message, history, session_id, current_img_path):
420
  yield history, session_id, current_img_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(), gr.update(), gr.update()
421
 
422
  if not ACTIVE_RUNNER:
423
- history[-1]["content"] = "⚠️ Session expired."
424
  yield history, None, current_img_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(), gr.update(), gr.update()
425
  return
426
 
 
12
  from PIL import Image
13
 
14
  # --- Safe Input Mocking ---
15
+ # Fix: Mock input to prevent hanging on server consoles
16
  builtins.input = lambda *args: "y"
17
 
18
  # GenAI & ADK Imports
 
29
  Sam3Model = None
30
  Sam3Processor = None
31
  root_agent = None
32
+ AnalysisDeps = None # FIX: Correctly indented inside except block
33
 
34
  # Optional: Distinctipy for better colors
35
  try:
 
269
  yield [{"role": "assistant", "content": error_msg}], None, None, [], None, waiting_df, waiting_df, waiting_df, *empty_slider_updates
270
  return
271
 
272
+ # FIX: Safety check for AnalysisDeps availability
273
  if AnalysisDeps is None:
274
  error_msg = "❌ Project imports failed. 'AnalysisDeps' is missing. Check your 'cellemetry' package installation."
275
  yield [{"role": "assistant", "content": error_msg}], None, None, [], None, waiting_df, waiting_df, waiting_df, *empty_slider_updates
276
  return
277
 
278
+ # FIX: Wrap Agent/Runner initialization in try/except to catch crashes here
279
+ try:
280
+ deps = AnalysisDeps(
281
+ sam_model=MODEL_CACHE["model"],
282
+ sam_processor=MODEL_CACHE["processor"],
283
+ image_path=image_path,
284
+ device=MODEL_CACHE["device"],
285
+ pixel_size_microns=None
286
+ )
287
+
288
+ global ACTIVE_RUNNER
289
+ if root_agent is None:
290
+ raise ValueError("Root agent is not loaded.")
291
+
292
+ ACTIVE_RUNNER = InMemoryRunner(agent=root_agent, app_name="cellemetry_demo")
293
+
294
+ session = await ACTIVE_RUNNER.session_service.create_session(
295
+ app_name="cellemetry_demo",
296
+ user_id="demo_user",
297
+ state=deps.to_state_dict()
298
+ )
299
+ session_id = session.id
300
+
301
+ except Exception as e:
302
+ error_msg = f"❌ Agent Initialization Failed: {str(e)}"
303
+ print(error_msg)
304
+ yield [{"role": "assistant", "content": error_msg}], None, None, [], None, waiting_df, waiting_df, waiting_df, *empty_slider_updates
305
+ return
306
+
307
  image_bytes = image_path.read_bytes()
308
  content = types.Content(
309
  role="user",
 
406
  yield history, session_id, image_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(visible=False), gr.update(visible=True), gr.update(visible=False)
407
 
408
  final_result = None
409
+ # FIX: Catch potential generator crashes here to prevent asyncio loop death
410
+ try:
411
+ async for result in run_analysis(image_path, user_text, session_id):
412
+ final_result = result
413
+ updated_history = result[0].copy()
414
+ if files and len(updated_history) > 0:
415
+ # Ensure the user message in history also uses the encoded path
416
+ updated_history[0] = {"role": "user", "content": f"![](file={display_path})\n\n{user_text}"}
417
+
418
+ # Yield Loop: Pass gr.update() to prevent flickering
419
+ yield (updated_history, result[1], image_path, *result[2:], None, gr.update(), gr.update(), gr.update())
420
+ except Exception as e:
421
+ history.append({"role": "assistant", "content": f"❌ Critical Error: {str(e)}"})
422
+ yield history, session_id, image_path, None, gr.CheckboxGroup(), None, waiting_df, waiting_df, waiting_df, *empty_slider_updates, None, gr.update(visible=False), gr.update(visible=False), gr.update(visible=True)
423
+ return
424
+
425
  if final_result:
426
  updated_history = final_result[0].copy()
427
  if files and len(updated_history) > 0:
 
438
  yield history, session_id, current_img_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(), gr.update(), gr.update()
439
 
440
  if not ACTIVE_RUNNER:
441
+ history[-1]["content"] = "⚠️ Session expired or Agent not initialized."
442
  yield history, None, current_img_path, gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), *empty_slider_updates, None, gr.update(), gr.update(), gr.update()
443
  return
444