from datetime import datetime
from typing import Dict, Any
import httpx
from fastapi import APIRouter, HTTPException, status
from fastapi.responses import StreamingResponse
from db.mongo import collection_resumos_documentos, collection_sinteses
from services.resumo_service import (
stream_existing_summary,
stream_llm_chunks,
aggregator,
obter_texto_pdf,
gerar_prompt_resumo,
gerar_prompt_sintese,
chamar_servico_resumo
)
from utils.logger import logger
# Constantes
TIMEOUT_SECONDS = 60.0
MEDIA_TYPE_EVENT_STREAM = "text/event-stream"
router = APIRouter()
@router.get("/resumir_documento_judicial/{cnj}/{sigla_tribunal}/{id_documento}")
async def resumir_documento_judicial(
cnj: str,
sigla_tribunal: str,
id_documento: str
) -> StreamingResponse:
"""
Resume um documento judicial específico.
Args:
cnj: Código CNJ do processo
sigla_tribunal: Sigla do tribunal
id_documento: ID do documento a ser resumido
Returns:
StreamingResponse: Stream do resumo do documento
Raises:
HTTPException: Erro 500 em caso de falha no processamento
"""
try:
# Busca documento existente
documento_existente = await _buscar_documento_existente(
cnj, sigla_tribunal, id_documento
)
if documento_existente:
logger.info(f"Documento encontrado no cache - CNJ: {cnj}, Tribunal: {sigla_tribunal}")
return StreamingResponse(
stream_existing_summary(documento_existente["resumo"]),
media_type=MEDIA_TYPE_EVENT_STREAM
)
# Processa novo documento
logger.info(f"Processando novo documento - CNJ: {cnj}, Tribunal: {sigla_tribunal}")
return await _processar_novo_documento(cnj, sigla_tribunal, id_documento)
except Exception as e:
logger.error(f"Erro ao resumir documento judicial - CNJ: {cnj}, Erro: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Erro interno ao processar documento: {str(e)}"
)
@router.get("/sintese_demanda/{cnj}/{sigla_tribunal}")
async def gerar_sintese_demanda(cnj: str, sigla_tribunal: str) -> Dict[str, str]:
"""
Gera síntese da demanda de um processo.
Args:
cnj: Código CNJ do processo
sigla_tribunal: Sigla do tribunal
Returns:
Dict contendo a síntese da demanda
Raises:
HTTPException: Erro 500 em caso de falha no processamento
"""
try:
# Busca síntese existente
sintese_existente = await _buscar_sintese_existente(cnj, sigla_tribunal)
if sintese_existente:
logger.info(f"Síntese encontrada no cache - CNJ: {cnj}, Tribunal: {sigla_tribunal}")
return {"sintese": sintese_existente["sintese"]}
# Gera nova síntese
logger.info(f"Gerando nova síntese - CNJ: {cnj}, Tribunal: {sigla_tribunal}")
return await _gerar_nova_sintese(cnj, sigla_tribunal)
except Exception as e:
logger.error(f"Erro ao gerar síntese - CNJ: {cnj}, Erro: {str(e)}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"Erro interno ao gerar síntese: {str(e)}"
)
# Funções auxiliares privadas
async def _buscar_documento_existente(
cnj: str,
sigla_tribunal: str,
id_documento: str
) -> Dict[str, Any] | None:
"""Busca documento existente no banco de dados."""
return await collection_resumos_documentos.find_one({
"cnj": cnj,
"tribunal_sigla": sigla_tribunal,
"id_documento": id_documento
})
async def _buscar_sintese_existente(
cnj: str,
sigla_tribunal: str
) -> Dict[str, Any] | None:
"""Busca síntese existente no banco de dados."""
return await collection_sinteses.find_one({
"cnj": cnj,
"tribunal_sigla": sigla_tribunal
})
async def _processar_novo_documento(
cnj: str,
sigla_tribunal: str,
id_documento: str
) -> StreamingResponse:
"""Processa um novo documento e retorna o stream do resumo."""
# Extrai texto do PDF
texto_extraido = await obter_texto_pdf(cnj, sigla_tribunal, id_documento)
logger.info(f"Texto extraído com sucesso - Tamanho: {len(texto_extraido)} caracteres")
# Gera prompt e payload
prompt = gerar_prompt_resumo(texto_extraido)
payload = {
"messages": [{"role": "user", "content": prompt}],
"stream": True,
}
# Metadados do documento
metadata = {
"cnj": cnj,
"sigla_tribunal": sigla_tribunal,
"id_documento": id_documento
}
# Retorna stream response
return StreamingResponse(
aggregator(
stream_llm_chunks(httpx.AsyncClient(timeout=TIMEOUT_SECONDS), payload),
metadata
),
media_type=MEDIA_TYPE_EVENT_STREAM,
)
async def _gerar_nova_sintese(cnj: str, sigla_tribunal: str) -> Dict[str, str]:
"""Gera uma nova síntese e salva no banco de dados."""
# Extrai texto do PDF (petição)
texto_extraido = await obter_texto_pdf(cnj, sigla_tribunal, tipo="peticao")
logger.info(f"Texto da petição extraído - Tamanho: {len(texto_extraido)} caracteres")
# Gera síntese
prompt = gerar_prompt_sintese(texto_extraido)
resumo = await chamar_servico_resumo(prompt)
# Salva no banco de dados
documento_sintese = {
"cnj": cnj,
"tribunal_sigla": sigla_tribunal,
"sintese": resumo,
"timestamp": datetime.now()
}
await collection_sinteses.insert_one(documento_sintese)
logger.info(f"Síntese salva com sucesso - CNJ: {cnj}, Tribunal: {sigla_tribunal}")
return {"sintese": resumo}