Spaces:
No application file
No application file
Download app.py from eFama/efama-forecast-api: direct link, hf CLI and curl.
- Browser
- Download file 1.7 kB
-
https://huggingface.co/spaces/eFama/efama-forecast-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/eFama/efama-forecast-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/eFama/efama-forecast-api/resolve/main/app.py
1.7 kB
| import os | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import torch | |
| import pandas as pd | |
| from transformers import LagLlamaForPrediction | |
| # Set device for the model | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| # Load the pre-trained model | |
| model = LagLlamaForPrediction.from_pretrained("time-series-foundation-models/lag-llama", torch_dtype=torch.float32).to(device) | |
| # Initialize the FastAPI app | |
| app = FastAPI() | |
| # Define the structure of the input data we expect | |
| class PredictionInput(BaseModel): | |
| past_values: list[float] | |
| prediction_length: int | |
| def read_root(): | |
| return {"message": "Lag-Llama Prediction API is running."} | |
| def predict(data: PredictionInput): | |
| try: | |
| # Convert input list to a pandas DataFrame, which the model expects | |
| past_df = pd.DataFrame(data.past_values, columns=["value"]) | |
| # Create a date range for the time series | |
| start_date = pd.Timestamp.now() - pd.DateOffset(days=len(data.past_values) - 1) | |
| date_range = pd.date_range(start=start_date, periods=len(data.past_values), freq='D') | |
| past_df['date'] = date_range | |
| past_df = past_df.set_index('date') | |
| # Prepare the time series data for the model | |
| time_series = [ | |
| past_df.to_period('D')['value'] | |
| ] | |
| # Get the model prediction | |
| forecasts = model.predict(time_series, prediction_length=data.prediction_length) | |
| # The model returns a list of forecasts, we take the first one | |
| forecast_values = forecasts[0].mean.tolist() | |
| return {"prediction": forecast_values} | |
| except Exception as e: | |
| return {"error": str(e)} |