Spaces:
Sleeping
Sleeping
Download main.py from JoyZhan/BackendPayactiv: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/JoyZhan/BackendPayactiv/resolve/main/main.py
- Command line
-
hf download hf://spaces/JoyZhan/BackendPayactiv/main.py
-
curl -L -o main.py https://huggingface.co/spaces/JoyZhan/BackendPayactiv/resolve/main/main.py
10.3 kB
| """Unified Financial & Demand Forecast API – FastAPI application entry point. | |
| Supports both: | |
| - EWA Demand Forecast predictions | |
| - Financial Distress Risk predictions | |
| """ | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| from config import settings | |
| from models.forecast import EWAForecastModel | |
| from models.distress import predict_distress | |
| from schemas.request import BatchForecastRequest, ForecastRequest | |
| from schemas.response import ( | |
| BatchForecastResponse, | |
| ConfidenceInterval, | |
| ForecastResponse, | |
| HealthResponse, | |
| ModelInfoResponse, | |
| ) | |
| from utils.validation import validate_history | |
| app = FastAPI( | |
| title="Unified Financial & Demand Forecast API", | |
| description="Combined API for EWA demand forecasting and financial distress prediction", | |
| version="2.0.0", | |
| docs_url="/docs", | |
| redoc_url="/redoc", | |
| ) | |
| def root() -> HTMLResponse: | |
| """Show a small landing page with direct links to the useful endpoints.""" | |
| return HTMLResponse( | |
| """ | |
| <!doctype html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1" /> | |
| <title>Unified Financial & Demand Forecast API</title> | |
| <style> | |
| body { | |
| font-family: Arial, sans-serif; | |
| margin: 0; | |
| min-height: 100vh; | |
| display: grid; | |
| place-items: center; | |
| background: linear-gradient(135deg, #f7f9fc 0%, #eef3ff 100%); | |
| color: #1f2937; | |
| } | |
| .card { | |
| max-width: 640px; | |
| padding: 32px; | |
| border-radius: 16px; | |
| background: white; | |
| box-shadow: 0 12px 40px rgba(15, 23, 42, 0.12); | |
| } | |
| h1 { margin-top: 0; } | |
| a { | |
| display: inline-block; | |
| margin-right: 12px; | |
| margin-top: 8px; | |
| color: #2563eb; | |
| text-decoration: none; | |
| font-weight: 600; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="card"> | |
| <h1>Unified Financial & Demand Forecast API</h1> | |
| <p>The service is running. Use the links below:</p> | |
| <p> | |
| <a href="/docs">API Docs</a> | |
| <a href="/health">Health Check</a> | |
| <a href="/model-info">Model Info</a> | |
| </p> | |
| </div> | |
| </body> | |
| </html> | |
| """ | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Request/Response Models for Distress | |
| # --------------------------------------------------------------------------- | |
| class DistressRequest(BaseModel): | |
| """Request model for financial distress prediction.""" | |
| user_id: Optional[str] = None | |
| total_spend: float | |
| txn_count: float | |
| total_spend_30d: float | |
| max_daily_spend_30d: float | |
| txn_count_30d: float | |
| ewa_usage_count: float = 0 | |
| ewa_total_amount: float = 0 | |
| ewa_avg_amount: float = 0 | |
| ewa_max_amount: float = 0 | |
| class DistressResponse(BaseModel): | |
| """Response model for distress prediction.""" | |
| user_id: Optional[str] = None | |
| risk_score: float | |
| timestamp: str | |
| model_type: str | |
| # --------------------------------------------------------------------------- | |
| # Health check | |
| # --------------------------------------------------------------------------- | |
| def health() -> HealthResponse: | |
| """Return the current health status of the service.""" | |
| return HealthResponse(status="ok", version=settings.app_version) | |
| # --------------------------------------------------------------------------- | |
| # Model information | |
| # --------------------------------------------------------------------------- | |
| def model_info() -> ModelInfoResponse: | |
| """Return metadata and default parameters of the forecast model.""" | |
| return ModelInfoResponse( | |
| name="EWA Demand Forecast Model", | |
| version=settings.app_version, | |
| description=( | |
| "Exponential Weighted Average (EWA) demand forecasting model. " | |
| "Supports simple (level only) and Holt's double (level + trend) " | |
| "exponential smoothing with automatic parameter optimisation." | |
| ), | |
| supported_models=["simple", "double"], | |
| default_alpha=settings.default_alpha, | |
| default_beta=settings.default_beta, | |
| default_horizon=settings.default_horizon, | |
| default_confidence_level=settings.default_confidence_level, | |
| min_history_length=settings.min_history_length, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Single prediction | |
| # --------------------------------------------------------------------------- | |
| def predict(request: ForecastRequest) -> ForecastResponse: | |
| """Fit an EWA model on the supplied history and return a forecast. | |
| * If **alpha** / **beta** are omitted the parameters are automatically | |
| optimised to minimise in-sample squared error. | |
| * Supplying only **alpha** enables simple exponential smoothing. | |
| * Supplying both **alpha** and **beta** enables Holt's double | |
| exponential smoothing with the given parameters. | |
| """ | |
| validate_history(request.history, min_length=settings.min_history_length) | |
| model = EWAForecastModel(alpha=request.alpha, beta=request.beta) | |
| try: | |
| forecast_vals, intervals, alpha_used, beta_used, model_type, rmse = ( | |
| model.fit_predict( | |
| history=request.history, | |
| horizon=request.horizon, | |
| confidence_level=request.confidence_level, | |
| ) | |
| ) | |
| except Exception as exc: # pragma: no cover | |
| raise HTTPException(status_code=500, detail=str(exc)) from exc | |
| return ForecastResponse( | |
| forecast=forecast_vals, | |
| confidence_intervals=[ | |
| ConfidenceInterval(lower=lo, upper=hi) for lo, hi in intervals | |
| ], | |
| confidence_level=request.confidence_level, | |
| alpha=alpha_used, | |
| beta=beta_used, | |
| model_type=model_type, | |
| rmse=rmse, | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Batch prediction | |
| # --------------------------------------------------------------------------- | |
| def predict_batch(request: BatchForecastRequest) -> BatchForecastResponse: | |
| """Run forecasts for multiple time series in a single request (max 100).""" | |
| results = [] | |
| for item in request.items: | |
| validate_history(item.history, min_length=settings.min_history_length) | |
| model = EWAForecastModel(alpha=item.alpha, beta=item.beta) | |
| try: | |
| forecast_vals, intervals, alpha_used, beta_used, model_type, rmse = ( | |
| model.fit_predict( | |
| history=item.history, | |
| horizon=item.horizon, | |
| confidence_level=item.confidence_level, | |
| ) | |
| ) | |
| except Exception as exc: # pragma: no cover | |
| raise HTTPException(status_code=500, detail=str(exc)) from exc | |
| results.append( | |
| ForecastResponse( | |
| forecast=forecast_vals, | |
| confidence_intervals=[ | |
| ConfidenceInterval(lower=lo, upper=hi) for lo, hi in intervals | |
| ], | |
| confidence_level=item.confidence_level, | |
| alpha=alpha_used, | |
| beta=beta_used, | |
| model_type=model_type, | |
| rmse=rmse, | |
| ) | |
| ) | |
| return BatchForecastResponse(results=results, total=len(results)) | |
| # --------------------------------------------------------------------------- | |
| # Financial Distress endpoints | |
| # --------------------------------------------------------------------------- | |
| def predict_financial_distress(request: DistressRequest) -> DistressResponse: | |
| """Predict financial distress risk for a user based on spending patterns. | |
| Takes engineered features about user spending, transaction count, and EWA usage | |
| and returns a risk score between 0 and 1 where 1 = highest risk. | |
| """ | |
| try: | |
| # Convert request to dict for internal model | |
| features = request.dict() | |
| result = predict_distress(features) | |
| return DistressResponse(**result) | |
| except Exception as exc: | |
| raise HTTPException(status_code=400, detail=str(exc)) from exc | |
| # --------------------------------------------------------------------------- | |
| # Entry point (local development) | |
| # --------------------------------------------------------------------------- | |
| if __name__ == "__main__": # pragma: no cover | |
| import uvicorn | |
| uvicorn.run( | |
| "main:app", | |
| host=settings.host, | |
| port=settings.port, | |
| reload=settings.debug, | |
| ) | |