'''import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error, mean_absolute_error import gradio as gr def train_and_evaluate(file): try: df = pd.read_csv(file.name) # Validate columns required = {"Period", "Total"} if not required.issubset(df.columns): return {"error": f"CSV must contain columns {sorted(required)}. Found: {list(df.columns)}"} # Clean numbers: remove commas, coerce errors (e.g., '.', blanks) to NaN df["Total"] = pd.to_numeric(df["Total"].astype(str).str.replace(",", ""), errors="coerce") # Parse dates and clean df["Period"] = pd.to_datetime(df["Period"], errors="coerce") df = df.dropna(subset=["Period", "Total"]).sort_values("Period") # Check length if len(df) < 12: return {"error": "Need at least 12 rows of monthly data to train and forecast."} # Simple time index feature X = np.arange(len(df)).reshape(-1, 1) y = df["Total"].values # Train/test split split = int(0.8 * len(X)) if split == 0 or split == len(X): return {"error": "Not enough rows to make a train/test split."} X_train, X_test = X[:split], X[split:] y_train, y_test = y[:split], y[split:] # Train model model = LinearRegression() model.fit(X_train, y_train) # Evaluate mse = mean_squared_error(y_test, model.predict(X_test)) # always available rmse = float(np.sqrt(mse)) # compute RMSE manually for older sklearn mae = float(mean_absolute_error(y_test, model.predict(X_test))) # Forecast next 6 months future_X = np.arange(len(X), len(X) + 6).reshape(-1, 1) future_preds = model.predict(future_X) return { "RMSE": round(rmse, 2), "MAE": round(mae, 2), "Next 6 months forecast": [round(float(x), 2) for x in future_preds] } except Exception as e: return {"error": str(e)} demo = gr.Interface( fn=train_and_evaluate, inputs=gr.File(label="Upload CSV of monthly tourists (columns: Period, Total)", file_types=[".csv"]), outputs="json", title="Tourism Prediction Service", description="Trains a regression on your monthly data, evaluates it (RMSE/MAE), and forecasts the next 6 months." ) if __name__ == "__main__": demo.launch()''' '''import gradio as gr from huggingface_hub import InferenceClient client = InferenceClient("thuml/timer-base-84m") def predict_tourism(input_text, months_ahead): # Simple interface to TIMER model response = client.text_generation(input_text, max_new_tokens=50) return response iface = gr.Interface( fn=predict_tourism, inputs=[ gr.Textbox(label="Enter last 12 months of tourism data"), gr.Number(label="Months to predict", value=6) ], outputs="text", title="Spanish Tourism Predictor" ) iface.launch()''' import pandas as pd import numpy as np import gradio as gr from statsmodels.tsa.statespace.sarimax import SARIMAX from sklearn.metrics import mean_squared_error, mean_absolute_error def train_and_forecast(file): # Load the dataset df = pd.read_csv(file.name) df['Period'] = pd.to_datetime(df['Period']) df = df.sort_values('Period') df.set_index('Period', inplace=True) y = df['Total'] # Train-test split train_size = int(len(y) * 0.8) train, test = y[:train_size], y[train_size:] # Fit SARIMA model # (p,d,q) x (P,D,Q,s) → values can be tuned, here we assume yearly seasonality (12 months) model = SARIMAX(train, order=(1,1,1), seasonal_order=(1,1,1,12)) model_fit = model.fit(disp=False) # Forecast on test set forecast = model_fit.get_forecast(steps=len(test)) forecast_mean = forecast.predicted_mean # Evaluate mse = mean_squared_error(test, forecast_mean) rmse = mse ** 0.5 mae = mean_absolute_error(test, forecast_mean) # Forecast next 6 months future_forecast = model_fit.get_forecast(steps=len(test)+6) next6 = future_forecast.predicted_mean[-6:] return { "RMSE": round(rmse), "Next 6 months forecast": [round(x) for x in next6.tolist()] } demo = gr.Interface( fn=train_and_forecast, inputs=gr.File(file_types=[".csv"], label="Upload CSV"), outputs="json", title="Monthly Tourism Forecast with SARIMA", description="Upload a CSV with columns: Period, Total. Forecasts the next 6 months using SARIMA." ) demo.launch(share=True)