Spaces:
Running
Running
Download app.py from onaaction/timesfm-api: direct link, hf CLI and curl.
- Browser
- Download file 8.55 kB
-
https://huggingface.co/spaces/onaaction/timesfm-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/onaaction/timesfm-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/onaaction/timesfm-api/resolve/main/app.py
8.55 kB
| """ | |
| TimesFM API v2 - Utilise Hugging Face Inference API | |
| Plus de problèmes de dépendances ! | |
| """ | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import List, Optional | |
| import numpy as np | |
| import httpx | |
| import logging | |
| from datetime import datetime | |
| import os | |
| # Setup logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # FastAPI app | |
| app = FastAPI( | |
| title="TimesFM Forecasting API", | |
| description="API REST utilisant TimesFM via Hugging Face Inference", | |
| version="2.1.0" | |
| ) | |
| # CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Configuration Hugging Face Inference API | |
| HF_API_URL = "https://api-inference.huggingface.co/models/google/timesfm-1.0-200m" | |
| HF_TOKEN = os.getenv("HF_TOKEN", "") # Token optionnel | |
| # HTTP client | |
| http_client = httpx.AsyncClient(timeout=60.0) | |
| async def predict_with_hf_inference(data: List[float], horizon: int) -> List[float]: | |
| """ | |
| Utilise l'API Inference de Hugging Face pour TimesFM | |
| Pas besoin d'installer timesfm localement ! | |
| """ | |
| try: | |
| logger.info(f"🔮 Appel HF Inference API pour {len(data)} points, horizon={horizon}") | |
| headers = {} | |
| if HF_TOKEN: | |
| headers["Authorization"] = f"Bearer {HF_TOKEN}" | |
| # Préparer payload | |
| payload = { | |
| "inputs": data, | |
| "parameters": { | |
| "horizon": horizon | |
| } | |
| } | |
| # Appel API | |
| response = await http_client.post( | |
| HF_API_URL, | |
| json=payload, | |
| headers=headers | |
| ) | |
| if response.status_code == 200: | |
| result = response.json() | |
| # Extraire les prédictions | |
| if isinstance(result, list): | |
| forecast = result[:horizon] | |
| elif isinstance(result, dict) and "forecast" in result: | |
| forecast = result["forecast"][:horizon] | |
| else: | |
| logger.warning("Format inattendu de HF Inference, fallback") | |
| return None | |
| logger.info(f"✅ Prédiction HF Inference réussie: {forecast[:3]}...") | |
| return [float(x) for x in forecast] | |
| elif response.status_code == 503: | |
| logger.warning("⏳ Modèle en cours de chargement sur HF...") | |
| return None | |
| else: | |
| logger.error(f"❌ HF Inference erreur {response.status_code}: {response.text}") | |
| return None | |
| except Exception as e: | |
| logger.error(f"❌ Erreur HF Inference: {e}") | |
| return None | |
| def fallback_forecast(data: List[float], horizon: int) -> List[float]: | |
| """Prédiction de secours avec régression linéaire intelligente""" | |
| logger.info("🔄 Utilisation du fallback (régression linéaire)") | |
| n = len(data) | |
| x = np.arange(n) | |
| # Régression linéaire avec numpy | |
| coeffs = np.polyfit(x, data, deg=1) | |
| slope, intercept = coeffs[0], coeffs[1] | |
| # Prédiction avec dampening intelligent | |
| forecast = [] | |
| for i in range(horizon): | |
| # Dampening qui diminue l'influence du slope | |
| dampening = max(0.95 ** i, 0.6) | |
| pred = intercept + slope * (n + i) * dampening | |
| forecast.append(float(pred)) | |
| return forecast | |
| # Modèles Pydantic | |
| class ForecastRequest(BaseModel): | |
| data: List[float] | |
| horizon: int = 6 | |
| class Config: | |
| json_schema_extra = { | |
| "example": { | |
| "data": [100.0, 120.0, 110.0, 150.0, 180.0, 200.0], | |
| "horizon": 6 | |
| } | |
| } | |
| class ForecastResponse(BaseModel): | |
| success: bool | |
| point_forecast: List[float] | |
| volatility: Optional[float] = None | |
| stability_score: Optional[float] = None | |
| trend: Optional[str] = None | |
| risk_level: Optional[str] = None | |
| model_version: str | |
| timestamp: str | |
| async def startup_event(): | |
| """Au démarrage""" | |
| logger.info("🚀 Démarrage TimesFM API v2 (HF Inference)") | |
| async def shutdown_event(): | |
| """Fermeture propre""" | |
| await http_client.aclose() | |
| async def root(): | |
| """Page d'accueil""" | |
| return { | |
| "name": "TimesFM Forecasting API", | |
| "version": "2.1.0", | |
| "status": "operational", | |
| "model": "Google TimesFM via HF Inference", | |
| "endpoints": { | |
| "health": "/health", | |
| "forecast": "/api/forecast", | |
| "docs": "/docs" | |
| } | |
| } | |
| async def health_check(): | |
| """Health check""" | |
| # Tester HF Inference | |
| test_available = False | |
| try: | |
| test_response = await http_client.get( | |
| HF_API_URL, | |
| timeout=5.0 | |
| ) | |
| test_available = test_response.status_code in [200, 503] | |
| except: | |
| pass | |
| return { | |
| "status": "healthy", | |
| "hf_inference_available": test_available, | |
| "fallback_available": True, | |
| "timestamp": datetime.now().isoformat() | |
| } | |
| async def forecast(request: ForecastRequest): | |
| """ | |
| Endpoint principal de prédiction | |
| Compatible avec Polymarket Bot | |
| """ | |
| try: | |
| # Validation | |
| if len(request.data) < 3: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Minimum 3 points de données requis" | |
| ) | |
| if request.horizon < 1 or request.horizon > 128: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Horizon doit être entre 1 et 128" | |
| ) | |
| # Convertir en numpy | |
| data_array = np.array(request.data, dtype=np.float32) | |
| # Tenter prédiction avec HF Inference | |
| forecast_values = await predict_with_hf_inference(request.data, request.horizon) | |
| # Fallback si échec | |
| if forecast_values is None: | |
| forecast_values = fallback_forecast(request.data, request.horizon) | |
| model_used = "Fallback-LinearRegression" | |
| else: | |
| model_used = "Google-TimesFM-1.0-200M-HF-Inference" | |
| # Calculer métriques | |
| mean_val = float(np.mean(data_array)) | |
| std_val = float(np.std(data_array)) | |
| volatility = std_val / abs(mean_val) if mean_val != 0 else 0.0 | |
| # Stability score (0-100) | |
| stability_score = max(0, min(100, 100 * (1 - min(volatility, 1)))) | |
| # Trend detection | |
| if len(request.data) > 1: | |
| recent_change = request.data[-1] - request.data[0] | |
| threshold = abs(mean_val) * 0.1 | |
| if recent_change > threshold: | |
| trend = "upward" | |
| elif recent_change < -threshold: | |
| trend = "downward" | |
| else: | |
| trend = "stable" | |
| else: | |
| trend = "unknown" | |
| # Risk level | |
| if volatility < 0.15: | |
| risk_level = "LOW" | |
| elif volatility < 0.30: | |
| risk_level = "MODERATE" | |
| else: | |
| risk_level = "HIGH" | |
| # Construire réponse | |
| return ForecastResponse( | |
| success=True, | |
| point_forecast=forecast_values, | |
| volatility=round(volatility, 4), | |
| stability_score=round(stability_score, 2), | |
| trend=trend, | |
| risk_level=risk_level, | |
| model_version=model_used, | |
| timestamp=datetime.now().isoformat() | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| logger.error(f"❌ Erreur forecast: {e}") | |
| raise HTTPException( | |
| status_code=500, | |
| detail=f"Erreur lors de la prédiction: {str(e)}" | |
| ) | |
| async def forecast_alias(request: ForecastRequest): | |
| """Alias pour compatibilité""" | |
| return await forecast(request) | |
| async def test_prediction(): | |
| """Test rapide""" | |
| test_data = [100.0, 120.0, 110.0, 150.0, 180.0, 200.0] | |
| request = ForecastRequest( | |
| data=test_data, | |
| horizon=6 | |
| ) | |
| return await forecast(request) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| print("🚀 TimesFM API v2 - HF Inference") | |
| print("📖 Documentation: http://localhost:7860/docs") | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |