ryanDing26 commited on
Commit
a666af4
Β·
1 Parent(s): ba91360

this better work

Browse files
Files changed (1) hide show
  1. app.py +104 -2
app.py CHANGED
@@ -303,6 +303,108 @@ def validate_passcode(input_passcode):
303
  gr.update(visible=False),
304
  "❌ Invalid passcode. Please try again."
305
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
 
307
 
308
  # Custom theme
@@ -500,7 +602,7 @@ with gr.Blocks(title="HistoPath Agent", theme=custom_theme, css="""
500
  )
501
 
502
  submit_btn.click(
503
- fn=process_agent_response,
504
  inputs=[prompt_input, file_upload, chatbot],
505
  outputs=[chatbot, output_gallery, data_files, input_image_preview, input_file_preview, status_text]
506
  )
@@ -530,4 +632,4 @@ if __name__ == "__main__":
530
  print("=" * 60)
531
 
532
  # Launch the app
533
- demo.launch()
 
303
  gr.update(visible=False),
304
  "❌ Invalid passcode. Please try again."
305
  )
306
+ # batched streaming instead
307
+ def process_agent_response_batched(prompt, uploaded_file, chatbot_history, batch_size=5):
308
+ """Process agent response with BATCHED updates (every N steps)."""
309
+ global agent
310
+
311
+ if agent is None:
312
+ chatbot_history.append({
313
+ "role": "assistant",
314
+ "content": "⚠️ Please enter the passcode first to initialize the agent."
315
+ })
316
+ yield chatbot_history, None, None, None, None, "⚠️ Agent not initialized"
317
+ return
318
+
319
+ if not prompt.strip() and uploaded_file is None:
320
+ chatbot_history.append({
321
+ "role": "assistant",
322
+ "content": "⚠️ Please provide a prompt or upload a file."
323
+ })
324
+ yield chatbot_history, None, None, None, None, "⚠️ No input provided"
325
+ return
326
+
327
+ # Handle file upload
328
+ file_path = None
329
+ file_info = ""
330
+ if uploaded_file is not None:
331
+ try:
332
+ data_dir = Path("./data")
333
+ data_dir.mkdir(exist_ok=True)
334
+
335
+ file_name = Path(uploaded_file.name).name
336
+ file_path = data_dir / file_name
337
+ shutil.copy(uploaded_file.name, file_path)
338
+
339
+ file_info = f"\n\nπŸ“Ž **Uploaded file:** `{file_path}`\n"
340
+
341
+ if prompt.strip():
342
+ prompt = f"{prompt}\n\nUploaded file path: {file_path}"
343
+ else:
344
+ prompt = f"I have uploaded a file at: {file_path}. Please analyze it."
345
+
346
+ except Exception as e:
347
+ error_msg = f"❌ Error handling file upload: {str(e)}"
348
+ chatbot_history.append({
349
+ "role": "assistant",
350
+ "content": error_msg
351
+ })
352
+ yield chatbot_history, None, None, None, None, error_msg
353
+ return
354
+
355
+ # Add user message to chat
356
+ user_message = prompt if not file_info else f"{prompt}{file_info}"
357
+ chatbot_history.append({"role": "user", "content": user_message})
358
+ yield chatbot_history, None, None, None, None, "πŸ”„ Processing..."
359
+
360
+ try:
361
+ # Stream with batching
362
+ step_count = 0
363
+ batch_count = 0
364
+
365
+ for step in agent.go_stream(prompt):
366
+ step_count += 1
367
+ output = step.get("output", "")
368
+
369
+ if output:
370
+ parsed = parse_agent_output(output)
371
+ formatted_message = format_message_for_display(parsed)
372
+
373
+ # Update chatbot history
374
+ if chatbot_history and chatbot_history[-1]["role"] == "assistant":
375
+ chatbot_history[-1]["content"] = formatted_message
376
+ else:
377
+ chatbot_history.append({
378
+ "role": "assistant",
379
+ "content": formatted_message
380
+ })
381
+
382
+ # Only yield every batch_size steps
383
+ if step_count % batch_size == 0:
384
+ batch_count += 1
385
+ yield chatbot_history, None, None, None, None, f"πŸ”„ Step {step_count}..."
386
+
387
+ # Final yield with files
388
+ images, data = check_for_output_files()
389
+
390
+ status_msg = f"βœ… Complete ({step_count} steps)"
391
+ if images:
392
+ status_msg += f" | {len(images)} image(s)"
393
+ if data:
394
+ status_msg += f" | {len(data)} data file(s)"
395
+
396
+ yield chatbot_history, images, data, None, None, status_msg
397
+
398
+ except Exception as e:
399
+ error_trace = traceback.format_exc()
400
+ error_msg = f"❌ **Error:** {str(e)}\n\n<details>\n<summary>Stack Trace</summary>\n\n```\n{error_trace}\n```\n</details>"
401
+
402
+ chatbot_history.append({
403
+ "role": "assistant",
404
+ "content": error_msg
405
+ })
406
+
407
+ yield chatbot_history, None, None, None, None, f"❌ Error: {str(e)}"
408
 
409
 
410
  # Custom theme
 
602
  )
603
 
604
  submit_btn.click(
605
+ fn=process_agent_response_batched,
606
  inputs=[prompt_input, file_upload, chatbot],
607
  outputs=[chatbot, output_gallery, data_files, input_image_preview, input_file_preview, status_text]
608
  )
 
632
  print("=" * 60)
633
 
634
  # Launch the app
635
+ demo.launch(show_api=False)