Spaces:
Sleeping
Sleeping
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,21 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def fetch_banxico_serie(serie_id: str) -> dict:
|
| 2 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 3 |
try:
|
| 4 |
r = requests.get(url, timeout=15)
|
| 5 |
r.raise_for_status()
|
| 6 |
-
|
| 7 |
-
# Banxico regresa JSON
|
| 8 |
data = r.json()
|
| 9 |
-
|
| 10 |
-
# Estructura: {"bmx": {"series": [{"idSerie": "...", "datos": [{"fecha": "...", "dato": "..."}]}]}}
|
| 11 |
series = data.get("bmx", {}).get("series", [])
|
| 12 |
if not series:
|
| 13 |
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
| 14 |
-
|
| 15 |
datos = series[0].get("datos", [])
|
| 16 |
if not datos:
|
| 17 |
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
| 18 |
-
|
| 19 |
ultimo = datos[-1]
|
| 20 |
return {
|
| 21 |
"serie": serie_id,
|
|
@@ -24,4 +57,168 @@ def fetch_banxico_serie(serie_id: str) -> dict:
|
|
| 24 |
"fecha": ultimo.get("fecha"),
|
| 25 |
}
|
| 26 |
except Exception as e:
|
| 27 |
-
return {"serie": serie_id, "error": str(e)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 6 |
+
from datetime import datetime
|
| 7 |
+
from fastapi import FastAPI, HTTPException
|
| 8 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
|
| 11 |
+
app = FastAPI(title="Fer Private AI · API", version="1.0.0")
|
| 12 |
+
|
| 13 |
+
app.add_middleware(
|
| 14 |
+
CORSMiddleware,
|
| 15 |
+
allow_origins=["*"],
|
| 16 |
+
allow_methods=["*"],
|
| 17 |
+
allow_headers=["*"],
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY", "")
|
| 21 |
+
BANXICO_TOKEN = os.getenv("BANXICO_TOKEN", "")
|
| 22 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
| 23 |
+
NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"
|
| 24 |
+
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
| 25 |
+
|
| 26 |
+
BANXICO_SERIES = {
|
| 27 |
+
"SF43718": "Tipo de cambio USD/MXN (FIX)",
|
| 28 |
+
"SF46410": "TIIE 28 días (%)",
|
| 29 |
+
"SF61745": "Tasa objetivo Banxico (%)",
|
| 30 |
+
"SP74625": "Inflación general",
|
| 31 |
+
"SF290383": "Reservas internacionales (MDD)",
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
# ── Models ────────────────────────────────────────────────────────────────────
|
| 35 |
+
class ChatRequest(BaseModel):
|
| 36 |
+
query: str
|
| 37 |
+
session_id: str = "mobile"
|
| 38 |
+
|
| 39 |
+
# ── Helpers ───────────────────────────────────────────────────────────────────
|
| 40 |
def fetch_banxico_serie(serie_id: str) -> dict:
|
| 41 |
url = f"https://www.banxico.org.mx/SieAPIRest/service/v1/series/{serie_id}/datos/oportuno?token={BANXICO_TOKEN}"
|
| 42 |
try:
|
| 43 |
r = requests.get(url, timeout=15)
|
| 44 |
r.raise_for_status()
|
|
|
|
|
|
|
| 45 |
data = r.json()
|
|
|
|
|
|
|
| 46 |
series = data.get("bmx", {}).get("series", [])
|
| 47 |
if not series:
|
| 48 |
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
|
|
|
| 49 |
datos = series[0].get("datos", [])
|
| 50 |
if not datos:
|
| 51 |
return {"serie": serie_id, "nombre": BANXICO_SERIES.get(serie_id), "valor": None, "fecha": None}
|
|
|
|
| 52 |
ultimo = datos[-1]
|
| 53 |
return {
|
| 54 |
"serie": serie_id,
|
|
|
|
| 57 |
"fecha": ultimo.get("fecha"),
|
| 58 |
}
|
| 59 |
except Exception as e:
|
| 60 |
+
return {"serie": serie_id, "error": str(e)}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def call_llm(prompt: str) -> dict:
|
| 64 |
+
if GROQ_API_KEY:
|
| 65 |
+
try:
|
| 66 |
+
start = time.time()
|
| 67 |
+
headers = {
|
| 68 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 69 |
+
"Content-Type": "application/json"
|
| 70 |
+
}
|
| 71 |
+
payload = {
|
| 72 |
+
"model": "llama-3.3-70b-versatile",
|
| 73 |
+
"messages": [
|
| 74 |
+
{"role": "system", "content": "Eres un experto en economía mexicana. Responde en español, de forma concisa y precisa."},
|
| 75 |
+
{"role": "user", "content": prompt}
|
| 76 |
+
],
|
| 77 |
+
"max_tokens": 1024,
|
| 78 |
+
"temperature": 0.3,
|
| 79 |
+
}
|
| 80 |
+
r = requests.post(f"{GROQ_BASE_URL}/chat/completions",
|
| 81 |
+
headers=headers, json=payload, timeout=15)
|
| 82 |
+
r.raise_for_status()
|
| 83 |
+
data = r.json()
|
| 84 |
+
latencia = int((time.time() - start) * 1000)
|
| 85 |
+
return {
|
| 86 |
+
"respuesta": data["choices"][0]["message"]["content"],
|
| 87 |
+
"modelo": "Llama 3.3 70B · Groq LPU",
|
| 88 |
+
"latencia_ms": latencia,
|
| 89 |
+
}
|
| 90 |
+
except Exception:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
start = time.time()
|
| 95 |
+
headers = {
|
| 96 |
+
"Authorization": f"Bearer {NVIDIA_API_KEY}",
|
| 97 |
+
"Content-Type": "application/json"
|
| 98 |
+
}
|
| 99 |
+
payload = {
|
| 100 |
+
"model": "meta/llama-3.1-70b-instruct",
|
| 101 |
+
"messages": [
|
| 102 |
+
{"role": "system", "content": "Eres un experto en economía mexicana. Responde en español."},
|
| 103 |
+
{"role": "user", "content": prompt}
|
| 104 |
+
],
|
| 105 |
+
"max_tokens": 1024,
|
| 106 |
+
"temperature": 0.3,
|
| 107 |
+
}
|
| 108 |
+
r = requests.post(f"{NVIDIA_BASE_URL}/chat/completions",
|
| 109 |
+
headers=headers, json=payload, timeout=45)
|
| 110 |
+
r.raise_for_status()
|
| 111 |
+
data = r.json()
|
| 112 |
+
latencia = int((time.time() - start) * 1000)
|
| 113 |
+
return {
|
| 114 |
+
"respuesta": data["choices"][0]["message"]["content"],
|
| 115 |
+
"modelo": "LLaMA 3.1 70B · NVIDIA H100",
|
| 116 |
+
"latencia_ms": latencia,
|
| 117 |
+
}
|
| 118 |
+
except Exception as e:
|
| 119 |
+
return {
|
| 120 |
+
"respuesta": f"Error de inferencia: {e}",
|
| 121 |
+
"modelo": "error",
|
| 122 |
+
"latencia_ms": 0,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
# ── Endpoints ────────────────────��────────────────────────────────────────────
|
| 126 |
+
|
| 127 |
+
@app.get("/")
|
| 128 |
+
def root():
|
| 129 |
+
return {
|
| 130 |
+
"name": "Fer Private AI · API",
|
| 131 |
+
"version": "1.0.0",
|
| 132 |
+
"status": "ok",
|
| 133 |
+
"endpoints": ["/health", "/indicadores", "/telco", "/worldbank", "/chat"],
|
| 134 |
+
"compute": "NVIDIA H100 · NIM + Groq LPU",
|
| 135 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
@app.get("/health")
|
| 139 |
+
def health():
|
| 140 |
+
return {
|
| 141 |
+
"status": "ok",
|
| 142 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 143 |
+
"compute": "NVIDIA H100 · NIM",
|
| 144 |
+
"secrets": {
|
| 145 |
+
"NVIDIA_API_KEY": "✅" if NVIDIA_API_KEY else "❌",
|
| 146 |
+
"BANXICO_TOKEN": "✅" if BANXICO_TOKEN else "❌",
|
| 147 |
+
"GROQ_API_KEY": "✅" if GROQ_API_KEY else "❌",
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
@app.get("/indicadores")
|
| 152 |
+
def indicadores():
|
| 153 |
+
if not BANXICO_TOKEN:
|
| 154 |
+
raise HTTPException(status_code=503, detail="BANXICO_TOKEN no configurado")
|
| 155 |
+
resultados = {}
|
| 156 |
+
for serie_id in BANXICO_SERIES:
|
| 157 |
+
resultados[serie_id] = fetch_banxico_serie(serie_id)
|
| 158 |
+
return {
|
| 159 |
+
"fuente": "Banxico SIE API",
|
| 160 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 161 |
+
"indicadores": resultados,
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
@app.get("/telco")
|
| 165 |
+
def telco():
|
| 166 |
+
return {
|
| 167 |
+
"fuente": "IFT · Instituto Federal de Telecomunicaciones",
|
| 168 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 169 |
+
"mercado_movil": {
|
| 170 |
+
"total_lineas_millones": 127.4,
|
| 171 |
+
"periodo": "Q3 2024",
|
| 172 |
+
"operadores": [
|
| 173 |
+
{"operador": "Telcel", "participacion_pct": 63.4},
|
| 174 |
+
{"operador": "AT&T México", "participacion_pct": 17.5},
|
| 175 |
+
{"operador": "Movistar", "participacion_pct": 17.0},
|
| 176 |
+
{"operador": "Otros MVNOs", "participacion_pct": 2.1},
|
| 177 |
+
]
|
| 178 |
+
},
|
| 179 |
+
"ingresos_q1_2025_millones_mxn": 148541.1,
|
| 180 |
+
"cobertura_4g_pct_poblacion": 92.0,
|
| 181 |
+
"penetracion_5g_pct": 3.5,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
@app.get("/worldbank")
|
| 185 |
+
def worldbank():
|
| 186 |
+
WB_INDICATORS = {
|
| 187 |
+
"NY.GDP.MKTP.CD": "PIB México (USD)",
|
| 188 |
+
"FP.CPI.TOTL.ZG": "Inflación anual (%)",
|
| 189 |
+
"SL.UEM.TOTL.ZS": "Desempleo (%)",
|
| 190 |
+
}
|
| 191 |
+
resultados = {}
|
| 192 |
+
for indicator, nombre in WB_INDICATORS.items():
|
| 193 |
+
try:
|
| 194 |
+
url = f"https://api.worldbank.org/v2/country/MX/indicator/{indicator}?format=json&mrv=1"
|
| 195 |
+
r = requests.get(url, timeout=15)
|
| 196 |
+
data = r.json()
|
| 197 |
+
if len(data) > 1 and data[1]:
|
| 198 |
+
entry = data[1][0]
|
| 199 |
+
resultados[indicator] = {
|
| 200 |
+
"nombre": nombre,
|
| 201 |
+
"valor": entry.get("value"),
|
| 202 |
+
"año": entry.get("date"),
|
| 203 |
+
}
|
| 204 |
+
except Exception as e:
|
| 205 |
+
resultados[indicator] = {"nombre": nombre, "error": str(e)}
|
| 206 |
+
return {
|
| 207 |
+
"fuente": "World Bank API",
|
| 208 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 209 |
+
"indicadores": resultados,
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
@app.post("/chat")
|
| 213 |
+
def chat(req: ChatRequest):
|
| 214 |
+
if not req.query.strip():
|
| 215 |
+
raise HTTPException(status_code=400, detail="Query vacía")
|
| 216 |
+
result = call_llm(req.query)
|
| 217 |
+
return {
|
| 218 |
+
"query": req.query,
|
| 219 |
+
"response": result.get("respuesta", ""),
|
| 220 |
+
"modelo": result.get("modelo", ""),
|
| 221 |
+
"latencia_ms": result.get("latencia_ms", 0),
|
| 222 |
+
"timestamp": datetime.utcnow().isoformat() + "Z",
|
| 223 |
+
"infraestructura": "Fer Private AI · datos nunca salen de infraestructura privada",
|
| 224 |
+
}
|