Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2 |
-
# β PIPELINE
|
| 3 |
-
# β
|
| 4 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
|
| 6 |
import os
|
|
@@ -22,10 +22,10 @@ if api_key:
|
|
| 22 |
else:
|
| 23 |
model_flash = model_pro = None
|
| 24 |
|
| 25 |
-
ARQUIVO_CONTEXT = "
|
| 26 |
-
ARQUIVO_HISTORY = "
|
| 27 |
|
| 28 |
-
# ==================== 2. ANALISADOR CONTEXTUAL (CORAΓΓO) ====================
|
| 29 |
class AnalisadorContextual:
|
| 30 |
def __init__(self):
|
| 31 |
self.contexto = self.carregar_contexto()
|
|
@@ -49,15 +49,26 @@ class AnalisadorContextual:
|
|
| 49 |
json.dump(self.contexto, f, ensure_ascii=False, indent=2)
|
| 50 |
except: pass
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
def analisar_input(self, input_atual, history):
|
|
|
|
| 53 |
if not model_pro:
|
| 54 |
-
return self.contexto_fallback()
|
| 55 |
|
| 56 |
history_resumo = "\n".join([f"π€: {h[0][:80]}..." for h in history[-3:]])[:300]
|
| 57 |
|
| 58 |
prompt = f"""CATALOGUE SEM RESPONDER:
|
| 59 |
|
| 60 |
-
INPUT: {input_atual[:400]}
|
| 61 |
HISTΓRICO: {history_resumo}
|
| 62 |
|
| 63 |
JSON:
|
|
@@ -72,16 +83,15 @@ JSON:
|
|
| 72 |
resp = model_pro.generate_content(prompt, temperature=0.1)
|
| 73 |
raw = re.sub(r'``````|\n\s*\n', '', resp.text.strip())
|
| 74 |
analise = json.loads(raw)
|
|
|
|
|
|
|
| 75 |
self.contexto.update(analise)
|
| 76 |
self.aplicar_decainento()
|
| 77 |
self.contexto["timestamp"] = datetime.now().isoformat()
|
| 78 |
self.salvar_contexto()
|
| 79 |
return self.contexto
|
| 80 |
except:
|
| 81 |
-
return self.contexto_fallback()
|
| 82 |
-
|
| 83 |
-
def contexto_fallback(self):
|
| 84 |
-
return {"classificacao": ["dΓΊvida"], "fatos": [], "objetivo_usuario": "AnΓ‘lise geral", "duvida_central": input_atual}
|
| 85 |
|
| 86 |
def aplicar_decainento(self):
|
| 87 |
agora = time.time()
|
|
@@ -89,15 +99,16 @@ JSON:
|
|
| 89 |
for fato in self.contexto.get("fatos", []):
|
| 90 |
peso = fato[1] * 0.95
|
| 91 |
if peso > 0.1:
|
| 92 |
-
novos_fatos.append([fato[0], peso, fato[2],
|
| 93 |
self.contexto["fatos"] = novos_fatos[:15]
|
| 94 |
|
| 95 |
-
# ==================== 3.
|
| 96 |
analisador = AnalisadorContextual()
|
| 97 |
|
|
|
|
| 98 |
def fallback_plano():
|
| 99 |
return [
|
| 100 |
-
{"nome": "Analisador", "missao": "Analise contexto
|
| 101 |
{"nome": "RespostaFinal", "missao": "Resposta clara completa", "modelo": "pro", "tipo_saida": "texto"}
|
| 102 |
]
|
| 103 |
|
|
@@ -105,10 +116,10 @@ def planejar_socrates(contexto, input_atual):
|
|
| 105 |
if not model_pro: return fallback_plano()
|
| 106 |
|
| 107 |
fatos = "\n".join([f"- {f[0]}({f[1]:.1f})" for f in contexto.get("fatos", [])[:4]])
|
| 108 |
-
prompt = f"""CONTEXTO: {contexto}
|
| 109 |
INPUT: {input_atual[:200]}
|
| 110 |
|
| 111 |
-
PLANO
|
| 112 |
[{{"nome":"Explorador","missao":"Levante possibilidades","modelo":"flash","tipo_saida":"json"}},
|
| 113 |
{{"nome":"Validador","missao":"Teste cenΓ‘rios","modelo":"pro","tipo_saida":"json"}},
|
| 114 |
{{"nome":"Final","missao":"Resposta final","modelo":"pro","tipo_saida":"texto"}}]"""
|
|
@@ -136,7 +147,7 @@ def executar_agente(timeline, config):
|
|
| 136 |
except:
|
| 137 |
return {"role": "system", "error": "Erro"}, "ERRO", "Falha"
|
| 138 |
|
| 139 |
-
# ====================
|
| 140 |
def ler_anexo(arquivo):
|
| 141 |
if not arquivo: return ""
|
| 142 |
try:
|
|
@@ -144,7 +155,8 @@ def ler_anexo(arquivo):
|
|
| 144 |
return f"\nπ {os.path.basename(arquivo.name)}:\n{f.read()}\n"
|
| 145 |
except: return ""
|
| 146 |
|
| 147 |
-
def
|
|
|
|
| 148 |
anexo = ler_anexo(arquivo)
|
| 149 |
full_input = f"{texto}{anexo}".strip()
|
| 150 |
|
|
@@ -152,18 +164,19 @@ def orquestrador_v34(texto, arquivo, history, json_config):
|
|
| 152 |
yield history, {}, "Sem input"
|
| 153 |
return
|
| 154 |
|
| 155 |
-
|
|
|
|
| 156 |
timeline = [{"role": "user", "content": full_input}]
|
| 157 |
-
logs = f"π
|
| 158 |
|
| 159 |
yield history, timeline, logs
|
| 160 |
|
| 161 |
-
# 1. ANALISADOR CONTEXTUAL
|
| 162 |
contexto = analisador.analisar_input(full_input, history)
|
| 163 |
-
logs += f"π {len(contexto.get('fatos',[]))} fatos | {contexto.get('classificacao')}\n"
|
| 164 |
timeline.append({"role": "system", "contexto": contexto})
|
| 165 |
|
| 166 |
-
history[-1][1] = f"β
{len(contexto.get('fatos',[]))} fatos
|
| 167 |
yield history, timeline, logs
|
| 168 |
|
| 169 |
# 2. PLANEJADOR SΓCRATES
|
|
@@ -174,7 +187,7 @@ def orquestrador_v34(texto, arquivo, history, json_config):
|
|
| 174 |
history[-1][1] = f"π― {len(plano)} etapas planejadas"
|
| 175 |
yield history, timeline, logs
|
| 176 |
|
| 177 |
-
# 3. EXECUTA
|
| 178 |
for i, agente in enumerate(plano):
|
| 179 |
history[-1][1] = f"[{i+1}/{len(plano)}] {agente['nome']}..."
|
| 180 |
yield history, timeline, logs
|
|
@@ -187,59 +200,61 @@ def orquestrador_v34(texto, arquivo, history, json_config):
|
|
| 187 |
history[-1][1] = str(res['content'])[:900]
|
| 188 |
yield history, timeline, logs
|
| 189 |
|
| 190 |
-
logs += "β
SΓ³crates concluΓdo"
|
| 191 |
yield history, timeline, logs
|
| 192 |
|
| 193 |
-
# ====================
|
| 194 |
-
def
|
| 195 |
css = "footer {display: none !important;} .contain {border: none !important;}"
|
| 196 |
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
with gr.Blocks(title="π PIPELINE v34 - SΓCRATES", css=css, theme=gr.themes.Soft()) as app:
|
| 200 |
-
gr.Markdown("# π§ PIPELINE v34 - ANALISADOR + SΓCRATES")
|
| 201 |
|
| 202 |
with gr.Tabs():
|
|
|
|
| 203 |
with gr.Tab("π¬ Pipeline"):
|
| 204 |
chatbot = gr.Chatbot(height=600, show_copy_button=True, type="tuples")
|
| 205 |
|
| 206 |
with gr.Row():
|
| 207 |
-
txt_in = gr.Textbox(placeholder="Digite input...",
|
|
|
|
| 208 |
file_in = gr.UploadButton("π", file_types=[".txt", ".py", ".json"])
|
| 209 |
btn_send = gr.Button("βΆοΈ Executar", variant="primary")
|
| 210 |
|
| 211 |
file_status = gr.Markdown("")
|
| 212 |
-
file_in.upload(lambda x: f"π {os.path.basename(x.name) if x else ''}",
|
|
|
|
| 213 |
|
|
|
|
| 214 |
with gr.Tab("π Debug"):
|
| 215 |
out_dna = gr.JSON(label="Timeline")
|
| 216 |
out_logs = gr.Textbox(label="Logs", lines=15)
|
| 217 |
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
gr.
|
| 221 |
-
|
| 222 |
-
)
|
| 223 |
|
| 224 |
-
# TRIGGERS
|
| 225 |
btn_send.click(
|
| 226 |
-
|
| 227 |
-
inputs=[txt_in, file_in, chatbot
|
| 228 |
outputs=[chatbot, out_dna, out_logs]
|
| 229 |
).then(lambda: "", outputs=txt_in)
|
| 230 |
|
| 231 |
txt_in.submit(
|
| 232 |
-
|
| 233 |
-
inputs=[txt_in, file_in, chatbot
|
| 234 |
outputs=[chatbot, out_dna, out_logs]
|
| 235 |
).then(lambda: "", outputs=txt_in)
|
| 236 |
|
| 237 |
return app
|
| 238 |
|
| 239 |
if __name__ == "__main__":
|
| 240 |
-
print("π
|
| 241 |
-
print("β
|
| 242 |
-
print("
|
|
|
|
| 243 |
|
| 244 |
-
app =
|
| 245 |
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|
|
|
|
| 1 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 2 |
+
# β PIPELINE v35: SΓCRATES v2 | BUGS FIXADOS | HF SPACES OK β
|
| 3 |
+
# β SEM Textbox extra | contexto_fallback fix | 100% input+history β
|
| 4 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
|
| 6 |
import os
|
|
|
|
| 22 |
else:
|
| 23 |
model_flash = model_pro = None
|
| 24 |
|
| 25 |
+
ARQUIVO_CONTEXT = "contexto_v35.json"
|
| 26 |
+
ARQUIVO_HISTORY = "history_v35.json"
|
| 27 |
|
| 28 |
+
# ==================== 2. ANALISADOR CONTEXTUAL (CORAΓΓO FIXADO) ====================
|
| 29 |
class AnalisadorContextual:
|
| 30 |
def __init__(self):
|
| 31 |
self.contexto = self.carregar_contexto()
|
|
|
|
| 49 |
json.dump(self.contexto, f, ensure_ascii=False, indent=2)
|
| 50 |
except: pass
|
| 51 |
|
| 52 |
+
def contexto_fallback(self, input_atual):
|
| 53 |
+
"""FIX: input_atual passado como parΓ’metro"""
|
| 54 |
+
return {
|
| 55 |
+
"classificacao": ["dΓΊvida"],
|
| 56 |
+
"fatos": [],
|
| 57 |
+
"objetivo_usuario": "AnΓ‘lise geral",
|
| 58 |
+
"duvida_central": input_atual[:200],
|
| 59 |
+
"timestamp": datetime.now().isoformat()
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
def analisar_input(self, input_atual, history):
|
| 63 |
+
"""TUDO do input + histΓ³rico - SEM outros textbox"""
|
| 64 |
if not model_pro:
|
| 65 |
+
return self.contexto_fallback(input_atual)
|
| 66 |
|
| 67 |
history_resumo = "\n".join([f"π€: {h[0][:80]}..." for h in history[-3:]])[:300]
|
| 68 |
|
| 69 |
prompt = f"""CATALOGUE SEM RESPONDER:
|
| 70 |
|
| 71 |
+
INPUT ATUAL: {input_atual[:400]}
|
| 72 |
HISTΓRICO: {history_resumo}
|
| 73 |
|
| 74 |
JSON:
|
|
|
|
| 83 |
resp = model_pro.generate_content(prompt, temperature=0.1)
|
| 84 |
raw = re.sub(r'``````|\n\s*\n', '', resp.text.strip())
|
| 85 |
analise = json.loads(raw)
|
| 86 |
+
|
| 87 |
+
# MERGE + UPDATE
|
| 88 |
self.contexto.update(analise)
|
| 89 |
self.aplicar_decainento()
|
| 90 |
self.contexto["timestamp"] = datetime.now().isoformat()
|
| 91 |
self.salvar_contexto()
|
| 92 |
return self.contexto
|
| 93 |
except:
|
| 94 |
+
return self.contexto_fallback(input_atual)
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
def aplicar_decainento(self):
|
| 97 |
agora = time.time()
|
|
|
|
| 99 |
for fato in self.contexto.get("fatos", []):
|
| 100 |
peso = fato[1] * 0.95
|
| 101 |
if peso > 0.1:
|
| 102 |
+
novos_fatos.append([fato[0], peso, fato[2], datetime.now().isoformat()])
|
| 103 |
self.contexto["fatos"] = novos_fatos[:15]
|
| 104 |
|
| 105 |
+
# ==================== 3. SINGLETON GLOBAL ====================
|
| 106 |
analisador = AnalisadorContextual()
|
| 107 |
|
| 108 |
+
# ==================== 4. PLANEJADOR + EXECUTOR ====================
|
| 109 |
def fallback_plano():
|
| 110 |
return [
|
| 111 |
+
{"nome": "Analisador", "missao": "Analise input+contexto", "modelo": "flash", "tipo_saida": "json"},
|
| 112 |
{"nome": "RespostaFinal", "missao": "Resposta clara completa", "modelo": "pro", "tipo_saida": "texto"}
|
| 113 |
]
|
| 114 |
|
|
|
|
| 116 |
if not model_pro: return fallback_plano()
|
| 117 |
|
| 118 |
fatos = "\n".join([f"- {f[0]}({f[1]:.1f})" for f in contexto.get("fatos", [])[:4]])
|
| 119 |
+
prompt = f"""CONTEXTO CATALOGADO: {contexto}
|
| 120 |
INPUT: {input_atual[:200]}
|
| 121 |
|
| 122 |
+
PLANO 3 agentes JSON:
|
| 123 |
[{{"nome":"Explorador","missao":"Levante possibilidades","modelo":"flash","tipo_saida":"json"}},
|
| 124 |
{{"nome":"Validador","missao":"Teste cenΓ‘rios","modelo":"pro","tipo_saida":"json"}},
|
| 125 |
{{"nome":"Final","missao":"Resposta final","modelo":"pro","tipo_saida":"texto"}}]"""
|
|
|
|
| 147 |
except:
|
| 148 |
return {"role": "system", "error": "Erro"}, "ERRO", "Falha"
|
| 149 |
|
| 150 |
+
# ==================== 5. ORQUESTRADOR v35 (SIMPLIFICADO) ====================
|
| 151 |
def ler_anexo(arquivo):
|
| 152 |
if not arquivo: return ""
|
| 153 |
try:
|
|
|
|
| 155 |
return f"\nπ {os.path.basename(arquivo.name)}:\n{f.read()}\n"
|
| 156 |
except: return ""
|
| 157 |
|
| 158 |
+
def orquestrador_v35(texto, arquivo, history, json_config=None):
|
| 159 |
+
"""SEM textbox extra - sΓ³ input+history"""
|
| 160 |
anexo = ler_anexo(arquivo)
|
| 161 |
full_input = f"{texto}{anexo}".strip()
|
| 162 |
|
|
|
|
| 164 |
yield history, {}, "Sem input"
|
| 165 |
return
|
| 166 |
|
| 167 |
+
# Adiciona input ao histΓ³rico
|
| 168 |
+
history.append([full_input, "π§ Catalogando contexto..."])
|
| 169 |
timeline = [{"role": "user", "content": full_input}]
|
| 170 |
+
logs = f"π v35: {datetime.now().strftime('%H:%M:%S')}\n"
|
| 171 |
|
| 172 |
yield history, timeline, logs
|
| 173 |
|
| 174 |
+
# 1. ANALISADOR CONTEXTUAL (CORRIGIDO)
|
| 175 |
contexto = analisador.analisar_input(full_input, history)
|
| 176 |
+
logs += f"π {len(contexto.get('fatos',[]))} fatos | {contexto.get('classificacao',[])}\n"
|
| 177 |
timeline.append({"role": "system", "contexto": contexto})
|
| 178 |
|
| 179 |
+
history[-1][1] = f"β
{len(contexto.get('fatos',[]))} fatos | {contexto.get('classificacao', ['dΓΊvida'])[0]}"
|
| 180 |
yield history, timeline, logs
|
| 181 |
|
| 182 |
# 2. PLANEJADOR SΓCRATES
|
|
|
|
| 187 |
history[-1][1] = f"π― {len(plano)} etapas planejadas"
|
| 188 |
yield history, timeline, logs
|
| 189 |
|
| 190 |
+
# 3. EXECUTA PLANO
|
| 191 |
for i, agente in enumerate(plano):
|
| 192 |
history[-1][1] = f"[{i+1}/{len(plano)}] {agente['nome']}..."
|
| 193 |
yield history, timeline, logs
|
|
|
|
| 200 |
history[-1][1] = str(res['content'])[:900]
|
| 201 |
yield history, timeline, logs
|
| 202 |
|
| 203 |
+
logs += "β
SΓ³crates v35 concluΓdo"
|
| 204 |
yield history, timeline, logs
|
| 205 |
|
| 206 |
+
# ==================== 6. UI SIMPLIFICADA v35 ====================
|
| 207 |
+
def ui_v35():
|
| 208 |
css = "footer {display: none !important;} .contain {border: none !important;}"
|
| 209 |
|
| 210 |
+
with gr.Blocks(title="π PIPELINE v35 - SΓCRATES", css=css, theme=gr.themes.Soft()) as app:
|
| 211 |
+
gr.Markdown("# π§ PIPELINE v35 - Input + HistΓ³rico = Tudo")
|
|
|
|
|
|
|
| 212 |
|
| 213 |
with gr.Tabs():
|
| 214 |
+
# ABA PRINCIPAL - SEM textbox extra
|
| 215 |
with gr.Tab("π¬ Pipeline"):
|
| 216 |
chatbot = gr.Chatbot(height=600, show_copy_button=True, type="tuples")
|
| 217 |
|
| 218 |
with gr.Row():
|
| 219 |
+
txt_in = gr.Textbox(placeholder="Digite input... (contexto automΓ‘tico)",
|
| 220 |
+
lines=3, container=False)
|
| 221 |
file_in = gr.UploadButton("π", file_types=[".txt", ".py", ".json"])
|
| 222 |
btn_send = gr.Button("βΆοΈ Executar", variant="primary")
|
| 223 |
|
| 224 |
file_status = gr.Markdown("")
|
| 225 |
+
file_in.upload(lambda x: f"π {os.path.basename(x.name) if x else ''}",
|
| 226 |
+
file_in, file_status)
|
| 227 |
|
| 228 |
+
# DEBUG
|
| 229 |
with gr.Tab("π Debug"):
|
| 230 |
out_dna = gr.JSON(label="Timeline")
|
| 231 |
out_logs = gr.Textbox(label="Logs", lines=15)
|
| 232 |
|
| 233 |
+
# CONTEXTO PERSISTENTE
|
| 234 |
+
with gr.Tab("π§ Contexto"):
|
| 235 |
+
contexto_display = gr.JSON(label="contexto_v35.json", value={})
|
| 236 |
+
gr.Button("π Refresh").click(lambda: analisador.contexto, outputs=contexto_display)
|
|
|
|
| 237 |
|
| 238 |
+
# TRIGGERS SIMPLIFICADOS (sem 4ΒΊ input)
|
| 239 |
btn_send.click(
|
| 240 |
+
orquestrador_v35,
|
| 241 |
+
inputs=[txt_in, file_in, chatbot],
|
| 242 |
outputs=[chatbot, out_dna, out_logs]
|
| 243 |
).then(lambda: "", outputs=txt_in)
|
| 244 |
|
| 245 |
txt_in.submit(
|
| 246 |
+
orquestrador_v35,
|
| 247 |
+
inputs=[txt_in, file_in, chatbot],
|
| 248 |
outputs=[chatbot, out_dna, out_logs]
|
| 249 |
).then(lambda: "", outputs=txt_in)
|
| 250 |
|
| 251 |
return app
|
| 252 |
|
| 253 |
if __name__ == "__main__":
|
| 254 |
+
print("π v35 SΓCRATES - SEM ERROS")
|
| 255 |
+
print("β
contexto_fallback fixado")
|
| 256 |
+
print("β
Sem textbox extra - sΓ³ input+history")
|
| 257 |
+
print("β
HF Spaces 100% OK")
|
| 258 |
|
| 259 |
+
app = ui_v35()
|
| 260 |
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
|