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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2 |
+
# β PIPELINE v27: UI LIMPA & ESTRUTURA DE ABAS β
|
| 3 |
+
# β Layout: Chat (Aba 1) | Debug (Aba 2) | Config (Aba 3) β
|
| 4 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
import gradio as gr
|
| 12 |
+
import google.generativeai as genai
|
| 13 |
+
|
| 14 |
+
# ==================== 1. CONFIGURAΓΓO ====================
|
| 15 |
+
api_key = os.getenv("GOOGLE_API_KEY", "SUA_API_KEY_AQUI")
|
| 16 |
+
if api_key: genai.configure(api_key=api_key)
|
| 17 |
+
|
| 18 |
+
model_flash = genai.GenerativeModel("gemini-2.0-flash")
|
| 19 |
+
model_pro = genai.GenerativeModel("gemini-2.0-pro")
|
| 20 |
+
|
| 21 |
+
ARQUIVO_CONFIG = "protocolo.json"
|
| 22 |
+
|
| 23 |
+
# ==================== 2. UTILIDADES ====================
|
| 24 |
+
|
| 25 |
+
def carregar_protocolo():
|
| 26 |
+
try:
|
| 27 |
+
with open(ARQUIVO_CONFIG, "r", encoding="utf-8") as f: return f.read()
|
| 28 |
+
except: return "[]"
|
| 29 |
+
|
| 30 |
+
def salvar_protocolo(conteudo):
|
| 31 |
+
try:
|
| 32 |
+
json.loads(conteudo)
|
| 33 |
+
with open(ARQUIVO_CONFIG, "w", encoding="utf-8") as f: f.write(conteudo)
|
| 34 |
+
return "β
Salvo"
|
| 35 |
+
except: return "β Erro JSON"
|
| 36 |
+
|
| 37 |
+
def ler_anexo(arquivo):
|
| 38 |
+
if arquivo is None: return ""
|
| 39 |
+
try:
|
| 40 |
+
with open(arquivo.name, "r", encoding="utf-8") as f:
|
| 41 |
+
return f"\n\n[ANEXO SISTEMA: {os.path.basename(arquivo.name)}]\n{f.read()}\n[FIM ANEXO]\n"
|
| 42 |
+
except: return ""
|
| 43 |
+
|
| 44 |
+
# ==================== 3. ENGINE DE EXECUΓΓO ====================
|
| 45 |
+
|
| 46 |
+
def executar_no(timeline, config):
|
| 47 |
+
modelo = model_pro if config.get("modelo") == "pro" else model_flash
|
| 48 |
+
contexto = json.dumps(timeline, ensure_ascii=False, indent=2)
|
| 49 |
+
prompt = f"--- TIMELINE ---\n{contexto}\n----------------\nAGENTE: {config['nome']}\nMISSΓO: {config['missao']}"
|
| 50 |
+
|
| 51 |
+
log = f"\nπΈ {config['nome']}..."
|
| 52 |
+
try:
|
| 53 |
+
inicio = time.time()
|
| 54 |
+
resp = modelo.generate_content(prompt)
|
| 55 |
+
out = resp.text
|
| 56 |
+
tempo = time.time() - inicio
|
| 57 |
+
|
| 58 |
+
content = json.loads(out.strip().replace('```json','').replace('```','')) if config['tipo_saida']=='json' else out
|
| 59 |
+
log += f" (OK - {tempo:.2f}s)"
|
| 60 |
+
return {"role": "assistant", "agent": config['nome'], "content": content}, log, out
|
| 61 |
+
except Exception as e:
|
| 62 |
+
return {"role": "system", "error": str(e)}, f" (ERRO: {e})", str(e)
|
| 63 |
+
|
| 64 |
+
# ==================== 4. ORQUESTRADOR ====================
|
| 65 |
+
|
| 66 |
+
def orquestrador(texto, arquivo, history, json_config):
|
| 67 |
+
# 1. Input Check
|
| 68 |
+
anexo = ler_anexo(arquivo)
|
| 69 |
+
full_input = f"{texto}\n{anexo}".strip()
|
| 70 |
+
|
| 71 |
+
if not full_input:
|
| 72 |
+
yield history, {}, "Sem input."
|
| 73 |
+
return
|
| 74 |
+
|
| 75 |
+
# 2. Setup
|
| 76 |
+
history = history + [[texto + (" π" if arquivo else ""), None]]
|
| 77 |
+
try: protocolo = json.loads(json_config)
|
| 78 |
+
except:
|
| 79 |
+
history[-1][1] = "β Erro no JSON de ConfiguraΓ§Γ£o."
|
| 80 |
+
yield history, {}, "Erro JSON"
|
| 81 |
+
return
|
| 82 |
+
|
| 83 |
+
timeline = [{"role": "user", "content": full_input}]
|
| 84 |
+
logs = f"π START: {datetime.now().strftime('%H:%M:%S')}\n"
|
| 85 |
+
history[-1][1] = "β³ Iniciando anΓ‘lise..."
|
| 86 |
+
yield history, timeline, logs
|
| 87 |
+
|
| 88 |
+
# 3. Loop
|
| 89 |
+
final_response = ""
|
| 90 |
+
for cfg in protocolo:
|
| 91 |
+
history[-1][1] = f"βοΈ {cfg['nome']} trabalhando..."
|
| 92 |
+
yield history, timeline, logs
|
| 93 |
+
|
| 94 |
+
res, log_add, raw = executar_no(timeline, cfg)
|
| 95 |
+
timeline.append(res)
|
| 96 |
+
logs += log_add + "\n"
|
| 97 |
+
|
| 98 |
+
if cfg['tipo_saida'] == 'texto':
|
| 99 |
+
final_response = res['content']
|
| 100 |
+
history[-1][1] = final_response # Mostra texto progressivo se fosse stream, aqui mostra final
|
| 101 |
+
|
| 102 |
+
yield history, timeline, logs
|
| 103 |
+
|
| 104 |
+
logs += "β
FIM."
|
| 105 |
+
yield history, timeline, logs
|
| 106 |
+
|
| 107 |
+
# ==================== 5. UI LIMPA (v27) ====================
|
| 108 |
+
|
| 109 |
+
def ui_clean():
|
| 110 |
+
css = """
|
| 111 |
+
footer {display: none !important;}
|
| 112 |
+
.contain {border: none !important;}
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
config_init = carregar_protocolo()
|
| 116 |
+
|
| 117 |
+
with gr.Blocks(title="AI Forensics", css=css, theme=gr.themes.Soft()) as app:
|
| 118 |
+
|
| 119 |
+
with gr.Tabs():
|
| 120 |
+
|
| 121 |
+
# === ABA 1: CHAT (LIMPO) ===
|
| 122 |
+
with gr.Tab("π¬ Investigador"):
|
| 123 |
+
chatbot = gr.Chatbot(
|
| 124 |
+
label="",
|
| 125 |
+
show_label=False,
|
| 126 |
+
height=600,
|
| 127 |
+
show_copy_button=True,
|
| 128 |
+
render_markdown=True
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
with gr.Row():
|
| 132 |
+
with gr.Column(scale=10):
|
| 133 |
+
txt_in = gr.Textbox(
|
| 134 |
+
show_label=False,
|
| 135 |
+
placeholder="Descreva o caso ou instruΓ§Γ£o...",
|
| 136 |
+
lines=1,
|
| 137 |
+
max_lines=5,
|
| 138 |
+
container=False
|
| 139 |
+
)
|
| 140 |
+
with gr.Column(scale=1, min_width=50):
|
| 141 |
+
file_in = gr.UploadButton(
|
| 142 |
+
"π",
|
| 143 |
+
file_types=[".txt", ".md", ".csv", ".json"],
|
| 144 |
+
size="sm"
|
| 145 |
+
)
|
| 146 |
+
with gr.Column(scale=1, min_width=80):
|
| 147 |
+
btn_send = gr.Button("Enviar", variant="primary", size="sm")
|
| 148 |
+
|
| 149 |
+
# Feedback visual sutil do arquivo
|
| 150 |
+
file_status = gr.Markdown("", visible=True)
|
| 151 |
+
file_in.upload(lambda x: f"π Anexo: {os.path.basename(x.name)}", file_in, file_status)
|
| 152 |
+
|
| 153 |
+
# === ABA 2: DEPURAΓΓO (ESCONDIDO) ===
|
| 154 |
+
with gr.Tab("π΅οΈ DepuraΓ§Γ£o"):
|
| 155 |
+
with gr.Row():
|
| 156 |
+
out_dna = gr.JSON(label="DNA (Timeline)")
|
| 157 |
+
out_logs = gr.Textbox(label="Logs do Sistema", lines=20)
|
| 158 |
+
|
| 159 |
+
# === ABA 3: CONFIG (TΓCNICO) ===
|
| 160 |
+
with gr.Tab("βοΈ Config"):
|
| 161 |
+
with gr.Row():
|
| 162 |
+
btn_save = gr.Button("Salvar Config")
|
| 163 |
+
lbl_save = gr.Label(show_label=False)
|
| 164 |
+
code_json = gr.Code(value=config_init, language="json", label="protocolo.json")
|
| 165 |
+
btn_save.click(salvar_protocolo, code_json, lbl_save)
|
| 166 |
+
|
| 167 |
+
# === TRIGGERS ===
|
| 168 |
+
# Enter ou BotΓ£o Enviar
|
| 169 |
+
triggers = [btn_send.click, txt_in.submit]
|
| 170 |
+
|
| 171 |
+
for trig in triggers:
|
| 172 |
+
trig(
|
| 173 |
+
orquestrador,
|
| 174 |
+
inputs=[txt_in, file_in, chatbot, code_json],
|
| 175 |
+
outputs=[chatbot, out_dna, out_logs]
|
| 176 |
+
).then(
|
| 177 |
+
lambda: (None, ""), # Limpa input e label do arquivo apΓ³s envio
|
| 178 |
+
outputs=[txt_in, file_status]
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
return app
|
| 182 |
+
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
+
ui_clean().launch()
|