Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,506 +1,58 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
return nome_limpo + ".json"
|
| 60 |
-
|
| 61 |
-
def extrair_texto_pdf(caminho_pdf):
|
| 62 |
-
try:
|
| 63 |
-
with open(caminho_pdf, 'rb') as f:
|
| 64 |
-
reader = PyPDF2.PdfReader(f)
|
| 65 |
-
paginas = []
|
| 66 |
-
for i, page in enumerate(reader.pages):
|
| 67 |
-
texto = page.extract_text()
|
| 68 |
-
paginas.append({
|
| 69 |
-
"numero": i + 1,
|
| 70 |
-
"texto": texto,
|
| 71 |
-
"metadata": str(page)[:200]
|
| 72 |
-
})
|
| 73 |
-
return paginas, None
|
| 74 |
-
except Exception as e:
|
| 75 |
-
return None, str(e)
|
| 76 |
-
|
| 77 |
-
def fragmentar_pdf(paginas, tamanho_chunk=PAGES_PER_CHUNK):
|
| 78 |
-
chunks = []
|
| 79 |
-
for i in range(0, len(paginas), tamanho_chunk):
|
| 80 |
-
chunk = paginas[i:i + tamanho_chunk]
|
| 81 |
-
num_inicio = chunk[0]["numero"]
|
| 82 |
-
num_fim = chunk[-1]["numero"]
|
| 83 |
-
|
| 84 |
-
texto_consolidado = "\n---QUEBRA DE PÁGINA---\n".join(
|
| 85 |
-
[f"[PÁGINA {p['numero']}]\n{p['texto']}" for p in chunk]
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
chunks.append({
|
| 89 |
-
"id": f"chunk_{num_inicio}_{num_fim}",
|
| 90 |
-
"paginas": f"{num_inicio}-{num_fim}",
|
| 91 |
-
"num_paginas": len(chunk),
|
| 92 |
-
"texto": texto_consolidado,
|
| 93 |
-
"metadata": [p["metadata"] for p in chunk]
|
| 94 |
-
})
|
| 95 |
-
return chunks
|
| 96 |
-
|
| 97 |
-
def processar_pdf_completo(arquivo_pdf):
|
| 98 |
-
if not PDF_SUPPORT:
|
| 99 |
-
return None, "❌ PyPDF2 não disponível"
|
| 100 |
-
|
| 101 |
-
try:
|
| 102 |
-
paginas, erro = extrair_texto_pdf(arquivo_pdf.name if hasattr(arquivo_pdf, 'name') else arquivo_pdf)
|
| 103 |
-
if erro:
|
| 104 |
-
return None, f"❌ Erro ao ler PDF: {erro}"
|
| 105 |
-
|
| 106 |
-
chunks = fragmentar_pdf(paginas)
|
| 107 |
-
nome_arquivo = os.path.basename(arquivo_pdf.name if hasattr(arquivo_pdf, 'name') else arquivo_pdf)
|
| 108 |
-
|
| 109 |
-
return {
|
| 110 |
-
"arquivo": nome_arquivo,
|
| 111 |
-
"total_paginas": len(paginas),
|
| 112 |
-
"total_chunks": len(chunks),
|
| 113 |
-
"chunks": chunks,
|
| 114 |
-
"tipo": "pdf"
|
| 115 |
-
}, None
|
| 116 |
-
except Exception as e:
|
| 117 |
-
return None, f"❌ Erro no processamento: {str(e)}"
|
| 118 |
-
|
| 119 |
-
def ler_arquivo_texto(arquivo):
|
| 120 |
-
if arquivo is None: return None
|
| 121 |
-
try:
|
| 122 |
-
with open(arquivo.name, "r", encoding="utf-8") as f:
|
| 123 |
-
conteudo = f.read()
|
| 124 |
-
return {
|
| 125 |
-
"arquivo": os.path.basename(arquivo.name),
|
| 126 |
-
"conteudo": conteudo,
|
| 127 |
-
"tipo": "texto"
|
| 128 |
-
}
|
| 129 |
-
except: return None
|
| 130 |
-
|
| 131 |
-
# ==================== 3. PIPELINE DE IA ====================
|
| 132 |
-
|
| 133 |
-
def transcrever_chunk(chunk_data, config_agentes):
|
| 134 |
-
# Função auxiliar para ser executada na thread
|
| 135 |
-
modelo = model_flash
|
| 136 |
-
try:
|
| 137 |
-
if config_agentes and isinstance(config_agentes, list):
|
| 138 |
-
if config_agentes[0].get("modelo") == "pro":
|
| 139 |
-
modelo = model_pro
|
| 140 |
-
except:
|
| 141 |
-
pass
|
| 142 |
-
|
| 143 |
-
prompt = f"""
|
| 144 |
-
ANÁLISE DE DOCUMENTO (OCR/LEITURA):
|
| 145 |
-
Transcreva e estruture o conteúdo das páginas {chunk_data['paginas']}.
|
| 146 |
-
Texto extraído:
|
| 147 |
-
{chunk_data['texto']}
|
| 148 |
-
|
| 149 |
-
Retorne JSON: {{ "transcricao": "...", "objetos": ["..."], "resumo": "..." }}
|
| 150 |
-
"""
|
| 151 |
-
try:
|
| 152 |
-
# Retry simples em caso de erro 429 (rate limit)
|
| 153 |
-
for tentativa in range(3):
|
| 154 |
-
try:
|
| 155 |
-
resposta = modelo.generate_content(prompt)
|
| 156 |
-
texto_resp = resposta.text.replace("```json", "").replace("```", "")
|
| 157 |
-
return json.loads(texto_resp.strip()), None
|
| 158 |
-
except Exception as inner_e:
|
| 159 |
-
if "429" in str(inner_e):
|
| 160 |
-
time.sleep(2 * (tentativa + 1))
|
| 161 |
-
continue
|
| 162 |
-
raise inner_e
|
| 163 |
-
except Exception as e:
|
| 164 |
-
return None, str(e)
|
| 165 |
-
|
| 166 |
-
# ==================== 4. GERENCIADOR DE ARQUIVOS ====================
|
| 167 |
-
|
| 168 |
-
class GerenciadorArquivos:
|
| 169 |
-
def __init__(self):
|
| 170 |
-
self.arquivos = {}
|
| 171 |
-
|
| 172 |
-
def adicionar(self, arquivo, arquivo_id):
|
| 173 |
-
self.arquivos[arquivo_id] = {
|
| 174 |
-
"arquivo": arquivo,
|
| 175 |
-
"nome": os.path.basename(arquivo.name),
|
| 176 |
-
"status": "adicionado",
|
| 177 |
-
"processado": None,
|
| 178 |
-
"transcricao": None
|
| 179 |
-
}
|
| 180 |
-
|
| 181 |
-
def gerar_prompt_com_transcricoes(self, texto_usuario):
|
| 182 |
-
prompt = texto_usuario + "\n\n--- CONTEXTO DOS ARQUIVOS ---\n"
|
| 183 |
-
count = 0
|
| 184 |
-
for _, item in self.arquivos.items():
|
| 185 |
-
if item["status"] == "processado" and item["transcricao"]:
|
| 186 |
-
count += 1
|
| 187 |
-
trans = item["transcricao"]
|
| 188 |
-
nome = item["nome"]
|
| 189 |
-
prompt += f"\n[ARQUIVO: {nome}]\n"
|
| 190 |
-
|
| 191 |
-
if isinstance(trans, dict) and "chunks_processados" in trans:
|
| 192 |
-
# Como garantimos a ordem na lista chunks_processados, iteramos normalmente
|
| 193 |
-
for chunk in trans["chunks_processados"]:
|
| 194 |
-
if chunk.get("status") == "OK":
|
| 195 |
-
resumo = chunk.get('resumo', '')
|
| 196 |
-
resumo = str(resumo) if resumo else ""
|
| 197 |
-
prompt += f"Páginas {chunk['paginas']}: {resumo}\n"
|
| 198 |
-
|
| 199 |
-
texto_full = chunk.get('transcricao', '')
|
| 200 |
-
if texto_full:
|
| 201 |
-
texto_seguro = str(texto_full)
|
| 202 |
-
prompt += f"Trecho: {texto_seguro[:400]}...\n"
|
| 203 |
-
else:
|
| 204 |
-
prompt += "Trecho: (vazio)\n"
|
| 205 |
-
|
| 206 |
-
elif isinstance(trans, dict) and "conteudo" in trans:
|
| 207 |
-
conteudo = str(trans['conteudo'])
|
| 208 |
-
prompt += f"Conteúdo: {conteudo[:1000]}...\n"
|
| 209 |
-
|
| 210 |
-
if count == 0:
|
| 211 |
-
prompt += "(Nenhum arquivo processado ainda)"
|
| 212 |
-
return prompt
|
| 213 |
-
|
| 214 |
-
# Instância Global
|
| 215 |
-
gerenciador = GerenciadorArquivos()
|
| 216 |
-
|
| 217 |
-
# ==================== 5. FUNÇÕES DE ORQUESTRAÇÃO ====================
|
| 218 |
-
|
| 219 |
-
def automacao_upload_processamento(files, history, config_json):
|
| 220 |
-
if not files:
|
| 221 |
-
return history
|
| 222 |
-
|
| 223 |
-
try:
|
| 224 |
-
config_agentes = json.loads(config_json)
|
| 225 |
-
except:
|
| 226 |
-
config_agentes = []
|
| 227 |
-
|
| 228 |
-
if history is None:
|
| 229 |
-
history = []
|
| 230 |
-
|
| 231 |
-
history.append([None, f"📂 **SISTEMA:** Recebi {len(files)} arquivo(s). Verificando cache e processando..."])
|
| 232 |
-
yield history
|
| 233 |
-
|
| 234 |
-
ids_para_processar = []
|
| 235 |
-
|
| 236 |
-
for f in files:
|
| 237 |
-
arquivo_id = f"arq_{int(time.time()*1000)}_{f.name}"
|
| 238 |
-
gerenciador.adicionar(f, arquivo_id)
|
| 239 |
-
ids_para_processar.append(arquivo_id)
|
| 240 |
-
|
| 241 |
-
for arq_id in ids_para_processar:
|
| 242 |
-
item = gerenciador.arquivos[arq_id]
|
| 243 |
-
nome = item["nome"]
|
| 244 |
-
|
| 245 |
-
# --- VERIFICAÇÃO DE CACHE ---
|
| 246 |
-
nome_cache = limpar_nome_arquivo(nome)
|
| 247 |
-
caminho_cache = os.path.join(PASTA_TRANSCRICOES, nome_cache)
|
| 248 |
-
|
| 249 |
-
if os.path.exists(caminho_cache):
|
| 250 |
-
try:
|
| 251 |
-
with open(caminho_cache, "r", encoding="utf-8") as cache_file:
|
| 252 |
-
dados_cache = json.load(cache_file)
|
| 253 |
-
item["transcricao"] = dados_cache
|
| 254 |
-
item["status"] = "processado"
|
| 255 |
-
if nome.lower().endswith('.pdf') and "chunks_processados" in dados_cache:
|
| 256 |
-
item["processado"] = {"tipo": "pdf", "chunks": []}
|
| 257 |
-
history.append([None, f"♻️ **Cache Encontrado:** `{nome}` já foi processado. Carregando..."])
|
| 258 |
-
yield history
|
| 259 |
-
continue
|
| 260 |
-
except Exception as e:
|
| 261 |
-
history.append([None, f"⚠️ Erro cache `{nome}`: {e}. Reprocessando..."])
|
| 262 |
-
# ---------------------------
|
| 263 |
-
|
| 264 |
-
history.append([None, f"⚙️ **Processando:** `{nome}`..."])
|
| 265 |
-
yield history
|
| 266 |
-
|
| 267 |
-
if nome.lower().endswith('.pdf'):
|
| 268 |
-
if not PDF_SUPPORT:
|
| 269 |
-
history.append([None, f"❌ Erro em `{nome}`: Biblioteca PDF ausente."])
|
| 270 |
-
yield history
|
| 271 |
-
continue
|
| 272 |
-
|
| 273 |
-
pdf_proc, erro = processar_pdf_completo(item["arquivo"])
|
| 274 |
-
if erro:
|
| 275 |
-
history.append([None, f"❌ Erro em `{nome}`: {erro}"])
|
| 276 |
-
yield history
|
| 277 |
-
continue
|
| 278 |
-
|
| 279 |
-
item["processado"] = pdf_proc
|
| 280 |
-
chunks = pdf_proc["chunks"]
|
| 281 |
-
total_chunks = len(chunks)
|
| 282 |
-
|
| 283 |
-
# Inicializa lista com o tamanho exato para garantir a ordem
|
| 284 |
-
chunks_ordenados = [None] * total_chunks
|
| 285 |
-
|
| 286 |
-
history.append([None, f"📄 `{nome}` fragmentado em {total_chunks} partes. Iniciando IA (Paralelo: {MAX_WORKERS} threads)..."])
|
| 287 |
-
yield history
|
| 288 |
-
|
| 289 |
-
# --- PROCESSAMENTO PARALELO ---
|
| 290 |
-
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
|
| 291 |
-
# Dicionário para mapear Future -> Índice Original
|
| 292 |
-
futures_map = {}
|
| 293 |
-
|
| 294 |
-
# Submeter todas as tarefas
|
| 295 |
-
for i, chunk in enumerate(chunks):
|
| 296 |
-
future = executor.submit(transcrever_chunk, chunk, config_agentes)
|
| 297 |
-
futures_map[future] = i
|
| 298 |
-
|
| 299 |
-
# Coletar resultados conforme ficam prontos
|
| 300 |
-
concluidos = 0
|
| 301 |
-
for future in as_completed(futures_map):
|
| 302 |
-
index_original = futures_map[future]
|
| 303 |
-
res, err = future.result()
|
| 304 |
-
|
| 305 |
-
if err:
|
| 306 |
-
chunks_ordenados[index_original] = {"status": "ERRO", "paginas": chunks[index_original]["paginas"]}
|
| 307 |
-
else:
|
| 308 |
-
chunks_ordenados[index_original] = {
|
| 309 |
-
"status": "OK",
|
| 310 |
-
"paginas": chunks[index_original]["paginas"],
|
| 311 |
-
"transcricao": res.get("transcricao"),
|
| 312 |
-
"resumo": res.get("resumo")
|
| 313 |
-
}
|
| 314 |
-
|
| 315 |
-
concluidos += 1
|
| 316 |
-
# Atualiza a UI a cada 2 chunks ou no final para não flodar
|
| 317 |
-
if concluidos % 2 == 0 or concluidos == total_chunks:
|
| 318 |
-
msg_base = f"📄 `{nome}`: Processando partes... ({concluidos}/{total_chunks})"
|
| 319 |
-
history[-1][1] = msg_base
|
| 320 |
-
yield history
|
| 321 |
-
# ------------------------------
|
| 322 |
-
|
| 323 |
-
dados_finais = {
|
| 324 |
-
"arquivo": nome,
|
| 325 |
-
"data_processamento": str(datetime.now()),
|
| 326 |
-
"chunks_processados": chunks_ordenados # Agora contém a lista na ordem correta
|
| 327 |
-
}
|
| 328 |
-
|
| 329 |
-
item["transcricao"] = dados_finais
|
| 330 |
-
item["status"] = "processado"
|
| 331 |
-
|
| 332 |
-
try:
|
| 333 |
-
with open(caminho_cache, "w", encoding="utf-8") as f_out:
|
| 334 |
-
json.dump(dados_finais, f_out, indent=2, ensure_ascii=False)
|
| 335 |
-
history.append([None, f"💾 `{nome}` processado e salvo no cache."])
|
| 336 |
-
except Exception as e:
|
| 337 |
-
history.append([None, f"⚠️ Erro ao salvar cache: {e}"])
|
| 338 |
-
|
| 339 |
-
yield history
|
| 340 |
-
|
| 341 |
-
else:
|
| 342 |
-
# Processamento de Texto Simples (não precisa de paralelismo pois é 1 chunk)
|
| 343 |
-
res = ler_arquivo_texto(item["arquivo"])
|
| 344 |
-
if res:
|
| 345 |
-
item["processado"] = res
|
| 346 |
-
dados_finais = {"conteudo": res["conteudo"], "data_processamento": str(datetime.now())}
|
| 347 |
-
item["transcricao"] = dados_finais
|
| 348 |
-
item["status"] = "processado"
|
| 349 |
-
|
| 350 |
-
with open(caminho_cache, "w", encoding="utf-8") as f_out:
|
| 351 |
-
json.dump(dados_finais, f_out, indent=2, ensure_ascii=False)
|
| 352 |
-
|
| 353 |
-
history.append([None, f"✅ `{nome}` (Texto) lido e salvo."])
|
| 354 |
-
else:
|
| 355 |
-
history.append([None, f"❌ Falha ao ler `{nome}`."])
|
| 356 |
-
yield history
|
| 357 |
-
|
| 358 |
-
history.append([None, "🏁 **Processamento de lote finalizado.** Os arquivos estão prontos para análise."])
|
| 359 |
-
yield history
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
def chat_orquestrador(message, history, config_json):
|
| 363 |
-
"""
|
| 364 |
-
Orquestra a conversa, passando o contexto e as missões para cada agente em sequência.
|
| 365 |
-
Agora também retorna a trilha de auditoria para a nova aba.
|
| 366 |
-
"""
|
| 367 |
-
try:
|
| 368 |
-
prompt_contexto = gerenciador.gerar_prompt_com_transcricoes(message)
|
| 369 |
-
except Exception as e:
|
| 370 |
-
history.append([message, f"❌ Erro ao gerar contexto: {str(e)}"])
|
| 371 |
-
yield history, []
|
| 372 |
-
return
|
| 373 |
-
|
| 374 |
-
try:
|
| 375 |
-
protocolo = json.loads(config_json)
|
| 376 |
-
except:
|
| 377 |
-
history.append([message, "❌ Erro no JSON de Configuração."])
|
| 378 |
-
yield history, []
|
| 379 |
-
return
|
| 380 |
-
|
| 381 |
-
history.append([message, None])
|
| 382 |
-
|
| 383 |
-
# A trilha de auditoria começa com o prompt completo enviado pelo usuário
|
| 384 |
-
timeline_execucao = [{"passo": 1, "tipo": "prompt_usuario", "conteudo": prompt_contexto}]
|
| 385 |
-
yield history, timeline_execucao
|
| 386 |
-
|
| 387 |
-
passo_atual = 2
|
| 388 |
-
for cfg in protocolo:
|
| 389 |
-
nome_agente = cfg.get("nome", "Agente")
|
| 390 |
-
modelo_agente = model_pro if cfg.get("modelo") == "pro" else model_flash
|
| 391 |
-
|
| 392 |
-
# Atualiza o chatbot com o status do agente atual
|
| 393 |
-
msg_atual = history[-1][1] or ""
|
| 394 |
-
history[-1][1] = msg_atual + f"⏳ **{nome_agente}** está analisando...\n"
|
| 395 |
-
yield history, timeline_execucao
|
| 396 |
-
|
| 397 |
-
prompt_agente = f"""
|
| 398 |
-
--- HISTÓRICO DA CONVERSA ATÉ AGORA ---
|
| 399 |
-
{json.dumps(timeline_execucao, ensure_ascii=False, indent=2)}
|
| 400 |
-
-----------------
|
| 401 |
-
Sua Identidade: {nome_agente}
|
| 402 |
-
Sua Missão Específica Agora: {cfg['missao']}
|
| 403 |
-
Responda de forma concisa e direta, focando apenas na sua missão.
|
| 404 |
-
"""
|
| 405 |
-
try:
|
| 406 |
-
inicio = time.time()
|
| 407 |
-
resp = modelo_agente.generate_content(prompt_agente)
|
| 408 |
-
texto_resp = resp.text
|
| 409 |
-
duracao = time.time() - inicio
|
| 410 |
-
|
| 411 |
-
# Adiciona a resposta do agente à trilha de auditoria
|
| 412 |
-
timeline_execucao.append({"passo": passo_atual, "tipo": "resposta_agente", "agente": nome_agente, "resposta": texto_resp})
|
| 413 |
-
|
| 414 |
-
# Remove o status "analisando..." e adiciona a resposta final do agente
|
| 415 |
-
msg_atual = history[-1][1]
|
| 416 |
-
msg_atual = msg_atual.replace(f"⏳ **{nome_agente}** está analisando...\n", "")
|
| 417 |
-
|
| 418 |
-
novo_trecho = f"**[{nome_agente}]** ({duracao:.1f}s):\n{texto_resp}\n\n"
|
| 419 |
-
history[-1][1] = msg_atual + novo_trecho
|
| 420 |
-
yield history, timeline_execucao
|
| 421 |
-
|
| 422 |
-
except Exception as e:
|
| 423 |
-
# Adiciona o erro à trilha de auditoria e ao chat
|
| 424 |
-
timeline_execucao.append({"passo": passo_atual, "tipo": "erro_agente", "agente": nome_agente, "erro": str(e)})
|
| 425 |
-
msg_atual = history[-1][1]
|
| 426 |
-
history[-1][1] = msg_atual.replace(f"⏳ **{nome_agente}** está analisando...\n", "") + f"\n❌ Erro em {nome_agente}: {str(e)}\n"
|
| 427 |
-
yield history, timeline_execucao
|
| 428 |
-
|
| 429 |
-
passo_atual += 1
|
| 430 |
-
|
| 431 |
-
# ==================== 6. UI (Gradio) ====================
|
| 432 |
-
|
| 433 |
-
def ui_v28_corrected():
|
| 434 |
-
css = """
|
| 435 |
-
footer {display: none !important;}
|
| 436 |
-
.contain {border: none !important;}
|
| 437 |
-
"""
|
| 438 |
-
|
| 439 |
-
config_inicial = carregar_protocolo()
|
| 440 |
-
|
| 441 |
-
with gr.Blocks(title="AI Forensics Auto", css=css, theme=gr.themes.Soft()) as app:
|
| 442 |
-
|
| 443 |
-
state_config = gr.State(config_inicial)
|
| 444 |
-
|
| 445 |
-
with gr.Tabs():
|
| 446 |
-
with gr.Tab("💬 Investigação"):
|
| 447 |
-
|
| 448 |
-
chatbot = gr.Chatbot(
|
| 449 |
-
height=550,
|
| 450 |
-
show_label=False,
|
| 451 |
-
show_copy_button=True,
|
| 452 |
-
render_markdown=True
|
| 453 |
-
)
|
| 454 |
-
|
| 455 |
-
with gr.Row():
|
| 456 |
-
txt_input = gr.Textbox(
|
| 457 |
-
scale=8,
|
| 458 |
-
show_label=False,
|
| 459 |
-
placeholder="Digite sua instrução ou pergunta sobre o caso...",
|
| 460 |
-
lines=1
|
| 461 |
-
)
|
| 462 |
-
btn_enviar = gr.Button("Enviar 📨", variant="primary", scale=1)
|
| 463 |
-
|
| 464 |
-
with gr.Accordion("📂 Adicionar Arquivos para Análise", open=False):
|
| 465 |
-
gr.Markdown("Selecione arquivos (PDF, TXT). A transcrição iniciará **automaticamente** e os logs aparecerão no chat acima.")
|
| 466 |
-
file_uploader = gr.File(
|
| 467 |
-
file_count="multiple",
|
| 468 |
-
file_types=[".pdf", ".txt", ".json", ".md"],
|
| 469 |
-
label="Arraste arquivos aqui ou clique para selecionar"
|
| 470 |
-
)
|
| 471 |
-
|
| 472 |
-
# NOVA ABA DE AUDITORIA
|
| 473 |
-
with gr.Tab("🕵️ Auditoria"):
|
| 474 |
-
gr.Markdown("### Trilha de Auditoria\nExibe o histórico completo de prompts e respostas de cada agente na última execução. O conteúdo é atualizado a cada nova mensagem enviada.")
|
| 475 |
-
json_audit = gr.JSON(label="Timeline da Execução da Última Mensagem")
|
| 476 |
-
|
| 477 |
-
with gr.Tab("⚙️ Contexto & Config"):
|
| 478 |
-
gr.Markdown("### Protocolo dos Agentes")
|
| 479 |
-
with gr.Row():
|
| 480 |
-
btn_save_cfg = gr.Button("💾 Salvar Alterações")
|
| 481 |
-
lbl_cfg_status = gr.Label(show_label=False)
|
| 482 |
-
|
| 483 |
-
code_config = gr.Code(value=config_inicial, language="json", label="protocolo.json")
|
| 484 |
-
|
| 485 |
-
btn_save_cfg.click(salvar_protocolo, inputs=[code_config], outputs=[lbl_cfg_status])
|
| 486 |
-
btn_save_cfg.click(lambda x: x, inputs=[code_config], outputs=[state_config])
|
| 487 |
-
|
| 488 |
-
# A ação de clique agora atualiza tanto o chatbot quanto a aba de auditoria
|
| 489 |
-
btn_enviar.click(
|
| 490 |
-
chat_orquestrador,
|
| 491 |
-
inputs=[txt_input, chatbot, state_config],
|
| 492 |
-
outputs=[chatbot, json_audit] # Adicionado json_audit como saída
|
| 493 |
-
).then(
|
| 494 |
-
lambda: "", outputs=[txt_input]
|
| 495 |
-
)
|
| 496 |
-
|
| 497 |
-
file_uploader.upload(
|
| 498 |
-
automacao_upload_processamento,
|
| 499 |
-
inputs=[file_uploader, chatbot, state_config],
|
| 500 |
-
outputs=[chatbot]
|
| 501 |
-
)
|
| 502 |
-
|
| 503 |
-
return app
|
| 504 |
-
|
| 505 |
-
if __name__ == "__main__":
|
| 506 |
-
ui_v28_corrected().launch()
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"fase": 0,
|
| 4 |
+
"nome": "CONTEXTO_INICIAL_VALOR_VIDA",
|
| 5 |
+
"modelo": "flash",
|
| 6 |
+
"tipo_saida": "json",
|
| 7 |
+
"missao": "INICIAR PELO RACIOCÍNIO DO USUÁRIO + CAPTURA BRUTA.\n\nObjetivos:\n- Fazer o usuário pensar se já sabe a resposta (valor ou faixa justa) antes de pedir cálculo automatizado.\n- Capturar fatos básicos, contexto do dano e um primeiro palpite intuitivo.\n- Detectar dúvida real e, em caso de dúvida, NÃO avançar para a Fase 1 sem um teste de reflexão.\n\nLógicas:\n- Se EXPECTATIVA_VALOR for vaga, contraditória ou não alinhada ao contexto → DUVIDA_DETECTADA = true.\n- Se DUVIDA_DETECTADA = true → PROXIMA_ACAO = \"PERGUNTAR_USUARIO\".\n- Se DUVIDA_DETECTADA = false → PROXIMA_ACAO = \"AVANCAR_FASE_1\".\n\nRetorne JSON:\n1. PERGUNTA_NORMALIZADA\n2. CONTEXTO_IDENTIFICADO {tipo_caso: [LESAO_LEVE|GRAVE|GRAVISSIMA|MORTE|OUTRO], foro: [cível|criminal|trabalhista|outro]}\n3. RESUMO_FATOS_INICIAIS {em_ate_500_caracteres}\n4. EXPECTATIVA_VALOR_INICIAL {sabe_valor: true/false, faixa_sugerida: {min, max}, justificativa_intuitiva}\n5. NIVEL_CERTEZA_USUARIO (0-10)\n6. DADOS_MINIMOS_NEXO {houve_evento: true/false, houve_dano: true/false, sente_relacao_causa_efeito: true/false}\n7. AFETO_RAW {amor, medo, paixa}\n8. FELICIDADE_LATENTE\n9. SINAIS_DUVIDA {contradicoes, lacunas_obvias}\n10. DUVIDA_DETECTADA {true|false}\n11. TESTE_REFLEXAO {\n perguntas: [\n \"O que exatamente aconteceu, em ordem temporal?\",\n \"Se você fosse juiz, que valor consideraria minimamente justo e por quê?\",\n \"Existe algum caso parecido que você conhece? O que aconteceu lá?\"\n ],\n instrucoes_ao_usuario: \"Responda com calma a cada pergunta. O sistema só seguirá quando houver clareza mínima sobre fatos e sua própria expectativa.\"\n }\n12. PROXIMA_ACAO {\"PERGUNTAR_USUARIO\"|\"AVANCAR_FASE_1\"}\n\nRegras:\n- Não tirar conclusões jurídicas.\n- Se PROXIMA_ACAO = \"PERGUNTAR_USUARIO\", o app NÃO chama a próxima missão; mostra TESTE_REFLEXAO ao usuário e aguarda novas respostas."
|
| 8 |
+
},
|
| 9 |
+
{
|
| 10 |
+
"fase": 1,
|
| 11 |
+
"nome": "HISTORICO_VIDA_E_REDE_AFETIVA",
|
| 12 |
+
"modelo": "flash",
|
| 13 |
+
"tipo_saida": "json",
|
| 14 |
+
"missao": "MAPEAR VIDA, PAPÉIS E REDE AFETIVA PARA VALOR_DA_VIDA/DIGNIDADE.\n\nObjetivos:\n- Clarificar quem era/é a vítima na sua biografia: trabalho, família, sonhos, vulnerabilidades.\n- Entender a rede de dependência e afeto (cônjuge, filhos, pais, etc.).\n- Preparar terreno para valorar a perda/lesão na dimensão existencial.\n\nJSON:\n1. PERFIL_VITIMA {idade, genero, profissao, renda_media, estado_civil}\n2. PAPEL_SOCIAL_CENTRAL {provedor_familiar, cuidador, estudante, aposentado, outro}\n3. DEPENDENTES_DIRETOS {quantidade, tipos: [filhos, pais, conjuges, outros]}\n4. PROJETOS_DE_VIDA {curto_prazo, longo_prazo}\n5. VULNERABILIDADE_PREVIA {pobreza, doenca_preexistente, deficiencia, nenhum}\n6. REDE_AFETIVA {lista_pessoas_chave, grau_dependencia_emocional: 0-10}\n7. IMPACTO_POTENCIAL_PERDA {descricao_curta, intensidade: 0-10}\n8. COERENCIA_COM_CONTEXTO_INICIAL {coerente|parcial|incoerente}\n9. LACUNAS_HISTORICO_VIDA [lista]\n10. SUGESTAO_PERGUNTAS_ADICIONAIS_USUARIO [lista]"
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"fase": 2,
|
| 18 |
+
"nome": "FATO_DANO_E_NEXO_CAUSAL",
|
| 19 |
+
"modelo": "flash",
|
| 20 |
+
"tipo_saida": "json",
|
| 21 |
+
"missao": "CLAREAR FATO, DANO E NEXO CAUSAL DE FORMA ESTRUTURADA.\n\nObjetivos:\n- Organizar, de forma lógica, o que aconteceu, que dano houve e qual nexo alegado.\n- Separar fato objetivo de percepção subjetiva.\n\nJSON:\n1. FATO_GERADOR_LINEAR {linha_do_tempo: [eventos_em_ordem]}\n2. TIPO_EVENTO {acidente_transito, erro_medico, violencia_domestica, crime_intencional, outro}\n3. DANO_CORPORAL_CLASSIFICACAO {LEVE|GRAVE|GRAVISSIMA|MORTE|SEM_INFORMACAO}\n4. DANO_CONCRETO_DESCRITO {lesoes, sequelas, morte, dano_estetico}\n5. PROVAS_DISPONIVEIS {laudos_medicos, boletim_ocorrencia, fotos, videos, testemunhas}\n6. NARRATIVA_NEXO_CAUSAL {em_ate_500_caracteres}\n7. GRAU_CONFIANCA_NEXO_DECLARADO (autoavaliacao_usuario: 0-10)\n8. AMBIGUIDADES_IDENTIFICADAS {sim|nao, detalhes}\n9. ITENS_QUE_EXIGEM_PERICIA {lista}\n10. COERENCIA_FATO_NEXO {alta|media|baixa}"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"fase": 3,
|
| 25 |
+
"nome": "CONTEXTO_E_CONSEQUENCIAS_DO_DANO",
|
| 26 |
+
"modelo": "flash",
|
| 27 |
+
"tipo_saida": "json",
|
| 28 |
+
"missao": "MAPEAR CONTEXTO E CONSEQUÊNCIAS MATERIAIS, MORAIS E EXISTENCIAIS.\n\nObjetivos:\n- Levantar impactos na vida cotidiana, trabalho, família e psique.\n- Construir a ponte entre gravidade objetiva e dano moral/valor da vida.\n\nJSON:\n1. CONSEQUENCIAS_SAUDE {dor_cronica, limitacao_fisica, dependência_terceiros, tratamento_longo_prazo}\n2. CONSEQUENCIAS_TRABALHO {dias_afastamento, perda_emprego, rebaixamento_funcao, incapacidade_parcial, incapacidade_total}\n3. CONSEQUENCIAS_FAMILIA {rompimento_relacoes, sobrecarga_cuidador, impacto_filhos}\n4. CONSEQUENCIAS_PSICOLOGICAS {ansiedade, depressao, TEPT, medo_constante}\n5. PERDA_QUALIDADE_VIDA (0-10, justificativa)\n6. DESCRICAO_DANO_MORAL_SUBJETIVO {humilhacao, medo_de_morrer, perda_dignidade, luto}\n7. SINTONIA_COM_HISTORICO_VIDA {sim|parcial|nao}\n8. PONTOS_FORTES_DANO_MORAL {lista}\n9. PONTOS_FRACOS_DANO_MORAL {lista}"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"fase": 4,
|
| 32 |
+
"nome": "GRAVIDADE_DANO_E_FAIXA_STJ",
|
| 33 |
+
"modelo": "flash",
|
| 34 |
+
"tipo_saida": "json",
|
| 35 |
+
"missao": "CONECTAR GRAVIDADE DA LESÃO ÀS FAIXAS JURISPRUDENCIAIS DE DANO MORAL.\n\nBaseado em estudos de acórdãos e classificação legal: lesão leve, grave, gravíssima e casos de morte, com faixas típicas de 10 a 600 salários mínimos, variando conforme sequela e incapacidade. [2][3][4][12]\n\nJSON:\n1. CLASSIFICACAO_JURIDICA_LESÃO {LEVE|GRAVE|GRAVISSIMA|MORTE}\n2. CRITERIOS_USADOS {dias_incapacidade, risco_vida, sequela_permanente, incapacidade_trabalho, deformidade}\n3. FAIXA_REFERENCIA_STJ_SM {min_sm, max_sm, mediana_sm}\n4. FAIXA_REFERENCIA_STJ_RS {min_rs, max_rs, mediana_rs}\n5. AJUSTES_POR_CASO_CONCRETO {fatores_agravantes, fatores_atenuantes}\n6. FAIXA_AJUSTADA_RS {min_rs, max_rs}\n7. NOTA_SOBRE_TETOS_E_PISOS {comentario_curto}"
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"fase": 5,
|
| 39 |
+
"nome": "CENARIOS_VALOR_VIDA",
|
| 40 |
+
"modelo": "flash",
|
| 41 |
+
"tipo_saida": "json",
|
| 42 |
+
"missao": "GERAR CENÁRIOS DE VALOR (PRINCIPAL/ALTERNATIVO/IMPROVÁVEL) PARA O DANO À VIDA/DIGNIDADE.\n\nJSON (lista de 3 cenários):\n[\n {\n \"ID\": \"PRINCIPAL\",\n \"DESCRICAO\": \"cenário mais provável com base nas provas e na jurisprudência\",\n \"PRIOR\": 0.6,\n \"VALOR_SUGERIDO_RS\": 0,\n \"SUPOSICOES_CHAVE\": [\"nexo_causal_reconhecido\", \"lesao_grave_sem_tetraplegia\"],\n \"COMPATIBILIDADE_FATOS\": \"alta\",\n \"DANO_MORAL_RS\": {\"min\": 0, \"max\": 0, \"mediano\": 0},\n \"DANO_MATERIAL_RS\": 0,\n \"VALOR_TOTAL_RS\": {\"min\": 0, \"max\": 0, \"mediano\": 0}\n },\n {\n \"ID\": \"ALTERNATIVO\",\n \"PRIOR\": 0.3,\n \"...\": \"estrutura_análoga\"\n },\n {\n \"ID\": \"IMPROVAVEL\",\n \"PRIOR\": 0.1,\n \"...\": \"estrutura_análoga\"\n }\n]\n\nRegra: Σ(PRIOR) = 1.0"
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"fase": 6,
|
| 46 |
+
"nome": "TESTE_JUSTICA_DO_VALOR",
|
| 47 |
+
"modelo": "flash",
|
| 48 |
+
"tipo_saida": "json",
|
| 49 |
+
"missao": "EXPLICAR POR QUE O VALOR ESCOLHIDO É JUSTO E POR QUE OUTROS NÃO SÃO.\n\nJSON:\n1. VALOR_RECOMENDADO_RS\n2. CENARIO_BASE {PRINCIPAL|ALTERNATIVO|IMPROVAVEL}\n3. POR_QUE_ESTE_VALOR {texto_curto: liga_gravidade + historico_vida + consequências + faixa_STJ}\n4. POR_QUE_NAO_VALORES_MENORES [lista_de_itens_curta]\n5. POR_QUE_NAO_VALORES_MAIORES [lista_de_itens_curta]\n6. TESTE_PROPORCIONALIDADE {passou|falhou, justificativa}\n7. TESTE_ENRIQUECIMENTO_SEM_CAUSA {passou|falhou, justificativa}\n8. TESTE_REPARACAO_MINIMA_DIGNA {passou|falhou, justificativa}\n9. MARGEM_DISCRICIONARIEDADE_RS {min, max}"
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"fase": 7,
|
| 53 |
+
"nome": "RELATORIO_VALOR_VIDA",
|
| 54 |
+
"modelo": "pro",
|
| 55 |
+
"tipo_saida": "texto",
|
| 56 |
+
"missao": "GERAR TEXTO FINAL EXPLICANDO O VALOR DA INDENIZAÇÃO À LUZ DA VIDA, HISTÓRIA E GRAVIDADE DO DANO.\n\nEstrutura mínima do texto:\n1. RESUMO_FATOS_E_NEXO\n2. QUEM_ERA_A_VITIMA_E_O_QUE_PERDEU (vida, saúde, projetos, papéis familiares)\n3. GRAVIDADE_DA_LESÃO_E_FAIXA_JURISPRUDENCIAL\n4. CENARIO_ESCOLHIDO_E_VALOR_RECOMENDADO\n5. POR_QUE_ESTE_VALOR (argumento sintético)\n6. POR_QUE_NAO_MENOS (sub-reparação)\n7. POR_QUE_NAO_MAIS (desproporção/enriquecimento)\n8. OBSERVACOES_SOBRE_DUVIDAS_REMANESCENTES_E_LIMITES_DA_ANALISE"
|
| 57 |
+
}
|
| 58 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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