Spaces:
Paused

caarleexx commited on
Commit
8ca8e9f
·
verified ·
1 Parent(s): 9834115

Update frontend/app.py

Browse files
Files changed (1) hide show
  1. frontend/app.py +70 -20
frontend/app.py CHANGED
@@ -18,6 +18,11 @@ from concurrent.futures import ThreadPoolExecutor
18
  BACKEND_API_URL = os.getenv("BACKEND_API_URL", "http://0.0.0.0:8000")
19
  _executor = ThreadPoolExecutor(max_workers=4)
20
 
 
 
 
 
 
21
 
22
  HF_TOKEN = os.getenv("HF_TOKEN")
23
  if HF_TOKEN:
@@ -375,6 +380,20 @@ async def gerar_pdf(pergunta: str, docs: List[Dict], assuntos_cnj: List[Dict] =
375
  loop = asyncio.get_event_loop()
376
  return await loop.run_in_executor(_executor, _gerar_pdf_sync, pergunta, docs, assuntos_cnj or [])
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  # ──────────────────────────────────────────────────────────────────────
379
  # BACKEND CHECK (usa BACKEND_API_URL)
380
  # ──────────────────────────────────────────────────────────────────────
@@ -488,6 +507,8 @@ async def main(message: cl.Message):
488
  error_msg: str = ""
489
  token_buffer: List[str] = []
490
  pdf_future = None
 
 
491
 
492
  async with cl.Step(
493
  name="🔬 Pesquisa e andamento",
@@ -520,11 +541,18 @@ async def main(message: cl.Message):
520
  elif tipo == "docs":
521
  docs_data = evento.get("docs", [])
522
  assuntos_cnj = evento.get("assuntos_cnj", [])
523
- if docs_data:
524
  pdf_future = asyncio.ensure_future(
525
  gerar_pdf(message.content.strip(), docs_data, assuntos_cnj)
526
  )
527
 
 
 
 
 
 
 
 
528
  elif tipo == "done":
529
  for f in FASES:
530
  fase_status[f["idx"]] = "done"
@@ -591,25 +619,47 @@ async def main(message: cl.Message):
591
 
592
  resposta_msg.content = texto_completo
593
 
594
- if pdf_future is not None:
595
- try:
596
- pdf_path = await pdf_future
597
- data_str = datetime.now().strftime("%Y%m%d_%H%M")
598
- resposta_msg.elements = [
599
- cl.File(
600
- name=f"paraai_tjpr_{data_str}.pdf",
601
- path=pdf_path,
602
- display="inline",
 
 
 
 
603
  )
604
- ]
605
- async def cleanup():
606
- await asyncio.sleep(600)
607
- try: os.unlink(pdf_path)
608
- except Exception: pass
609
- asyncio.create_task(cleanup())
610
- except ImportError:
611
- pass
612
- except Exception:
613
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
 
615
  await resposta_msg.update()
 
18
  BACKEND_API_URL = os.getenv("BACKEND_API_URL", "http://0.0.0.0:8000")
19
  _executor = ThreadPoolExecutor(max_workers=4)
20
 
21
+ # ── FEATURE FLAGS ────────────────────────────────────────────────────────
22
+ # Ative/desative via estas constantes (uso interno)
23
+ SHOW_PDF = True # Gera e anexa o relatório PDF ao final da resposta
24
+ SHOW_DEBUG = True # Gera e anexa o debug.json (cadeia de ações da orquestração)
25
+
26
 
27
  HF_TOKEN = os.getenv("HF_TOKEN")
28
  if HF_TOKEN:
 
380
  loop = asyncio.get_event_loop()
381
  return await loop.run_in_executor(_executor, _gerar_pdf_sync, pergunta, docs, assuntos_cnj or [])
382
 
383
+
384
+ async def gerar_debug_json(debug_data: dict) -> str:
385
+ """
386
+ Persiste o payload de debug em um arquivo JSON temporário.
387
+ Sem limite de tamanho — uso interno para depuração da orquestração.
388
+ Estrutura: { pergunta, session_id, timestamp, modelos, etapas: [{input, reasoning, output}] }
389
+ """
390
+ tmp = tempfile.NamedTemporaryFile(
391
+ suffix=".json", prefix="paraai_debug_", delete=False, mode="w", encoding="utf-8"
392
+ )
393
+ json.dump(debug_data, tmp, ensure_ascii=False, indent=2)
394
+ tmp.close()
395
+ return tmp.name
396
+
397
  # ──────────────────────────────────────────────────────────────────────
398
  # BACKEND CHECK (usa BACKEND_API_URL)
399
  # ──────────────────────────────────────────────────────────────────────
 
507
  error_msg: str = ""
508
  token_buffer: List[str] = []
509
  pdf_future = None
510
+ debug_data: dict = {}
511
+ debug_future = None
512
 
513
  async with cl.Step(
514
  name="🔬 Pesquisa e andamento",
 
541
  elif tipo == "docs":
542
  docs_data = evento.get("docs", [])
543
  assuntos_cnj = evento.get("assuntos_cnj", [])
544
+ if docs_data and SHOW_PDF:
545
  pdf_future = asyncio.ensure_future(
546
  gerar_pdf(message.content.strip(), docs_data, assuntos_cnj)
547
  )
548
 
549
+ elif tipo == "debug":
550
+ debug_data = evento # armazena o payload completo
551
+ if SHOW_DEBUG:
552
+ debug_future = asyncio.ensure_future(
553
+ gerar_debug_json(debug_data)
554
+ )
555
+
556
  elif tipo == "done":
557
  for f in FASES:
558
  fase_status[f["idx"]] = "done"
 
619
 
620
  resposta_msg.content = texto_completo
621
 
622
+ if pdf_future is not None or debug_future is not None:
623
+ elements = []
624
+ data_str = datetime.now().strftime("%Y%m%d_%H%M")
625
+
626
+ if pdf_future is not None:
627
+ try:
628
+ pdf_path = await pdf_future
629
+ elements.append(
630
+ cl.File(
631
+ name=f"paraai_tjpr_{data_str}.pdf",
632
+ path=pdf_path,
633
+ display="inline",
634
+ )
635
  )
636
+ async def cleanup_pdf(p=pdf_path):
637
+ await asyncio.sleep(600)
638
+ try: os.unlink(p)
639
+ except Exception: pass
640
+ asyncio.create_task(cleanup_pdf())
641
+ except Exception:
642
+ pass
643
+
644
+ if debug_future is not None:
645
+ try:
646
+ debug_path = await debug_future
647
+ elements.append(
648
+ cl.File(
649
+ name=f"paraai_debug_{data_str}.json",
650
+ path=debug_path,
651
+ display="inline",
652
+ )
653
+ )
654
+ async def cleanup_debug(p=debug_path):
655
+ await asyncio.sleep(600)
656
+ try: os.unlink(p)
657
+ except Exception: pass
658
+ asyncio.create_task(cleanup_debug())
659
+ except Exception:
660
+ pass
661
+
662
+ if elements:
663
+ resposta_msg.elements = elements
664
 
665
  await resposta_msg.update()