|
|
import gradio as gr |
|
|
import pandas as pd |
|
|
import matplotlib.pyplot as plt |
|
|
import requests |
|
|
import io |
|
|
import os |
|
|
|
|
|
|
|
|
HF_TOKEN = os.getenv("HF_TOKEN") |
|
|
MODEL = "google/timesfm-2.5-200m-pytorch" |
|
|
|
|
|
API_URL = f"https://api-inference.huggingface.co/models/{MODEL}" |
|
|
headers = {"Authorization": f"Bearer {HF_TOKEN}"} |
|
|
|
|
|
def forecast(file, date_col, value_col, steps): |
|
|
|
|
|
if file.name.endswith(".csv"): |
|
|
df = pd.read_csv(file.name) |
|
|
else: |
|
|
df = pd.read_excel(file.name) |
|
|
|
|
|
|
|
|
df[date_col] = pd.to_datetime(df[date_col]) |
|
|
df = df.sort_values(by=date_col) |
|
|
|
|
|
series = df[value_col].tolist() |
|
|
|
|
|
|
|
|
payload = { |
|
|
"inputs": series, |
|
|
"parameters": {"prediction_length": steps} |
|
|
} |
|
|
|
|
|
response = requests.post(API_URL, headers=headers, json=payload) |
|
|
|
|
|
if response.status_code != 200: |
|
|
return f"Erro na API: {response.text}", None |
|
|
|
|
|
preds = response.json().get("prediction", series[-steps:]) |
|
|
|
|
|
|
|
|
fig, ax = plt.subplots() |
|
|
ax.plot(df[date_col], df[value_col], label="Histórico") |
|
|
future_dates = pd.date_range(start=df[date_col].iloc[-1], periods=steps+1, freq="D")[1:] |
|
|
ax.plot(future_dates, preds, label="Previsão", linestyle="--") |
|
|
ax.legend() |
|
|
plt.title("📊 Previsão de Vendas (TimesFM)") |
|
|
|
|
|
buf = io.BytesIO() |
|
|
plt.savefig(buf, format="png") |
|
|
buf.seek(0) |
|
|
|
|
|
return "✅ Previsão concluída!", buf |
|
|
|
|
|
with gr.Blocks() as demo: |
|
|
gr.Markdown("## 📈 Previsão de Vendas com TimesFM (Hugging Face)") |
|
|
|
|
|
file = gr.File(label="Envie seu arquivo (.csv ou .xlsx)", file_types=[".csv", ".xlsx"]) |
|
|
date_col = gr.Textbox(label="Nome da coluna de datas") |
|
|
value_col = gr.Textbox(label="Nome da coluna de valores") |
|
|
steps = gr.Slider(1, 90, value=30, label="Quantos dias prever?") |
|
|
output_text = gr.Textbox(label="Resultado") |
|
|
output_plot = gr.Image(type="pil", label="Gráfico") |
|
|
|
|
|
btn = gr.Button("Gerar Previsão") |
|
|
btn.click(forecast, inputs=[file, date_col, value_col, steps], outputs=[output_text, output_plot]) |
|
|
|
|
|
demo.launch() |
|
|
|