Spaces:
Sleeping
Sleeping
File size: 12,548 Bytes
18df1d9 0e0a17d 18df1d9 9c538d9 2b7c617 dcc08e1 18df1d9 9c538d9 18df1d9 0e0a17d 18df1d9 a81bbe2 18df1d9 a81bbe2 18df1d9 a81bbe2 18df1d9 0e0a17d 18df1d9 a81bbe2 18df1d9 a81bbe2 0e0a17d 18df1d9 a81bbe2 18df1d9 0e0a17d 9301d0e 18df1d9 a81bbe2 18df1d9 0e0a17d a81bbe2 0e0a17d c7397e8 a81bbe2 c7397e8 a81bbe2 c7397e8 0e0a17d 9301d0e 411fbac 0e0a17d c7397e8 0e0a17d 411fbac 9301d0e 411fbac a81bbe2 411fbac dcc08e1 411fbac a81bbe2 411fbac 9301d0e 411fbac 9301d0e 411fbac 9301d0e 411fbac 9301d0e 411fbac 0e0a17d a81bbe2 0e0a17d 411fbac a81bbe2 0e0a17d a81bbe2 0e0a17d 9ccab25 0e0a17d a81bbe2 0e0a17d a81bbe2 0e0a17d a81bbe2 0e0a17d dcc08e1 18df1d9 dcc08e1 0e0a17d a81bbe2 0e0a17d 2b7c617 a81bbe2 2b7c617 b6dfa57 2b7c617 b6dfa57 2b7c617 a81bbe2 2b7c617 a81bbe2 2b7c617 411fbac 2b7c617 411fbac 2b7c617 0e0a17d 18df1d9 a81bbe2 9c538d9 |
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# app.py
from flask import Flask, render_template, request, Response, jsonify
import markdown2
import json
import time
import os
import uuid
import threading
import concurrent.futures # Nova importação para timeout
# Importações do LangChain
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
# Importa os LLMs
from llms import claude_llm, grok_llm, gemini_llm
# Importa os prompts
from config import *
# Importa nosso processador RAG
from rag_processor import get_relevant_context
app = Flask(__name__)
# Garante que o diretório de uploads exista
if not os.path.exists('uploads'):
os.makedirs('uploads')
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
@app.route('/')
def index():
"""Renderiza a página inicial da aplicação."""
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
"""Processa a solicitação do usuário nos modos Hierárquico ou Atômico."""
form_data = request.form
files = request.files.getlist('files')
mode = form_data.get('mode', 'real')
processing_mode = form_data.get('processing_mode', 'hierarchical')
temp_file_paths = []
if mode == 'real':
for file in files:
if file and file.filename:
# Cria um nome de arquivo único para evitar conflitos
unique_filename = str(uuid.uuid4()) + "_" + os.path.basename(file.filename)
file_path = os.path.join('uploads', unique_filename)
file.save(file_path)
temp_file_paths.append(file_path)
def generate_stream(current_mode, form_data, file_paths):
"""Gera a resposta em streaming para o front-end."""
solicitacao_usuario = form_data.get('solicitacao', '')
if current_mode == 'test':
# Lógica para o modo de teste/simulação
mock_text = form_data.get('mock_text', 'Este é um texto de simulação.')
mock_html = markdown2.markdown(mock_text, extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'progress': 100, 'message': 'Simulação concluída!', 'partial_result': {'id': 'grok-output', 'content': mock_html}, 'done': True, 'mode': 'atomic' if processing_mode == 'atomic' else 'hierarchical'})}\n\n"
if processing_mode == 'atomic':
yield f"data: {json.dumps({'partial_result': {'id': 'sonnet-output', 'content': mock_html}})}\n\n"
yield f"data: {json.dumps({'partial_result': {'id': 'gemini-output', 'content': mock_html}})}\n\n"
else:
# Lógica para o modo real
if not solicitacao_usuario:
yield f"data: {json.dumps({'error': 'Solicitação não fornecida.'})}\n\n"
return
try:
yield f"data: {json.dumps({'progress': 0, 'message': 'Processando arquivos e extraindo contexto...'})}\n\n"
rag_context = get_relevant_context(file_paths, solicitacao_usuario)
if processing_mode == 'atomic':
# --- LÓGICA ATÔMICA (PARALELA) ---
results = {}
threads = []
def run_chain_with_timeout(chain, inputs, key, timeout=300):
"""Executa uma chain com timeout e trata respostas vazias."""
def task():
return chain.invoke(inputs)['text']
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(task)
try:
result = future.result(timeout=timeout)
# Validação de resposta vazia
if not result or not result.strip():
results[key] = "Error:EmptyResponse"
else:
results[key] = result
except concurrent.futures.TimeoutError:
results[key] = f"Erro ao processar {key.upper()}: Tempo limite excedido (Timeout)."
except Exception as e:
results[key] = f"Erro ao processar {key.upper()}: {e}"
models = {'grok': grok_llm, 'sonnet': claude_llm, 'gemini': gemini_llm}
prompt = PromptTemplate(template=PROMPT_ATOMICO_INICIAL, input_variables=["solicitacao_usuario", "rag_context"])
yield f"data: {json.dumps({'progress': 15, 'message': 'Iniciando processamento paralelo...'})}\n\n"
for name, llm in models.items():
chain = LLMChain(llm=llm, prompt=prompt)
thread = threading.Thread(target=run_chain_with_timeout, args=(chain, {"solicitacao_usuario": solicitacao_usuario, "rag_context": rag_context}, name))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
# Verifica se alguma thread falhou ou retornou vazio
for key, result in results.items():
if result == "Error:EmptyResponse" or "Erro ao processar" in result:
error_msg = result if "Erro ao processar" in result else f"Falha no serviço {key.upper()}: Sem resposta."
yield f"data: {json.dumps({'error': error_msg})}\n\n"
return # Interrompe todo o processo
yield f"data: {json.dumps({'progress': 80, 'message': 'Todos os modelos responderam. Formatando saída...'})}\n\n"
grok_html = markdown2.markdown(results.get('grok', ''), extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'partial_result': {'id': 'grok-output', 'content': grok_html}})}\n\n"
sonnet_html = markdown2.markdown(results.get('sonnet', ''), extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'partial_result': {'id': 'sonnet-output', 'content': sonnet_html}})}\n\n"
gemini_html = markdown2.markdown(results.get('gemini', ''), extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'partial_result': {'id': 'gemini-output', 'content': gemini_html}})}\n\n"
yield f"data: {json.dumps({'progress': 100, 'message': 'Processamento Atômico concluído!', 'done': True, 'mode': 'atomic'})}\n\n"
else:
# --- LÓGICA HIERÁRQUICA (SEQUENCIAL) ---
yield f"data: {json.dumps({'progress': 15, 'message': 'O GROK está processando sua solicitação...'})}\n\n"
prompt_grok = PromptTemplate(template=PROMPT_HIERARQUICO_GROK, input_variables=["solicitacao_usuario", "rag_context"])
chain_grok = LLMChain(llm=grok_llm, prompt=prompt_grok)
resposta_grok = chain_grok.invoke({"solicitacao_usuario": solicitacao_usuario, "rag_context": rag_context})['text']
# ✅ VALIDAÇÃO APRIMORADA
if not resposta_grok or not resposta_grok.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço GROK: Sem resposta. O processo foi interrompido.'})}\n\n"
return
grok_html = markdown2.markdown(resposta_grok, extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'progress': 33, 'message': 'Agora, o Claude Sonnet está aprofundando o texto...', 'partial_result': {'id': 'grok-output', 'content': grok_html}})}\n\n"
prompt_sonnet = PromptTemplate(template=PROMPT_HIERARQUICO_SONNET, input_variables=["solicitacao_usuario", "texto_para_analise"])
claude_with_max_tokens = claude_llm.bind(max_tokens=20000)
chain_sonnet = LLMChain(llm=claude_with_max_tokens, prompt=prompt_sonnet)
resposta_sonnet = chain_sonnet.invoke({"solicitacao_usuario": solicitacao_usuario, "texto_para_analise": resposta_grok})['text']
# ✅ VALIDAÇÃO APRIMORADA
if not resposta_sonnet or not resposta_sonnet.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço Claude Sonnet: Sem resposta. O processo foi interrompido.'})}\n\n"
return
sonnet_html = markdown2.markdown(resposta_sonnet, extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'progress': 66, 'message': 'Revisão final com o Gemini...'})}\n\n"
prompt_gemini = PromptTemplate(template=PROMPT_HIERARQUICO_GEMINI, input_variables=["solicitacao_usuario", "texto_para_analise"])
chain_gemini = LLMChain(llm=gemini_llm, prompt=prompt_gemini)
resposta_gemini = chain_gemini.invoke({"solicitacao_usuario": solicitacao_usuario, "texto_para_analise": resposta_sonnet})['text']
# ✅ VALIDAÇÃO APRIMORADA
if not resposta_gemini or not resposta_gemini.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço Gemini: Sem resposta. O processo foi interrompido.'})}\n\n"
return
gemini_html = markdown2.markdown(resposta_gemini, extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'progress': 100, 'message': 'Processamento concluído!', 'partial_result': {'id': 'gemini-output', 'content': gemini_html}, 'done': True, 'mode': 'hierarchical'})}\n\n"
except Exception as e:
print(f"Ocorreu um erro durante o processamento: {e}")
yield f"data: {json.dumps({'error': f'Ocorreu um erro inesperado na aplicação: {e}'})}\n\n"
return Response(generate_stream(mode, form_data, temp_file_paths), mimetype='text/event-stream')
# --- ROTA PARA O MERGE ---
@app.route('/merge', methods=['POST'])
def merge():
"""Recebe os textos do modo Atômico e os consolida usando um LLM."""
data = request.get_json()
def generate_merge_stream():
"""Gera a resposta do merge em streaming."""
try:
yield f"data: {json.dumps({'progress': 0, 'message': 'Iniciando o processo de merge...'})}\n\n"
prompt_merge = PromptTemplate(template=PROMPT_ATOMICO_MERGE, input_variables=["solicitacao_usuario", "texto_para_analise_grok", "texto_para_analise_sonnet", "texto_para_analise_gemini"])
chain_merge = LLMChain(llm=grok_llm, prompt=prompt_merge)
yield f"data: {json.dumps({'progress': 50, 'message': 'Enviando textos para o GROK para consolidação...'})}\n\n"
resposta_merge = chain_merge.invoke({
"solicitacao_usuario": data.get('solicitacao_usuario'),
"texto_para_analise_grok": data.get('grok_text'),
"texto_para_analise_sonnet": data.get('sonnet_text'),
"texto_para_analise_gemini": data.get('gemini_text')
})['text']
# ✅ VALIDAÇÃO APRIMORADA
if not resposta_merge or not resposta_merge.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço de Merge (GROK): Sem resposta.'})}\n\n"
return
word_count = len(resposta_merge.split())
merge_html = markdown2.markdown(resposta_merge, extras=["fenced-code-blocks", "tables"])
yield f"data: {json.dumps({'progress': 100, 'message': 'Merge concluído!', 'final_result': {'content': merge_html, 'word_count': word_count}, 'done': True})}\n\n"
except Exception as e:
print(f"Erro no processo de merge: {e}")
yield f"data: {json.dumps({'error': str(e)})}\n\n"
return Response(generate_merge_stream(), mimetype='text/event-stream')
if __name__ == '__main__':
# Executa a aplicação Flask em modo de depuração
app.run(debug=True)
|