Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,54 +1,70 @@
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import requests
|
|
|
|
| 4 |
from config import DOCS, MODEL_PRIORITY_A, MODEL_PRIORITY_B
|
| 5 |
|
| 6 |
def detect_language(passage):
|
| 7 |
greek_chars = re.findall(r'[\u0370-\u03FF\u1F00-\u1FFF]', passage)
|
| 8 |
return 'greek' if len(greek_chars) > len(passage) * 0.1 else 'latin'
|
| 9 |
|
|
|
|
| 10 |
def call_openrouter(passage, mode, category):
|
| 11 |
api_key = os.getenv("OPENROUTER_API_KEY")
|
| 12 |
lang = detect_language(passage)
|
| 13 |
|
|
|
|
| 14 |
url_doc = DOCS.get(category)
|
|
|
|
| 15 |
try:
|
| 16 |
resp = requests.get(url_doc, timeout=15)
|
| 17 |
resp.raise_for_status()
|
|
|
|
| 18 |
questions = [l.strip() for l in resp.text.splitlines() if l.strip().endswith('?')]
|
| 19 |
except Exception as e:
|
| 20 |
return f"Erro ao acessar Google Docs: {str(e)}", "Nenhum"
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
model_chain = MODEL_PRIORITY_A if "Alta" in mode else MODEL_PRIORITY_B
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
{chr(10).join(
|
| 33 |
|
| 34 |
-
# Tenta os modelos da lista até um funcionar
|
| 35 |
-
for model in model_chain:
|
| 36 |
try:
|
| 37 |
response = requests.post(
|
| 38 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 39 |
headers={"Authorization": f"Bearer {api_key}"},
|
| 40 |
json={
|
| 41 |
"model": model,
|
| 42 |
-
"messages": [{"role": "user", "content":
|
| 43 |
"temperature": 0.1,
|
| 44 |
-
"max_tokens":
|
| 45 |
},
|
| 46 |
-
timeout=
|
| 47 |
)
|
| 48 |
if response.status_code == 200:
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import requests
|
| 4 |
+
# MANTENHA ESTES IMPORTS (essenciais para ler o config.py)
|
| 5 |
from config import DOCS, MODEL_PRIORITY_A, MODEL_PRIORITY_B
|
| 6 |
|
| 7 |
def detect_language(passage):
|
| 8 |
greek_chars = re.findall(r'[\u0370-\u03FF\u1F00-\u1FFF]', passage)
|
| 9 |
return 'greek' if len(greek_chars) > len(passage) * 0.1 else 'latin'
|
| 10 |
|
| 11 |
+
# SUBSTITUA DAQUI PARA BAIXO PELA VERSÃO DE "LOTES" (BATCHES)
|
| 12 |
def call_openrouter(passage, mode, category):
|
| 13 |
api_key = os.getenv("OPENROUTER_API_KEY")
|
| 14 |
lang = detect_language(passage)
|
| 15 |
|
| 16 |
+
# 1. Busca a URL no dicionário que está no seu config.py
|
| 17 |
url_doc = DOCS.get(category)
|
| 18 |
+
|
| 19 |
try:
|
| 20 |
resp = requests.get(url_doc, timeout=15)
|
| 21 |
resp.raise_for_status()
|
| 22 |
+
# Filtra as perguntas (linhas terminadas em ?)
|
| 23 |
questions = [l.strip() for l in resp.text.splitlines() if l.strip().endswith('?')]
|
| 24 |
except Exception as e:
|
| 25 |
return f"Erro ao acessar Google Docs: {str(e)}", "Nenhum"
|
| 26 |
|
| 27 |
+
if not questions:
|
| 28 |
+
return "Nenhuma pergunta encontrada no documento.", "Nenhum"
|
| 29 |
+
|
| 30 |
model_chain = MODEL_PRIORITY_A if "Alta" in mode else MODEL_PRIORITY_B
|
| 31 |
+
model = model_chain[0]
|
| 32 |
|
| 33 |
+
full_report = [f"--- ANÁLISE FILOLÓGICA: {category.upper()} ---", f"Texto: {passage}\n"]
|
| 34 |
+
|
| 35 |
+
# 2. PROCESSAMENTO POR LOTES (O segredo para o Claude não ter 'preguiça')
|
| 36 |
+
batch_size = 5
|
| 37 |
+
for i in range(0, len(questions), batch_size):
|
| 38 |
+
batch = questions[i:i + batch_size]
|
| 39 |
+
|
| 40 |
+
prompt = f"""Atue como um Filólogo especialista em {lang}.
|
| 41 |
+
Passagem: "{passage}"
|
| 42 |
|
| 43 |
+
Responda detalhadamente em PORTUGUÊS.
|
| 44 |
+
OBRIGATÓRIO: Escreva a PERGUNTA completa antes de cada resposta.
|
| 45 |
|
| 46 |
+
QUESTÕES DESTE LOTE:
|
| 47 |
+
{chr(10).join(batch)}"""
|
| 48 |
|
|
|
|
|
|
|
| 49 |
try:
|
| 50 |
response = requests.post(
|
| 51 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 52 |
headers={"Authorization": f"Bearer {api_key}"},
|
| 53 |
json={
|
| 54 |
"model": model,
|
| 55 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 56 |
"temperature": 0.1,
|
| 57 |
+
"max_tokens": 4000
|
| 58 |
},
|
| 59 |
+
timeout=120
|
| 60 |
)
|
| 61 |
if response.status_code == 200:
|
| 62 |
+
batch_result = response.json()['choices'][0]['message']['content']
|
| 63 |
+
full_report.append(batch_result)
|
| 64 |
+
else:
|
| 65 |
+
full_report.append(f"\n[Erro no lote {i//batch_size + 1}: Status {response.status_code}]")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
full_report.append(f"\n[Falha de conexão no lote {i//batch_size + 1}: {str(e)}]")
|
| 68 |
+
|
| 69 |
+
# Junta todos os lotes em um único relatório final
|
| 70 |
+
return "\n\n".join(full_report), model
|