Lei075fr commited on
Commit
f8ccb73
·
verified ·
1 Parent(s): 20e3a21

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -46
app.py CHANGED
@@ -4,78 +4,72 @@ from fastapi.responses import HTMLResponse
4
 
5
  app = FastAPI()
6
 
7
- # Pool de 15 Chaves - O Arsenal Soberano da Aria
8
  KEYS = [os.getenv(f"OR_KEY_{i}") for i in range(1, 16)]
9
  KEYS = [k for k in KEYS if k and k.strip()]
10
 
11
- # MAPEAMENTO UNIFICADO - ECOSSISTEMA ARIA (2026)
12
- # Usamos sufixos para que o Python aceite as chaves únicas
13
  MODEL_MAP = {
14
- "aria_med": "google/gemini-2.5-pro:free", # Medicina/Protocolos (Vitalis)
15
- "aria_logic": "qwen/qwen3-coder-480b:free", # Gestão/ERP/Lógica (Nexos)
16
- "aria_vision": "nvidia/nemotron-nano-12b-2-vl:free", # Visão/Saúde (Nutrilens)
17
- "aria_brain": "meta-llama/llama-3.3-70b-instruct:free", # Cérebro padrão da Aria
18
- "aria_default": "qwen/qwen3-coder:free" # Coding e automação
19
  }
20
 
21
  @app.get("/", response_class=HTMLResponse)
22
  async def root():
23
- status = "🟢 ATIVO" if KEYS else "🔴 SEM CHAVES"
24
  return f"""
25
- <body style='background:#0f0f0f; color:#00ff99; font-family:monospace; text-align:center; padding-top:50px;'>
26
- <h1 style='border-bottom: 2px solid #00ff99; display:inline-block; padding-bottom:10px;'>🛡️ Escudo Fortune MAX: ARIA EDITION</h1>
27
- <p style='font-size:1.5em;'>Status: {status} | Chaves em Rotação: {len(KEYS)}</p>
28
- <p style='color:#666;'>Ponte de Guerrilha: Beira -> OpenRouter -> Aria Ecosystem</p>
29
  </body>
30
  """
31
 
32
  @app.post("/v1/chat/completions")
33
  async def proxy(request: Request):
34
  if not KEYS:
35
- return Response(content='{"error": "Configure OR_KEY_1 até 15 nos Secrets!"}', status_code=500)
36
 
37
  body = await request.json()
38
  incoming_model = body.get("model", "")
39
  msg_content = str(body.get("messages", "")).lower()
40
 
41
- # --- ROTEADOR INTELIGENTE ARIA ---
42
-
43
- # 1. Ordem Direta (Prefixo Fortune)
44
  if "fortune/" in incoming_model:
 
45
  target = incoming_model.replace("fortune/", "", 1)
46
- print(f"🎯 Comando Manual: {target}")
47
-
48
- # 2. Seleção Automática (Aria detecta o contexto)
49
  else:
50
- # Detecta palavras-chave para trocar de "especialização"
51
- if any(word in msg_content for word in ["vitalis", "medicina", "paciente", "diagnóstico"]):
52
  target = MODEL_MAP["aria_med"]
53
- elif any(word in msg_content for word in ["nexos", "erp", "gestão", "stock", "venda"]):
54
  target = MODEL_MAP["aria_logic"]
55
- elif any(word in msg_content for word in ["nutrilens", "visão", "vejo", "imagem"]):
56
  target = MODEL_MAP["aria_vision"]
57
- elif "aria" in msg_content:
58
- target = MODEL_MAP["aria_brain"]
59
  else:
60
- target = MODEL_MAP["aria_default"]
61
-
62
- body["model"] = target
63
 
64
- # --- CICLO DE ROTAÇÃO E SOBREVIVÊNCIA ---
65
- max_retries = 5
 
66
 
 
 
 
 
67
  async with httpx.AsyncClient() as client:
68
- for attempt in range(max_retries):
69
  selected_key = random.choice(KEYS)
70
  headers = {
71
  "Authorization": f"Bearer {selected_key}",
72
- "X-Title": "Aria_Sovereign_System",
73
- "HTTP-Referer": "https://fortune-dev-moz.io",
74
  "Content-Type": "application/json"
75
  }
76
 
77
  try:
78
- # Timeout de 120s para modelos massivos
79
  resp = await client.post(
80
  "https://openrouter.ai/api/v1/chat/completions",
81
  json=body, headers=headers, timeout=120.0
@@ -84,22 +78,17 @@ async def proxy(request: Request):
84
  if resp.status_code == 200:
85
  return Response(content=resp.content, status_code=200)
86
 
87
- if resp.status_code in [429, 402, 502, 503, 504]:
88
- print(f"⚠️ Chave bloqueada. Tentando nova chave ({attempt+1}/{max_retries})...")
89
- continue
90
-
91
  except Exception as e:
92
- print(f"⚠️ Erro na tentativa {attempt+1}: {str(e)}")
93
  await asyncio.sleep(0.3)
94
  continue
95
 
96
- # --- MODO DE EMERGÊNCIA ---
97
  body["model"] = "openrouter/free"
98
- try:
99
- emerg_resp = await client.post("https://openrouter.ai/api/v1/chat/completions", json=body, headers=headers, timeout=60.0)
100
- return Response(content=emerg_resp.content, status_code=emerg_resp.status_code)
101
- except:
102
- return Response(content='{"error": "Falha crítica no Escudo. Reinicie as chaves."}', status_code=503)
103
 
104
  if __name__ == "__main__":
105
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
4
 
5
  app = FastAPI()
6
 
7
+ # Pool de 15 Chaves - Arsenal Aria
8
  KEYS = [os.getenv(f"OR_KEY_{i}") for i in range(1, 16)]
9
  KEYS = [k for k in KEYS if k and k.strip()]
10
 
11
+ # MAPEAMENTO UNIFICADO ARIA (Com sufixos únicos para o Python)
 
12
  MODEL_MAP = {
13
+ "aria_med": "google/gemini-2.5-pro:free", # Vitalis
14
+ "aria_logic": "qwen/qwen3-coder-480b:free", # Nexos
15
+ "aria_vision": "nvidia/nemotron-nano-12b-2-vl:free", # Nutrilens
16
+ "aria_brain": "meta-llama/llama-3.3-70b-instruct:free", # Cérebro Principal
17
+ "aria_default": "qwen/qwen3-coder:free"
18
  }
19
 
20
  @app.get("/", response_class=HTMLResponse)
21
  async def root():
22
+ status = "🟢 SISTEMA OPERACIONAL" if KEYS else "🔴 FALHA NAS CHAVES"
23
  return f"""
24
+ <body style='background:#0a0a0a; color:#00ff99; font-family:monospace; text-align:center; padding-top:50px;'>
25
+ <h1 style='border: 2px solid #00ff99; display:inline-block; padding:20px;'>🛡️ ARIA SOVEREIGN SHIELD V2.5</h1>
26
+ <p style='font-size:1.5em;'>Chaves Ativas: {len(KEYS)} | Local: Beira, MZ</p>
27
+ <p style='color:#555;'>Status: {status}</p>
28
  </body>
29
  """
30
 
31
  @app.post("/v1/chat/completions")
32
  async def proxy(request: Request):
33
  if not KEYS:
34
+ return Response(content='{"error": "Adicione as chaves nos Secrets do HF!"}', status_code=500)
35
 
36
  body = await request.json()
37
  incoming_model = body.get("model", "")
38
  msg_content = str(body.get("messages", "")).lower()
39
 
40
+ # --- LOGICA DE ROTEAMENTO ---
 
 
41
  if "fortune/" in incoming_model:
42
+ # Extrai o modelo real enviado pelo CEO
43
  target = incoming_model.replace("fortune/", "", 1)
 
 
 
44
  else:
45
+ # Seleção por contexto se o CEO não especificar fortune/
46
+ if any(word in msg_content for word in ["medicina", "vitalis", "paciente"]):
47
  target = MODEL_MAP["aria_med"]
48
+ elif any(word in msg_content for word in ["nexos", "venda", "gestão", "erp"]):
49
  target = MODEL_MAP["aria_logic"]
50
+ elif any(word in msg_content for word in ["nutrilens", "vejo", "câmara", "visão"]):
51
  target = MODEL_MAP["aria_vision"]
 
 
52
  else:
53
+ target = MODEL_MAP["aria_brain"]
 
 
54
 
55
+ # Correção de Segurança: Garante que modelos free tenham o sufixo :free
56
+ if "instruct" in target and not target.endswith(":free"):
57
+ target = f"{target}:free"
58
 
59
+ body["model"] = target
60
+ print(f"📡 Roteando para: {target}")
61
+
62
+ # --- CICLO DE RESILIÊNCIA ---
63
  async with httpx.AsyncClient() as client:
64
+ for attempt in range(5):
65
  selected_key = random.choice(KEYS)
66
  headers = {
67
  "Authorization": f"Bearer {selected_key}",
68
+ "X-Title": "Aria_Sovereign",
 
69
  "Content-Type": "application/json"
70
  }
71
 
72
  try:
 
73
  resp = await client.post(
74
  "https://openrouter.ai/api/v1/chat/completions",
75
  json=body, headers=headers, timeout=120.0
 
78
  if resp.status_code == 200:
79
  return Response(content=resp.content, status_code=200)
80
 
81
+ print(f"⚠️ Tentativa {attempt+1} falhou (Status {resp.status_code}). Rodando chave...")
82
+
 
 
83
  except Exception as e:
84
+ print(f" Erro de rede: {str(e)}")
85
  await asyncio.sleep(0.3)
86
  continue
87
 
88
+ # Fallback Final para o roteador livre
89
  body["model"] = "openrouter/free"
90
+ emerg = await client.post("https://openrouter.ai/api/v1/chat/completions", json=body, headers=headers, timeout=60.0)
91
+ return Response(content=emerg.content, status_code=emerg.status_code)
 
 
 
92
 
93
  if __name__ == "__main__":
94
  uvicorn.run(app, host="0.0.0.0", port=7860)