caarleexx commited on
Commit
4a44d63
·
verified ·
1 Parent(s): 76d14db

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -197
app.py DELETED
@@ -1,197 +0,0 @@
1
-
2
- import json
3
- import os
4
- import base64
5
- import re
6
- import warnings
7
- from typing import Dict, List, Tuple
8
-
9
- import gradio as gr
10
- import google.generativeai as genai
11
-
12
- # ============================================================================
13
- # CONFIGURAÇÃO GERAL
14
- # ============================================================================
15
- warnings.filterwarnings("ignore", category=FutureWarning, module="google.api_core")
16
-
17
- API_KEY = os.getenv("GOOGLE_API_KEY", "")
18
-
19
- if not API_KEY:
20
- print("⚠️ AVISO: GOOGLE_API_KEY não encontrada!")
21
-
22
- genai.configure(api_key=API_KEY)
23
- model = genai.GenerativeModel("gemini-1.5-flash")
24
-
25
- TITLE = "# 🔹 Anise v10.5\n**Interface Limpa | DNA no Rodapé**"
26
-
27
- # ============================================================================
28
- # UTILITÁRIOS (MANTIDOS DO v10.4)
29
- # ============================================================================
30
- def processar_anexo(arquivo) -> Tuple[str, str]:
31
- if arquivo is None: return "", "nenhum"
32
- caminho = str(arquivo)
33
-
34
- if caminho.lower().endswith('.pdf'):
35
- try:
36
- import PyPDF2
37
- with open(caminho, 'rb') as f:
38
- leitor = PyPDF2.PdfReader(f)
39
- texto = "".join(pagina.extract_text() + "\n" for pagina in leitor.pages[:5])
40
- return texto[:5000], "pdf"
41
- except: return "Erro leitura PDF", "erro"
42
-
43
- elif any(caminho.lower().endswith(ext) for ext in ['.png','.jpg','.jpeg','.gif','.webp']):
44
- try:
45
- with open(caminho, 'rb') as f:
46
- encoded = base64.b64encode(f.read()).decode()
47
- return encoded, "imagem"
48
- except: return "Erro leitura IMG", "erro"
49
- return "", "nao_suportado"
50
-
51
- def chamar_gemini_json(prompt: str, etapa: str, temperatura=0.2) -> Dict:
52
- full_prompt = f"{prompt}\n\n---\nRESPONDER APENAS JSON VÁLIDO."
53
- try:
54
- response = model.generate_content(
55
- full_prompt,
56
- generation_config=genai.types.GenerationConfig(
57
- temperature=temperatura,
58
- max_output_tokens=2000,
59
- response_mime_type="application/json"
60
- )
61
- )
62
- return json.loads(response.text)
63
- except:
64
- return {"erro": "Falha API ou JSON", "raw": "..."}
65
-
66
- def historico_compacto(historico: List) -> str:
67
- if not historico: return "Nenhum."
68
- return "\n".join([f"{m.get('role','?')}: {str(m.get('content',''))[:150]}..." for m in historico[-4:]])
69
-
70
- def criar_dna() -> Dict:
71
- return {"historico": [], "meta": {"turnos": 0}}
72
-
73
- # ============================================================================
74
- # PIPELINE (RESUMIDO PARA FOCO NA UI)
75
- # ============================================================================
76
- def passo_x1_planejar(pergunta, p1) -> Dict:
77
- # Lógica simplificada para o exemplo, mantendo a estrutura robusta
78
- return chamar_gemini_json(f"Liste 2 sub-perguntas cruciais para: {pergunta}", "X1")
79
-
80
- def passo_p7_resposta(pergunta, x1) -> Dict:
81
- return chamar_gemini_json(f"Responda {pergunta} considerando {json.dumps(x1)}. JSON: {{'resposta_final': 'texto'}}", "P7", 0.7)
82
-
83
- # O Orquestrador principal
84
- def processar_pipeline(pergunta: str, historico: List, arquivo_anexo=None, dna=None) -> Tuple[str, List, Dict]:
85
- # Inicializa DNA se necessário
86
- if dna is None or not isinstance(dna, dict) or "historico" not in dna:
87
- dna = criar_dna()
88
-
89
- # 1. Processar Input
90
- cont_anexo, tipo_anexo = processar_anexo(arquivo_anexo)
91
- prompt_final = pergunta
92
- if tipo_anexo == "pdf": prompt_final = f"PDF INFO: {cont_anexo}\n{pergunta}"
93
-
94
- # 2. Execução (Simplificada aqui para funcionar rápido na UI nova)
95
- # No código real, mantenha seus passos P0-P8 aqui
96
- x1 = passo_x1_planejar(prompt_final, {"tipo": "geral"})
97
- p7 = passo_p7_resposta(prompt_final, x1)
98
-
99
- resp_texto = p7.get("resposta_final", "Erro na geração.")
100
-
101
- # 3. Atualizar Estado
102
- novo_hist = historico + [
103
- {"role": "user", "content": pergunta},
104
- {"role": "assistant", "content": resp_texto}
105
- ]
106
-
107
- # Log no DNA
108
- dna["historico"].append({
109
- "turno": dna["meta"]["turnos"] + 1,
110
- "usuario": pergunta,
111
- "analise_x1": x1,
112
- "resposta": resp_texto
113
- })
114
- dna["meta"]["turnos"] += 1
115
-
116
- return resp_texto, novo_hist, dna
117
-
118
- # ============================================================================
119
- # INTERFACE LIMPA V10.5
120
- # ============================================================================
121
- def chat_interface(msg, hist_state, anexo, dna_json):
122
- """
123
- Inputs: Mensagem, Estado(Invisível), Arquivo, DNA(String)
124
- Outputs: Estado(Atualizado), Resposta(Markdown), DNA(String), LimparMsg, LimparArq
125
- """
126
- dna = json.loads(dna_json) if dna_json else {}
127
- if hist_state is None: hist_state = []
128
-
129
- try:
130
- resp_texto, novo_hist_state, dna_new = processar_pipeline(msg, hist_state, anexo, dna)
131
-
132
- # Retorna:
133
- # 1. State do Histórico (invisível)
134
- # 2. Resposta para o Markdown
135
- # 3. DNA para o Code Block
136
- # 4. None para limpar Input Msg
137
- # 5. None para limpar Input Arquivo
138
- return novo_hist_state, f"### 🤖 Resposta:\n\n{resp_texto}", json.dumps(dna_new, indent=2), "", None
139
-
140
- except Exception as e:
141
- import traceback
142
- trace = traceback.format_exc()
143
- return hist_state, f"### ❌ Erro:\n\n```\n{trace}\n```", dna_json, msg, None
144
-
145
- if __name__ == "__main__":
146
- with gr.Blocks(title="Anise UI Clean", theme=gr.themes.Soft()) as demo:
147
-
148
- # ESTADO (Memória invisível da conversa)
149
- chat_state = gr.State([])
150
-
151
- gr.Markdown(TITLE)
152
-
153
- # --- ÁREA DE ENTRADA ---
154
- with gr.Group():
155
- with gr.Row():
156
- txt_input = gr.Textbox(
157
- show_label=False,
158
- placeholder="Digite sua pergunta aqui e pressione Enter...",
159
- scale=5,
160
- lines=2
161
- )
162
- file_input = gr.File(label="Anexar", scale=1, file_count="single", type="filepath")
163
-
164
- btn_submit = gr.Button("Enviar 🚀", variant="primary")
165
-
166
- # --- ÁREA DE RESPOSTA ---
167
- # Não usamos gr.Chatbot aqui, apenas um Markdown ou Textbox para a resposta atual
168
- with gr.Container(variant="panel"):
169
- out_resposta = gr.Markdown(
170
- value="### 👋 Olá! Faça uma pergunta para iniciar.",
171
- label="Resposta"
172
- )
173
-
174
- # --- RODAPÉ: DNA E HISTÓRICO TÉCNICO ---
175
- gr.Markdown("---") # Separador
176
- with gr.Accordion("🧬 Histórico DNA (Logs do Raciocínio)", open=True):
177
- # O componente Code tem botão de copiar nativo no canto superior direito
178
- out_dna = gr.Code(
179
- label="Estado Interno (JSON)",
180
- language="json",
181
- lines=10,
182
- interactive=False # Apenas leitura, facilita cópia
183
- )
184
-
185
- # Opção alternativa se preferir Textbox com botão explícito
186
- # out_dna_txt = gr.Textbox(label="DNA Texto", show_copy_button=True, max_lines=10)
187
-
188
- # --- EVENTOS ---
189
- entradas = [txt_input, chat_state, file_input, out_dna]
190
- saidas = [chat_state, out_resposta, out_dna, txt_input, file_input]
191
-
192
- txt_input.submit(chat_interface, inputs=entradas, outputs=saidas)
193
- btn_submit.click(chat_interface, inputs=entradas, outputs=saidas)
194
-
195
- print("🚀 Anise Interface Limpa iniciada em http://0.0.0.0:7860")
196
- demo.launch(server_name="0.0.0.0", server_port=7860)
197
- O