File size: 998 Bytes
f4091fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
from prophet import Prophet
import json

def forecast_api(json_data, periods):
    # 1. Parse Data
    try:
        data = json.loads(json_data)
        df = pd.DataFrame(data)

        # 2. Train Prophet (Runs on Hugging Face Server, not your machine)
        m = Prophet()
        m.fit(df)

        # 3. Predict
        future = m.make_future_dataframe(periods=int(periods))
        forecast = m.predict(future)

        # 4. Return result as JSON
        result = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(int(periods))
        # Convert timestamps to string for JSON serialization
        result['ds'] = result['ds'].astype(str)
        return result.to_json(orient='records')

    except Exception as e:
        return json.dumps({"error": str(e)})

# Create the API interface
demo = gr.Interface(
    fn=forecast_api,
    inputs=[gr.Textbox(label="JSON Data"), gr.Number(label="Periods", value=30)],
    outputs="json"
)

demo.launch()