Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -8,42 +8,51 @@ 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:
|
|
@@ -51,7 +60,7 @@ QUESTÕES DESTE LOTE:
|
|
| 51 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 52 |
headers={"Authorization": f"Bearer {api_key}"},
|
| 53 |
json={
|
| 54 |
-
"model":
|
| 55 |
"messages": [{"role": "user", "content": prompt}],
|
| 56 |
"temperature": 0.1,
|
| 57 |
"max_tokens": 4000
|
|
@@ -59,12 +68,10 @@ QUESTÕES DESTE LOTE:
|
|
| 59 |
timeout=120
|
| 60 |
)
|
| 61 |
if response.status_code == 200:
|
| 62 |
-
|
| 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
|
| 68 |
|
| 69 |
-
|
| 70 |
-
return "\n\n".join(full_report), model
|
|
|
|
| 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 |
def call_openrouter(passage, mode, category):
|
| 12 |
api_key = os.getenv("OPENROUTER_API_KEY")
|
| 13 |
lang = detect_language(passage)
|
| 14 |
|
|
|
|
| 15 |
url_doc = DOCS.get(category)
|
|
|
|
| 16 |
try:
|
| 17 |
resp = requests.get(url_doc, timeout=15)
|
| 18 |
resp.raise_for_status()
|
|
|
|
| 19 |
questions = [l.strip() for l in resp.text.splitlines() if l.strip().endswith('?')]
|
| 20 |
except Exception as e:
|
| 21 |
return f"Erro ao acessar Google Docs: {str(e)}", "Nenhum"
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
model_chain = MODEL_PRIORITY_A if "Alta" in mode else MODEL_PRIORITY_B
|
|
|
|
| 24 |
|
| 25 |
full_report = [f"--- ANÁLISE FILOLÓGICA: {category.upper()} ---", f"Texto: {passage}\n"]
|
|
|
|
|
|
|
| 26 |
batch_size = 5
|
| 27 |
+
|
| 28 |
+
# --- Lógica de Seleção de Modelo com Fallback ---
|
| 29 |
+
working_model = None
|
| 30 |
+
for model_candidate in model_chain:
|
| 31 |
+
try:
|
| 32 |
+
# Teste rápido para ver se o modelo responde
|
| 33 |
+
test_resp = requests.post(
|
| 34 |
+
url="https://openrouter.ai/api/v1/chat/completions",
|
| 35 |
+
headers={"Authorization": f"Bearer {api_key}"},
|
| 36 |
+
json={"model": model_candidate, "messages": [{"role": "user", "content": "test"}], "max_tokens": 1},
|
| 37 |
+
timeout=10
|
| 38 |
+
)
|
| 39 |
+
if test_resp.status_code == 200:
|
| 40 |
+
working_model = model_candidate
|
| 41 |
+
break
|
| 42 |
+
except:
|
| 43 |
+
continue
|
| 44 |
+
|
| 45 |
+
if not working_model:
|
| 46 |
+
return "Erro: Nenhum modelo da lista está disponível no momento (OpenRouter Offline?).", "Falha"
|
| 47 |
+
|
| 48 |
+
# --- Execução dos Lotes com o Modelo que Funcionou ---
|
| 49 |
for i in range(0, len(questions), batch_size):
|
| 50 |
batch = questions[i:i + batch_size]
|
|
|
|
| 51 |
prompt = f"""Atue como um Filólogo especialista em {lang}.
|
| 52 |
Passagem: "{passage}"
|
|
|
|
| 53 |
Responda detalhadamente em PORTUGUÊS.
|
| 54 |
OBRIGATÓRIO: Escreva a PERGUNTA completa antes de cada resposta.
|
| 55 |
+
QUESTÕES:
|
|
|
|
| 56 |
{chr(10).join(batch)}"""
|
| 57 |
|
| 58 |
try:
|
|
|
|
| 60 |
url="https://openrouter.ai/api/v1/chat/completions",
|
| 61 |
headers={"Authorization": f"Bearer {api_key}"},
|
| 62 |
json={
|
| 63 |
+
"model": working_model,
|
| 64 |
"messages": [{"role": "user", "content": prompt}],
|
| 65 |
"temperature": 0.1,
|
| 66 |
"max_tokens": 4000
|
|
|
|
| 68 |
timeout=120
|
| 69 |
)
|
| 70 |
if response.status_code == 200:
|
| 71 |
+
full_report.append(response.json()['choices'][0]['message']['content'])
|
|
|
|
| 72 |
else:
|
| 73 |
full_report.append(f"\n[Erro no lote {i//batch_size + 1}: Status {response.status_code}]")
|
| 74 |
except Exception as e:
|
| 75 |
+
full_report.append(f"\n[Falha de conexão: {str(e)}]")
|
| 76 |
|
| 77 |
+
return "\n\n".join(full_report), working_model
|
|
|