Spaces:
No application file
No application file
File size: 1,703 Bytes
c4addde | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 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)} |