Spaces:
Sleeping
Sleeping
File size: 14,090 Bytes
18df1d9 283dd8f 18df1d9 9c538d9 2b7c617 283dd8f e2c15c5 18df1d9 9c538d9 18df1d9 0e0a17d 18df1d9 a81bbe2 283dd8f e2c15c5 c03c193 e2c15c5 b6672f0 e2c15c5 c03c193 e2c15c5 18df1d9 a81bbe2 18df1d9 a81bbe2 18df1d9 0e0a17d 18df1d9 a81bbe2 18df1d9 a81bbe2 0e0a17d 18df1d9 e2c15c5 0e0a17d 9301d0e 18df1d9 0e0a17d a81bbe2 0e0a17d c7397e8 4c8169f c7397e8 0e0a17d 283dd8f 0e0a17d 9301d0e 411fbac 0e0a17d c7397e8 0e0a17d 411fbac 9301d0e 411fbac dcc08e1 411fbac 4c8169f 411fbac 4c8169f 411fbac 4c8169f 28e2bf1 e2c15c5 4c8169f 28e2bf1 e2c15c5 4c8169f 28e2bf1 e2c15c5 411fbac 0e0a17d a81bbe2 0e0a17d 411fbac a81bbe2 0e0a17d a81bbe2 283dd8f a81bbe2 4c8169f 28e2bf1 e2c15c5 0e0a17d 9ccab25 0e0a17d a81bbe2 283dd8f a81bbe2 28e2bf1 e2c15c5 0e0a17d a81bbe2 283dd8f a81bbe2 28e2bf1 e2c15c5 dcc08e1 18df1d9 0e0a17d a81bbe2 0e0a17d 2b7c617 a81bbe2 2b7c617 968a78b 2b7c617 b6dfa57 2b7c617 a81bbe2 2b7c617 e2c15c5 411fbac e2c15c5 2b7c617 411fbac 2b7c617 0e0a17d 18df1d9 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 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
# app.py
from flask import Flask, render_template, request, Response
import json
import time
import os
import uuid
import threading
import concurrent.futures
from html import escape
import re
from markdown_it import MarkdownIt # ✅ NOVA IMPORTAÇÃO
# 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
# ✅ Instancia o novo conversor de Markdown
md = MarkdownIt()
def is_html_empty(html: str) -> bool:
"""
Verifica de forma robusta se uma string HTML não contém texto visível,
lidando com entidades HTML.
"""
if not html:
return True
# 1. Remove todas as tags do HTML
text_only = re.sub('<[^<]+?>', '', html)
# 2. Decodifica entidades HTML (ex: para ' ')
decoded_text = unescape(text_only)
# 3. Verifica se o texto restante está de fato vazio
return not decoded_text.strip()
@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:
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':
mock_text = form_data.get('mock_text', 'Este é um texto de simulação.')
mock_html = md.render(mock_text)
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:
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):
def task():
return chain.invoke(inputs)['text']
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(task)
try:
result = future.result(timeout=timeout)
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."
except Exception as e:
results[key] = f"Erro ao processar {key.upper()}: {e}"
claude_atomic_llm = claude_llm.bind(max_tokens=20000)
models = {'grok': grok_llm, 'sonnet': claude_atomic_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()
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
yield f"data: {json.dumps({'progress': 80, 'message': 'Todos os modelos responderam. Formatando saídas...'})}\n\n"
grok_text = results.get('grok', '')
print(f"--- Resposta Bruta do GROK (Atômico) ---\n{grok_text}\n--------------------------------------")
grok_html = md.render(grok_text)
if is_html_empty(grok_html):
grok_html = f"<pre>{escape(grok_text)}</pre>"
yield f"data: {json.dumps({'partial_result': {'id': 'grok-output', 'content': grok_html}})}\n\n"
sonnet_text = results.get('sonnet', '')
print(f"--- Resposta Bruta do Sonnet (Atômico) ---\n{sonnet_text}\n----------------------------------------")
sonnet_html = md.render(sonnet_text)
if is_html_empty(sonnet_html):
sonnet_html = f"<pre>{escape(sonnet_text)}</pre>"
yield f"data: {json.dumps({'partial_result': {'id': 'sonnet-output', 'content': sonnet_html}})}\n\n"
gemini_text = results.get('gemini', '')
print(f"--- Resposta Bruta do Gemini (Atômico) ---\n{gemini_text}\n----------------------------------------")
gemini_html = md.render(gemini_text)
if is_html_empty(gemini_html):
gemini_html = f"<pre>{escape(gemini_text)}</pre>"
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']
if not resposta_grok or not resposta_grok.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço GROK: Sem resposta.'})}\n\n"
return
print(f"--- Resposta Bruta do GROK (Hierárquico) ---\n{resposta_grok}\n------------------------------------------")
grok_html = md.render(resposta_grok)
if is_html_empty(grok_html):
grok_html = f"<pre>{escape(resposta_grok)}</pre>"
yield f"data: {json.dumps({'progress': 33, 'message': 'Claude Sonnet está processando...', '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']
if not resposta_sonnet or not resposta_sonnet.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço Claude Sonnet: Sem resposta.'})}\n\n"
return
print(f"--- Resposta Bruta do Sonnet (Hierárquico) ---\n{resposta_sonnet}\n--------------------------------------------")
sonnet_html = md.render(resposta_sonnet)
if is_html_empty(sonnet_html):
sonnet_html = f"<pre>{escape(resposta_sonnet)}</pre>"
yield f"data: {json.dumps({'progress': 66, 'message': 'Gemini está processando...', 'partial_result': {'id': 'sonnet-output', 'content': sonnet_html}})}\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']
if not resposta_gemini or not resposta_gemini.strip():
yield f"data: {json.dumps({'error': 'Falha no serviço Gemini: Sem resposta.'})}\n\n"
return
print(f"--- Resposta Bruta do Gemini (Hierárquico) ---\n{resposta_gemini}\n--------------------------------------------")
gemini_html = md.render(resposta_gemini)
if is_html_empty(gemini_html):
gemini_html = f"<pre>{escape(gemini_html)}</pre>"
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')
@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"])
grok_with_max_tokens = grok_llm.bind(max_tokens=100000)
chain_merge = LLMChain(llm=grok_with_max_tokens, 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']
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
print(f"--- Resposta Bruta do Merge (GROK) ---\n{resposta_merge}\n------------------------------------")
word_count = len(resposta_merge.split())
merge_html = md.render(resposta_merge)
if is_html_empty(merge_html):
merge_html = f"<pre>{escape(resposta_merge)}</pre>"
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__':
app.run(debug=True)
|