Fercor95mx commited on
Commit
8f7b703
·
verified ·
1 Parent(s): 5b11461

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +40 -16
main.py CHANGED
@@ -1,11 +1,13 @@
1
  """
2
- main.py — Fer Private AI · API REST v6.0 · PROXY
3
  mx-data-api Space · Puerto 7860
4
 
5
  v6.0: Proxy puro — toda la lógica vive en mx-data-intelligence
6
  Este Space solo hace forward al Space principal.
7
- NO duplica agent_orchestrator, agent_tools ni ningún módulo.
8
- Un solo cerebro, una sola fuente de verdad.
 
 
9
  """
10
  import os
11
  import requests
@@ -15,13 +17,14 @@ from fastapi import FastAPI, HTTPException
15
  from fastapi.middleware.cors import CORSMiddleware
16
  from pydantic import BaseModel
17
 
18
- app = FastAPI(title="Fer Private AI · API Proxy", version="6.0.0")
19
-
20
- # ── Auto-sync módulos desde mx-data-intelligence al arrancar ─────────────────
21
  def sync_modules_from_brain():
22
  """
23
  Descarga los módulos del agente desde mx-data-intelligence.
24
- Así mx-data-api siempre tiene el código más reciente sin duplicación manual.
 
 
 
25
  """
26
  try:
27
  from huggingface_hub import hf_hub_download
@@ -38,6 +41,10 @@ def sync_modules_from_brain():
38
  "modules/critic_loop.py",
39
  ]
40
 
 
 
 
 
41
  os.makedirs("modules", exist_ok=True)
42
  synced = 0
43
  for module_path in MODULES:
@@ -51,16 +58,20 @@ def sync_modules_from_brain():
51
  )
52
  shutil.copy(local, module_path)
53
  synced += 1
 
54
  except Exception as e:
55
  print(f"[sync] ⚠️ {module_path}: {e}")
56
 
57
- print(f"[sync] ✅ {synced}/{len(MODULES)} módulos sincronizados desde {BRAIN_REPO}")
58
  except Exception as e:
59
  print(f"[sync] ❌ Error en sync: {e} — usando módulos locales existentes")
60
 
61
- # Sincronizar al arrancar en background para no bloquear el inicio
62
- import threading
63
- threading.Thread(target=sync_modules_from_brain, daemon=True).start()
 
 
 
64
 
65
  app.add_middleware(
66
  CORSMiddleware,
@@ -171,7 +182,6 @@ def fetch_banxico(serie_id: str) -> dict:
171
  def call_brain(query: str, session_id: str = "mobile") -> dict:
172
  """Llama al agente via modulos locales — mismo codigo que mx-data-intelligence."""
173
  try:
174
- # Intentar importar el agente local (modulos sincronizados)
175
  from modules.agent_orchestrator import run_agent
176
  start = time.time()
177
  response = run_agent(
@@ -185,7 +195,6 @@ def call_brain(query: str, session_id: str = "mobile") -> dict:
185
  "latencia_ms": int((time.time() - start) * 1000),
186
  }
187
  except ImportError:
188
- # Si no hay modulos locales, usar Groq fallback
189
  pass
190
  except Exception as e:
191
  pass
@@ -242,9 +251,9 @@ def call_groq_fallback(query: str) -> dict:
242
  def root():
243
  return {
244
  "name": "Fer Private AI · API Proxy",
245
- "version": "6.0.0",
246
  "brain": BRAIN_URL,
247
- "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat", "/questions"],
248
  "timestamp": datetime.utcnow().isoformat() + "Z",
249
  }
250
 
@@ -258,11 +267,26 @@ def health():
258
  pass
259
  return {
260
  "status": "ok",
261
- "version": "6.0.0",
262
  "brain": "✅ conectado" if brain_ok else "⚠️ sin respuesta (Space dormido)",
263
  "timestamp": datetime.utcnow().isoformat() + "Z",
264
  }
265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  @app.get("/questions")
267
  def questions(categoria: str = None):
268
  if categoria:
 
1
  """
2
+ main.py — Fer Private AI · API REST v6.1 · PROXY
3
  mx-data-api Space · Puerto 7860
4
 
5
  v6.0: Proxy puro — toda la lógica vive en mx-data-intelligence
6
  Este Space solo hace forward al Space principal.
7
+ v6.1 FIX CRÍTICO: el sync de módulos corría en background (threading daemon)
8
+ y el servidor aceptaba tráfico ANTES de que terminara de descargar
9
+ los módulos nuevos — condición de carrera que servía código viejo
10
+ indefinidamente. Ahora el sync es BLOQUEANTE antes de levantar la app.
11
  """
12
  import os
13
  import requests
 
17
  from fastapi.middleware.cors import CORSMiddleware
18
  from pydantic import BaseModel
19
 
20
+ # ── Auto-sync módulos desde mx-data-intelligence ANTES de levantar la app ────
 
 
21
  def sync_modules_from_brain():
22
  """
23
  Descarga los módulos del agente desde mx-data-intelligence.
24
+ v6.1: Ahora es BLOQUEANTE — se ejecuta y termina ANTES de que
25
+ el servidor acepte tráfico. Sin esto, las primeras requests
26
+ (y potencialmente todas, si el Space nunca recibe tráfico nuevo
27
+ después del sync) usan los módulos viejos indefinidamente.
28
  """
29
  try:
30
  from huggingface_hub import hf_hub_download
 
41
  "modules/critic_loop.py",
42
  ]
43
 
44
+ if not HF_TOKEN:
45
+ print("[sync] ⚠️ HF_TOKEN no disponible — usando módulos locales existentes")
46
+ return
47
+
48
  os.makedirs("modules", exist_ok=True)
49
  synced = 0
50
  for module_path in MODULES:
 
58
  )
59
  shutil.copy(local, module_path)
60
  synced += 1
61
+ print(f"[sync] ✅ {module_path}")
62
  except Exception as e:
63
  print(f"[sync] ⚠️ {module_path}: {e}")
64
 
65
+ print(f"[sync] ✅ COMPLETO: {synced}/{len(MODULES)} módulos sincronizados desde {BRAIN_REPO}")
66
  except Exception as e:
67
  print(f"[sync] ❌ Error en sync: {e} — usando módulos locales existentes")
68
 
69
+ # v6.1 FIX: sync BLOQUEANTE — se completa antes de definir la app y endpoints
70
+ print("[sync] Iniciando sincronización de módulos (bloqueante)...")
71
+ sync_modules_from_brain()
72
+ print("[sync] Sincronización finalizada — levantando servidor")
73
+
74
+ app = FastAPI(title="Fer Private AI · API Proxy", version="6.1.0")
75
 
76
  app.add_middleware(
77
  CORSMiddleware,
 
182
  def call_brain(query: str, session_id: str = "mobile") -> dict:
183
  """Llama al agente via modulos locales — mismo codigo que mx-data-intelligence."""
184
  try:
 
185
  from modules.agent_orchestrator import run_agent
186
  start = time.time()
187
  response = run_agent(
 
195
  "latencia_ms": int((time.time() - start) * 1000),
196
  }
197
  except ImportError:
 
198
  pass
199
  except Exception as e:
200
  pass
 
251
  def root():
252
  return {
253
  "name": "Fer Private AI · API Proxy",
254
+ "version": "6.1.0",
255
  "brain": BRAIN_URL,
256
+ "endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat", "/questions", "/resync"],
257
  "timestamp": datetime.utcnow().isoformat() + "Z",
258
  }
259
 
 
267
  pass
268
  return {
269
  "status": "ok",
270
+ "version": "6.1.0",
271
  "brain": "✅ conectado" if brain_ok else "⚠️ sin respuesta (Space dormido)",
272
  "timestamp": datetime.utcnow().isoformat() + "Z",
273
  }
274
 
275
+ @app.post("/resync")
276
+ def resync():
277
+ """
278
+ v6.1 NUEVO: fuerza re-sincronización de módulos SIN reiniciar el Space.
279
+ Útil para aplicar fixes sin esperar factory reboot completo.
280
+ Llamar con: curl -X POST https://fercor95mx-mx-data-api.hf.space/resync
281
+ """
282
+ sync_modules_from_brain()
283
+ return {
284
+ "status": "sync ejecutado",
285
+ "nota": "Los módulos en RAM (ya importados) NO se actualizan hasta reiniciar el proceso. "
286
+ "Este endpoint solo actualiza los archivos en disco para el próximo arranque.",
287
+ "timestamp": datetime.utcnow().isoformat() + "Z",
288
+ }
289
+
290
  @app.get("/questions")
291
  def questions(categoria: str = None):
292
  if categoria: