Download history.py from andervier/Tazas_API: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/andervier/Tazas_API/resolve/main/history.py
- Command line
-
hf download hf://spaces/andervier/Tazas_API/history.py
-
curl -L -o history.py https://huggingface.co/spaces/andervier/Tazas_API/resolve/main/history.py
11 kB
| """ | |
| Histórico de tasas persistido en Firestore. | |
| Diseño pensado para HF Spaces (disco efímero, 2 workers uvicorn) y para no | |
| saturar el tier gratis de Firebase: | |
| - Un único escritor: el muestreador (cada 15 min) llama record_*(); se escribe | |
| solo si el valor cambió (dedupe por worker). No hay escritura oportunista | |
| desde los fetchers, para acotar el volumen de escrituras. | |
| - Puntos como MAPA {bucket: valores} dentro del doc, indexados por franja de | |
| 15 min. Una sola entrada por bucket: si dos fuentes escriben la misma franja | |
| con precios distintos, la última gana (antes, ArrayUnion apilaba ambas y | |
| duplicaba puntos con el mismo `t`). | |
| - Documentos MENSUALES por serie (BCV_2026-07, VES_2026-07, COP_2026-07...): | |
| leer 35 días cuesta ≤2 lecturas por serie, y los meses pasados son | |
| inmutables → se cachean en memoria y las lecturas repetidas cuestan 0. | |
| Con 1 punto por franja de 15 min, un mes ≈ 3000 puntos (muy por debajo del | |
| límite de 1 MiB por documento de Firestore). | |
| Requiere el secret FIREBASE_SERVICE_ACCOUNT (JSON de la service account del | |
| proyecto Firebase). Sin él, el histórico queda deshabilitado y la API sigue | |
| funcionando normal. | |
| """ | |
| import asyncio | |
| import json | |
| import logging | |
| import os | |
| import time | |
| from datetime import datetime, timedelta, timezone | |
| logger = logging.getLogger(__name__) | |
| COLLECTION = "rate_history" | |
| BUCKET_SECONDS = 900 # una entrada por franja de 15 min (= cadencia del muestreador) | |
| MAX_DAYS = 35 | |
| # Caché de lecturas: el mes actual expira rápido; los pasados son inmutables. | |
| CURRENT_MONTH_TTL = 60 * 10 | |
| PAST_MONTH_TTL = 60 * 60 * 24 | |
| _db = None # firestore.AsyncClient | |
| _enabled = False | |
| _last_values: dict[str, dict] = {} # dedupe por worker: serie → últimos valores escritos | |
| _read_cache: dict[str, dict] = {} # doc_id → {"ts": epoch, "points": [...]} | |
| def init() -> None: | |
| """Inicializa Firestore desde el secret. Nunca tumba la API si falta.""" | |
| global _db, _enabled | |
| raw = os.getenv("FIREBASE_SERVICE_ACCOUNT") | |
| if not raw: | |
| logger.warning("FIREBASE_SERVICE_ACCOUNT no configurado — histórico deshabilitado") | |
| return | |
| try: | |
| from google.cloud import firestore | |
| from google.oauth2 import service_account | |
| info = json.loads(raw) | |
| creds = service_account.Credentials.from_service_account_info( | |
| info, scopes=["https://www.googleapis.com/auth/datastore"] | |
| ) | |
| _db = firestore.AsyncClient(project=info["project_id"], credentials=creds) | |
| _enabled = True | |
| logger.warning("Histórico habilitado (proyecto %s)", info["project_id"]) | |
| except Exception as e: | |
| logger.error("No se pudo inicializar Firestore: %s", e, exc_info=True) | |
| def is_enabled() -> bool: | |
| return _enabled | |
| def get_db(): | |
| """Cliente Firestore compartido (o None si el histórico está deshabilitado). | |
| Lo reutiliza stats.py para volcar métricas sin abrir otra conexión.""" | |
| return _db | |
| # ────────────────────────────────────────────── | |
| # Escritura (fire-and-forget desde el muestreador) | |
| # ────────────────────────────────────────────── | |
| def record_bcv(data: dict) -> None: | |
| values = { | |
| k: data.get(src) | |
| for k, src in (("usd", "bcvUsd"), ("eur", "bcvEur"), ("cny", "bcvCny"), | |
| ("try", "bcvTry"), ("rub", "bcvRub")) | |
| if data.get(src) is not None | |
| } | |
| _schedule("BCV", values) | |
| def record_p2p(fiat: str, buy: float | None, sell: float | None) -> None: | |
| values = {} | |
| if buy is not None: | |
| values["buy"] = buy | |
| if sell is not None: | |
| values["sell"] = sell | |
| _schedule(fiat, values) | |
| def _schedule(series: str, values: dict) -> None: | |
| if not _enabled or not values: | |
| return | |
| if _last_values.get(series) == values: | |
| return # nada cambió desde la última escritura de este worker | |
| try: | |
| asyncio.get_running_loop().create_task(_append(series, values)) | |
| except RuntimeError: | |
| pass # sin event loop (tests) — no registrar | |
| async def _append(series: str, values: dict) -> None: | |
| now = int(time.time()) | |
| month = datetime.fromtimestamp(now, tz=timezone.utc).strftime("%Y-%m") | |
| doc_id = f"{series}_{month}" | |
| try: | |
| doc = _db.collection(COLLECTION).document(doc_id) | |
| # Dedup robusto contra Firestore: cubre el hueco de _last_values (memoria) | |
| # tras un reinicio del Space. Si el último valor almacenado este mes es | |
| # idéntico, NO se escribe — así no se acumulan puntos del mismo monto. | |
| # Solo se lee aquí (no en el camino común, que ya cortó _schedule en memoria). | |
| last_stored = await _latest_stored_values(doc) | |
| if last_stored == values: | |
| _last_values[series] = values | |
| return | |
| # Mapa {bucket: valores} con merge: una sola entrada por franja de 15 min. | |
| bucket = now // BUCKET_SECONDS * BUCKET_SECONDS | |
| await doc.set({"points": {str(bucket): values}}, merge=True) | |
| _last_values[series] = values | |
| # El doc del mes actual cambió: invalidar su caché de lectura local. | |
| _read_cache.pop(doc_id, None) | |
| except Exception as e: | |
| logger.error("No se pudo registrar histórico %s: %s", series, e) | |
| async def _latest_stored_values(doc) -> dict | None: | |
| """Valores (sin `t`) del punto más reciente del doc, o None si está vacío.""" | |
| snap = await doc.get() | |
| if not snap.exists: | |
| return None | |
| points = _normalize_points((snap.to_dict() or {}).get("points")) | |
| if not points: | |
| return None | |
| latest = max(points, key=lambda p: p.get("t", 0)) | |
| return {k: v for k, v in latest.items() if k != "t"} | |
| # ────────────────────────────────────────────── | |
| # Lectura | |
| # ────────────────────────────────────────────── | |
| async def get_history(series: str, days: int) -> list[dict]: | |
| """Puntos de la serie en los últimos `days` días, ordenados por timestamp.""" | |
| if not _enabled: | |
| return [] | |
| days = max(1, min(days, MAX_DAYS)) | |
| now = datetime.now(tz=timezone.utc) | |
| cutoff = int((now - timedelta(days=days)).timestamp()) | |
| points: list[dict] = [] | |
| for month in _months_between(now - timedelta(days=days), now): | |
| points.extend(await _read_month(series, month, is_current=(month == now.strftime("%Y-%m")))) | |
| return sorted((p for p in points if p.get("t", 0) >= cutoff), key=lambda p: p["t"]) | |
| def _months_between(start: datetime, end: datetime) -> list[str]: | |
| months = [] | |
| cursor = datetime(start.year, start.month, 1, tzinfo=timezone.utc) | |
| while cursor <= end: | |
| months.append(cursor.strftime("%Y-%m")) | |
| cursor = datetime( | |
| cursor.year + (cursor.month == 12), | |
| cursor.month % 12 + 1, | |
| 1, | |
| tzinfo=timezone.utc, | |
| ) | |
| return months | |
| async def _read_month(series: str, month: str, is_current: bool) -> list[dict]: | |
| doc_id = f"{series}_{month}" | |
| ttl = CURRENT_MONTH_TTL if is_current else PAST_MONTH_TTL | |
| cached = _read_cache.get(doc_id) | |
| if cached and (time.time() - cached["ts"]) < ttl: | |
| return cached["points"] | |
| try: | |
| snap = await _db.collection(COLLECTION).document(doc_id).get() | |
| raw = (snap.to_dict() or {}).get("points") if snap.exists else None | |
| points = _normalize_points(raw) | |
| except Exception as e: | |
| logger.error("No se pudo leer histórico %s: %s", doc_id, e) | |
| # Fallback: servir caché vencido antes que nada. | |
| return cached["points"] if cached else [] | |
| _read_cache[doc_id] = {"ts": time.time(), "points": points} | |
| return points | |
| def _normalize_points(raw) -> list[dict]: | |
| """ | |
| Normaliza el campo `points` a lista de {t, ...}. | |
| - Formato nuevo: mapa {bucket: {buy, sell}}. | |
| - Formato viejo (transición): lista [{t, buy, sell}], posiblemente con | |
| duplicados por el bug de ArrayUnion. Se colapsa por `t` (última gana). | |
| """ | |
| if isinstance(raw, dict): | |
| out = [] | |
| for key, val in raw.items(): | |
| if not isinstance(val, dict): | |
| continue | |
| try: | |
| t = int(key) | |
| except (TypeError, ValueError): | |
| continue | |
| out.append({"t": t, **val}) | |
| return out | |
| if isinstance(raw, list): | |
| by_t: dict[int, dict] = {} | |
| for p in raw: | |
| if isinstance(p, dict) and "t" in p: | |
| by_t[p["t"]] = p | |
| return list(by_t.values()) | |
| return [] | |
| # ────────────────────────────────────────────── | |
| # Estado BCV: {current, previous} para la "tasa del viernes" | |
| # ────────────────────────────────────────────── | |
| # El fin de semana rige la tasa publicada el viernes (fecha valor "Lunes"); la | |
| # tasa "del viernes" que algunos usuarios prefieren es la publicación INMEDIATA- | |
| # MENTE anterior (fecha valor "Viernes"). Guardamos {current, previous} en un doc | |
| # aparte para servirla sin reconstruirla en el cliente. Se desplaza current->previous | |
| # solo cuando cambia el `updatedAt` (fecha valor) — idempotente entre los 2 workers. | |
| BCV_STATE_COLLECTION = "bcv_state" | |
| BCV_STATE_DOC = "latest" | |
| async def update_bcv_state(current: dict) -> dict | None: | |
| """Actualiza {current, previous} si el `updatedAt` scrapeado es nuevo. | |
| Devuelve el `previous` resultante (o None). No tumba el scrape si Firestore falla.""" | |
| if not _enabled: | |
| return None | |
| try: | |
| doc = _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC) | |
| snap = await doc.get() | |
| state = snap.to_dict() if snap.exists else {} | |
| stored_current = state.get("current") or {} | |
| # Idempotente: si el worker vecino ya guardó esta misma publicación, | |
| # no volver a desplazar (previous quedaría corrupto). | |
| if stored_current.get("updatedAt") == current.get("updatedAt"): | |
| return state.get("previous") | |
| previous = stored_current or None | |
| await doc.set({"current": current, "previous": previous}) | |
| return previous | |
| except Exception as e: | |
| logger.error("update_bcv_state falló: %s", e) | |
| return None | |
| async def get_bcv_previous() -> dict | None: | |
| """Lee el `previous` (tasa del viernes) del estado BCV, o None.""" | |
| if not _enabled: | |
| return None | |
| try: | |
| snap = await _db.collection(BCV_STATE_COLLECTION).document(BCV_STATE_DOC).get() | |
| if snap.exists: | |
| return (snap.to_dict() or {}).get("previous") | |
| except Exception as e: | |
| logger.error("get_bcv_previous falló: %s", e) | |
| return None | |