Spaces:
No application file
No application file
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051import osfrom fastapi import FastAPIfrom pydantic import BaseModelimport torchimport pandas as pdfrom transformers import LagLlamaForPrediction
# Set device for the modeldevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the pre-trained modelmodel = LagLlamaForPrediction.from_pretrained("time-series-foundation-models/lag-llama", torch_dtype=torch.float32).to(device)
# Initialize the FastAPI appapp = FastAPI()
# Define the structure of the input data we expectclass 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)}app.pyAdded+51