File size: 5,664 Bytes
36a7e49
69b5a3f
 
36a7e49
69b5a3f
36a7e49
69b5a3f
36a7e49
69b5a3f
36a7e49
 
69b5a3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
---
title: Chronos2 Excel Forecasting API
emoji: 📊
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
pinned: false
license: mit
---

# 📊 Chronos2 Excel Forecasting API

API de pronósticos con IA para Microsoft Excel usando [Amazon Chronos-2](https://huggingface.co/amazon/chronos-t5-large).

🔗 **Úsalo directamente desde Excel** con nuestro Office Add-in

## 🚀 Características

-**Pronósticos univariados**: Series temporales simples
-**Detección de anomalías**: Identifica valores atípicos automáticamente
-**Backtesting**: Valida la precisión de tus modelos
-**API REST con FastAPI**: Fácil integración
-**Documentación interactiva**: Swagger UI incluido

## 📖 Documentación

Accede a la documentación interactiva:
- **Swagger UI**: `/docs`
- **ReDoc**: `/redoc`
- **Health Check**: `/health`

## 🧪 Prueba Rápida

### Pronóstico Simple

```bash
curl -X POST https://YOUR-USERNAME-chronos2-excel-forecasting-api.hf.space/forecast_univariate \
  -H "Content-Type: application/json" \
  -d '{
    "series": {"values": [100, 102, 105, 103, 108, 112, 115]},
    "prediction_length": 3,
    "freq": "D"
  }'
```

**Respuesta esperada:**
```json
{
  "timestamps": ["t+1", "t+2", "t+3"],
  "median": [117.5, 119.2, 121.0],
  "quantiles": {
    "0.1": [112.3, 113.8, 115.5],
    "0.5": [117.5, 119.2, 121.0],
    "0.9": [122.7, 124.6, 126.5]
  }
}
```

### Detección de Anomalías

```bash
curl -X POST https://YOUR-USERNAME-chronos2-excel-forecasting-api.hf.space/detect_anomalies \
  -H "Content-Type: application/json" \
  -d '{
    "context": {"values": [100, 102, 105, 103, 108]},
    "recent_observed": [107, 200, 106],
    "prediction_length": 3
  }'
```

### Backtesting

```bash
curl -X POST https://YOUR-USERNAME-chronos2-excel-forecasting-api.hf.space/backtest_simple \
  -H "Content-Type: application/json" \
  -d '{
    "series": {"values": [100, 102, 105, 103, 108, 112, 115, 118, 120, 122, 125, 128]},
    "prediction_length": 7,
    "test_length": 4
  }'
```

## 🔗 Endpoints Disponibles

| Endpoint | Método | Descripción |
|----------|--------|-------------|
| `/` | GET | Información de la API |
| `/health` | GET | Health check del servicio |
| `/docs` | GET | Documentación Swagger |
| `/forecast_univariate` | POST | Pronóstico de serie simple |
| `/detect_anomalies` | POST | Detectar valores atípicos |
| `/backtest_simple` | POST | Validar precisión del modelo |
| `/simple_forecast` | POST | Pronóstico rápido (testing) |

## 💻 Uso con Excel

Este API funciona perfectamente con nuestro **Office Add-in para Excel**:

1. Descarga el Add-in desde [GitHub](https://github.com/tu-usuario/chronos2-server)
2. Configura la URL de este Space en el Add-in
3. ¡Realiza pronósticos directamente desde tus hojas de cálculo!

### Ejemplo en Excel

```javascript
// En el Excel Add-in, configura:
const API_BASE_URL = 'https://YOUR-USERNAME-chronos2-excel-forecasting-api.hf.space';
```

## 🛠️ Tecnologías

- **Modelo**: [Amazon Chronos-2 T5-Large](https://huggingface.co/amazon/chronos-t5-large)
- **Framework**: [FastAPI](https://fastapi.tiangolo.com/)
- **Inference**: [Hugging Face Inference API](https://huggingface.co/docs/api-inference)
- **Deployment**: Hugging Face Spaces (Docker)

## 📊 Casos de Uso

- 📈 **Ventas**: Predice demanda futura de productos
- 💰 **Finanzas**: Proyecta ingresos y gastos
- 📦 **Inventario**: Optimiza stock y reposición
- 🌡️ **Sensores**: Anticipa valores de sensores IoT
- 🏪 **Retail**: Planifica recursos y personal

## ⚙️ Configuración

### Variables de Entorno

Para desplegar tu propia instancia, configura:

- `HF_TOKEN`: Tu token de Hugging Face (requerido)
- `CHRONOS_MODEL_ID`: ID del modelo (default: `amazon/chronos-t5-large`)
- `PORT`: Puerto del servidor (default: `7860`)

### Crear tu propio Space

1. Fork este repositorio
2. Crea un nuevo Space en Hugging Face
3. Selecciona **Docker** como SDK
4. Conecta tu repositorio
5. Configura `HF_TOKEN` en los Secrets del Space
6. ¡Listo!

## 🔒 Seguridad

- ✅ CORS configurado para orígenes permitidos
- ✅ Validación de entrada con Pydantic
- ✅ Rate limiting en HuggingFace Inference API
- ✅ Timeouts configurados para evitar bloqueos

## 📚 Recursos

- [Documentación de Chronos-2](https://huggingface.co/amazon/chronos-t5-large)
- [API de HuggingFace Inference](https://huggingface.co/docs/api-inference)
- [FastAPI Docs](https://fastapi.tiangolo.com/)
- [Tutorial de Office Add-ins](https://docs.microsoft.com/en-us/office/dev/add-ins/)

## 🐛 Solución de Problemas

### "Model is loading"

La primera request puede tardar 30-60 segundos mientras el modelo se carga. Reintenta después.

### "HF_TOKEN not configured"

Asegúrate de configurar `HF_TOKEN` en los Secrets de tu Space.

### Errores de timeout

El modelo puede estar frío. Espera unos segundos y reintenta.

## 📝 Licencia

MIT License - Ver [LICENSE](LICENSE) para más detalles.

## 🤝 Contribuir

¿Quieres mejorar este proyecto?

1. Fork el repositorio
2. Crea una branch para tu feature (`git checkout -b feature/amazing`)
3. Commit tus cambios (`git commit -m 'Add amazing feature'`)
4. Push a la branch (`git push origin feature/amazing`)
5. Abre un Pull Request

## 📧 Contacto

¿Preguntas o sugerencias? Abre un [issue en GitHub](https://github.com/tu-usuario/chronos2-server/issues).

---

**Desarrollado con ❤️ usando [Chronos-2](https://huggingface.co/amazon/chronos-t5-large) y [FastAPI](https://fastapi.tiangolo.com/)**

🌟 Si te gusta este proyecto, ¡dale una estrella en [GitHub](https://github.com/tu-usuario/chronos2-server)!