File size: 7,244 Bytes
9e4bb05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# AndesAI - Deployment Guide for Hackathon

## 🎯 Plataformas Soportadas

-**Local**: `http://localhost:8000`
-**Hugging Face Spaces**: Auto-detecta desde URL
-**GitHub Pages + Backend externo**: Configurable
-**Vercel + API Backend**: Configurable

---

## 📦 Opción 1: Hugging Face Spaces (RECOMENDADO)

### Paso 1: Crear dos Spaces

1. **Frontend Space**
   - Ir a: https://huggingface.co/new-space
   - Name: `andesai-frontend`
   - License: OpenRAIL
   - Space SDK: Docker
   - (Luego subes el Dockerfile del frontend)

2. **Backend Space**
   - Ir a: https://huggingface.co/new-space
   - Name: `andesai-backend`
   - License: OpenRAIL
   - Space SDK: Docker
   - (Luego subes el Dockerfile del backend)

### Paso 2: Estructura de Carpetas en GitHub

```
andesai/
├── backend/          → Será dockerfile para HF backend space
│   ├── Dockerfile
│   ├── requirements.txt
│   └── app/
├── frontend/         → Será dockerfile para HF frontend space
│   ├── Dockerfile
│   ├── package.json
│   ├── .env.local (dev only)
│   ├── .env.production (vacío para auto-detect)
│   └── app/
└── .github/workflows/  → Auto-deploy a HF (optional)
```

### Paso 3: Frontend Dockerfile

```dockerfile
# frontend/Dockerfile (para Hugging Face)
FROM node:18-alpine

WORKDIR /app

COPY package*.json ./
RUN npm install

COPY . .

# Build para producción
RUN npm run build

# Variables de entorno (sin NEXT_PUBLIC_API_BASE = usa auto-detect)
ENV NODE_ENV=production

EXPOSE 3000

CMD ["npm", "start"]
```

### Paso 4: Backend Dockerfile (actualizado)

```dockerfile
# backend/Dockerfile (para Hugging Face)
FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY app/ app/
COPY *.py ./

ENV PYTHONUNBUFFERED=1

# Puerto debe ser 7860 para Hugging Face
EXPOSE 7860

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
```

### Paso 5: Variables de Entorno en HF

En el **Backend Space** de Hugging Face:
1. Ve a "Settings" → "Repository secrets"
2. Agrega:
   MERCADO_PUBLICO_TICKET=YOUR_TICKET_HERE
   GEMINI_API_KEY=YOUR_GEMINI_KEY_HERE
   DATABASE_URL=sqlite:///./andesops.db
   GROQ_API_KEY=YOUR_GROQ_KEY_HERE

### Cómo funciona el Auto-Detect

Una vez deployed en Hugging Face:

```javascript
// El código detecta automáticamente:
// Frontend URL: https://username-andesai-frontend.hf.space
// Y genera Backend URL: https://username-andesai-backend.hf.space

// En frontend/lib/api.ts:
if (window.location.hostname.includes('huggingface.co')) {
  const spaceName = window.location.pathname.split('/')[2]; // 'username/andesai-frontend'
  return `https://${spaceName}-backend.hf.space`; // Auto-construye URL del backend
}
```

---

## 🚀 Opción 2: GitHub + Deploy Backend a Fly.io (o similar)

### Paso 1: Deploy Backend a Fly.io

```bash
# Instalar Fly CLI
# https://fly.io/docs/getting-started/installing-flyctl/

cd backend
fly launch
# Llena las preguntas, selecciona app name: "andesai-backend"

# Deploy
fly deploy
# URL resultará en: https://andesai-backend.fly.dev
```

### Paso 2: GitHub Pages para Frontend

```bash
# Editar frontend/.env.production
NEXT_PUBLIC_API_BASE=https://andesai-backend.fly.dev
```

### Paso 3: GitHub Actions para Auto-Deploy

Crear archivo: `.github/workflows/deploy.yml`

```yaml
name: Deploy Frontend

on:
  push:
    branches: [main]
    paths:
      - 'frontend/**'

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install & Build
        working-directory: ./frontend
        run: |
          npm install
          npm run build
      
      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./frontend/.next/out
```

---

## 🔐 Secretos en GitHub

Para que funcione en CI/CD:

1. Ve a: `Settings``Secrets and variables``Actions`
2. Agrega variables (no necesitas secretos para .env públicos):
   ```
   NEXT_PUBLIC_API_BASE=https://andesai-backend.fly.dev
   ```

---

## ✅ Configuración para Hackathon (RECOMENDADO)

### Opción más fácil: Hugging Face Spaces

**Ventajas:**
- ✅ Todo en un solo lugar
- ✅ Auto-detecta URLs
- ✅ Muy fácil de compartir
- ✅ Free tier generoso
- ✅ Sin necesidad de CI/CD complejo

**Pasos:**
1. Crea 2 Spaces en HF (frontend + backend)
2. Sube Dockerfiles (usa los que creé arriba)
3. Agrega variables de entorno en backend space
4. ¡Listo! Frontend auto-detecta backend

### URL Final
```
Frontend: https://tuusername-andesai-frontend.hf.space
Backend: https://tuusername-andesai-backend.hf.space
```

El código detecta automáticamente que está en HF y conecta frontend → backend ✨

---

## 🧪 Test Local Antes de Deployar

```bash
# 1. Verificar que .env.local está correcto
cat frontend/.env.local
# Debe mostrar: NEXT_PUBLIC_API_BASE=http://localhost:8000

# 2. Iniciar backend
cd backend
python -m uvicorn app.main:app --reload --port 8000

# 3. En otra terminal, iniciar frontend
cd frontend
npm run dev

# 4. Abre http://localhost:3000 y verifica que funciona
```

---

## 📋 Checklist Final para Hackathon

- [ ] Frontend funciona localmente
- [ ] Backend responde a `/api/health`
- [ ] OC y Tenders traen datos
- [ ] Dockerfiles están listos
- [ ] HF Spaces creados (o Fly.io configurado)
- [ ] Variables de entorno agregadas
- [ ] GitHub repo actualizado
- [ ] URLs compartidas con jurado

---

## 🆘 Si algo falla

### Error: "Connection Error" en Spaces

```bash
# Verifica que el backend space está running:
# 1. Ve a tu backend space
# 2. Mira el "App status" (debe ser green)
# 3. Haz click en el link para verificar que responde

# El frontend automáticamente reintentar después de 5 segundos
```

### Error: "Invalid API URL"

```javascript
// Verifica en DevTools Console (F12):
console.log(window.location.hostname);
// Debe mostrar: username-andesai-frontend.hf.space
// o: localhost (en desarrollo)

// Verifica que API_BASE se detectó correctamente:
// Debe ver mensaje: [API] Using API base: https://...
```

### OC no trae datos

```bash
# Verifica que el ticket de Mercado Público es válido
curl "https://api.mercadopublico.cl/servicios/v1/publico/ordenesdecompra.json?ticket=YOUR_TICKET&fecha=$(date +%d%m%Y)"

# Si devuelve 500 = Sin datos disponibles (normal)
# Si devuelve 401 = Ticket inválido (error)
```

---

## 📞 Deployment Checklist

Para la hackathon, necesitas:

```markdown
✅ **GitHub Repo**
   - Frontend Code ✓
   - Backend Code ✓
   - Dockerfiles ✓
   - README con instrucciones ✓

✅ **Hugging Face Spaces** (Recomendado)
   - andesai-frontend space ✓
   - andesai-backend space ✓
   - Variables de entorno configuradas ✓
   - Ambos spaces running ✓

✅ **Compartir con Jurado**
   - Link a Frontend Space
   - Link a GitHub Repo
   - Link a Backend Space (opcional, mostrar en About)
   - README con "How to Use"
```

¡Listo! El auto-detect hace que funcione automáticamente en cualquier plataforma.