# 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.