Fercor95mx commited on
Commit
4697153
·
verified ·
1 Parent(s): d828681

Update main.py

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