Spaces:
No application file

eFama's picture
Create app.py
c4addde verified
Raw History Blame Contribute Delete
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
@app.get("/")
def read_root():
return {"message": "Lag-Llama Prediction API is running."}
@app.post("/predict/")
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)}