Spaces:
Sleeping
Sleeping
Randy Mustelier Rivero commited on
Commit ·
c4d0b23
1
Parent(s): e597ad1
feat: completar Fase 2 parcial + Gradio frontend + fix 3 tests + propuesta Cuba
Browse files- Fix 3 tests: test_circular_rotation flaky, _to_float bugs (EU decimal, texto residual)
- 118/118 tests pasando
- Nuevo frontend Gradio con busqueda multi-adaptador, lista de adaptadores y estado
- Nuevo endpoint POST /api/search con normalizacion a schema canonico
- Nuevo ResultNormalizer + CanonicalItem para normalizacion multi-fuente
- Nuevo modulo_1_servicio/ui/ con Gradio montado sobre FastAPI
- app.py entry point para HF Spaces con Gradio
- Soporte de canonical_map en adapters YAML y modelos
- Admin client con list_adapters(), list_verticals(), search()
- GUI QML con pagina de busqueda por vertical
- Archivos de persistencia: MEMORIA.md, PROPUESTA.md
- Actualizadas dependencias: gradio, pyproject.toml, requirements-hf.txt
- .gitignore +3 -0
- MEMORIA.md +180 -0
- PROPUESTA.md +322 -0
- adapters/example_httpbin.yaml +5 -0
- app.py +26 -0
- modulo_1_servicio/api/routes_search.py +236 -0
- modulo_1_servicio/main.py +2 -0
- modulo_1_servicio/requirements-hf.txt +1 -0
- modulo_1_servicio/scraping/adapters/models.py +8 -0
- modulo_1_servicio/scraping/normalizer.py +187 -0
- modulo_1_servicio/ui/__init__.py +0 -0
- modulo_1_servicio/ui/gradio_app.py +315 -0
- modulo_2_admin/core/client.py +65 -0
- modulo_2_admin/ui/main.py +65 -0
- modulo_2_admin/ui/qml/main.qml +396 -5
- pyproject.toml +2 -0
- tests/modulo_1/test_anti_scraping.py +5 -6
- tests/modulo_1/test_normalizer.py +194 -0
.gitignore
CHANGED
|
@@ -47,3 +47,6 @@ ms-playwright/
|
|
| 47 |
# Config with secrets
|
| 48 |
.env
|
| 49 |
*.env.local
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# Config with secrets
|
| 48 |
.env
|
| 49 |
*.env.local
|
| 50 |
+
|
| 51 |
+
# Screenshots / assets not for commit
|
| 52 |
+
google\ app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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MEMORIA del Proyecto — ScrapperGenérico
|
| 2 |
+
|
| 3 |
+
> Archivo de persistencia local (reemplaza Engram). Se actualiza al final de cada sesión.
|
| 4 |
+
> **NO ELIMINAR**. Contiene el contexto de sesiones anteriores.
|
| 5 |
+
|
| 6 |
+
---
|
| 7 |
+
|
| 8 |
+
## Última actualización: 2026-07-23 (Sesión 6 - Cierre)
|
| 9 |
+
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
## 🧠 Contexto del Proyecto
|
| 13 |
+
|
| 14 |
+
**Visión final**: Sistema B2B SaaS de scraping genérico multi-vertical. Cualquier persona busca productos/servicios en múltiples sitios simultáneamente con filtros. Escalar a modelo de suscripción para agentes inmobiliarios, concesionarias, comercios.
|
| 15 |
+
|
| 16 |
+
**Stack actual**: Python 3.12, FastAPI, httpx, BeautifulSoup, PySide6+QML (desktop), Pydantic, pytest, SQLite.
|
| 17 |
+
|
| 18 |
+
**Repos**: `https://github.com/randoloc/Sistema-de-Scraping-Parametrizado`
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
## 📐 Arquitectura Actual (3 Módulos)
|
| 23 |
+
|
| 24 |
+
```
|
| 25 |
+
modulo_1_servicio/ → API FastAPI (scraping engine, adaptadores, entregas)
|
| 26 |
+
modulo_2_admin/ → GUI desktop PySide6+QML (para administración local)
|
| 27 |
+
modulo_3_resultados/ → Templates de entrega (email, web, WhatsApp)
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
**Flujo**: Usuario → Admin GUI (M2) → API (M1) → Scraping Engine → Adapters YAML → Extractors → Result → Delivery
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## 📋 Historial de Sesiones
|
| 35 |
+
|
| 36 |
+
### Sesión 6 — 2026-07-23 (Cierre): Tests arreglados + Frontend Gradio
|
| 37 |
+
|
| 38 |
+
**Qué se hizo**:
|
| 39 |
+
1. ✅ Arreglados 3 tests fallando (118/118):
|
| 40 |
+
- `test_circular_rotation` — flaky por índice aleatorio (ahora no asume índice 0)
|
| 41 |
+
- `_to_float("€ 50,00")` — bug de coma decimal europea (ahora soporta formatos US y EU)
|
| 42 |
+
- `_to_float("$ 25,000 MXN")` — bug de texto residual (regex como último recurso)
|
| 43 |
+
2. ✅ Creado `modulo_1_servicio/ui/gradio_app.py` — Frontend Gradio completo:
|
| 44 |
+
- Tab "🔍 Buscar": búsqueda multi-adaptador con tabla de resultados
|
| 45 |
+
- Tab "📋 Adaptadores": lista todos los adaptadores cargados
|
| 46 |
+
- Tab "⚙️ Estado": información del servicio + ayuda
|
| 47 |
+
- Se conecta directamente con el engine interno (sin HTTP overhead)
|
| 48 |
+
3. ✅ Creado `app.py` — Entry point HF Spaces que monta Gradio sobre FastAPI
|
| 49 |
+
4. ✅ Actualizadas dependencias: Gradio 6.20.0 instalado
|
| 50 |
+
5. ✅ Actualizados `.gitignore`, `pyproject.toml`, `requirements-hf.txt`
|
| 51 |
+
6. ✅ Creados archivos de persistencia: `MEMORIA.md`, `PROPUESTA.md`
|
| 52 |
+
|
| 53 |
+
**Archivos creados**: 4 nuevos
|
| 54 |
+
- `app.py` — Entry point HF Spaces
|
| 55 |
+
- `modulo_1_servicio/ui/__init__.py`
|
| 56 |
+
- `modulo_1_servicio/ui/gradio_app.py` — Frontend Gradio
|
| 57 |
+
- `PROPUESTA.md` — Propuesta estratégica Cuba
|
| 58 |
+
|
| 59 |
+
**Archivos modificados**: 6
|
| 60 |
+
- `modulo_1_servicio/scraping/normalizer.py` — Fix _to_float
|
| 61 |
+
- `tests/modulo_1/test_anti_scraping.py` — Fix test flaky
|
| 62 |
+
- `pyproject.toml` — +gradio dep
|
| 63 |
+
- `modulo_1_servicio/requirements-hf.txt` — +gradio dep
|
| 64 |
+
- `.gitignore` — +google app password.png
|
| 65 |
+
- `MEMORIA.md` — Esta actualización
|
| 66 |
+
|
| 67 |
+
**Tests**: 118/118 pasando ✅
|
| 68 |
+
|
| 69 |
+
**Pendiente para próxima sesión**:
|
| 70 |
+
- [ ] Commitear el progreso actual
|
| 71 |
+
- [ ] Crear adapter real para Revolico (inspeccionar HTML)
|
| 72 |
+
- [ ] Crear adapter real para Porlalivre
|
| 73 |
+
- [ ] Integrar Telegram Bot (python-telegram-bot)
|
| 74 |
+
- [ ] Escribir tests para `routes_search.py`
|
| 75 |
+
- [ ] Desplegar en HF Spaces y probar
|
| 76 |
+
|
| 77 |
+
---
|
| 78 |
+
|
| 79 |
+
### Sesión 5 — 2026-07-23: Reevaluación estratégica completa
|
| 80 |
+
|
| 81 |
+
**Decisión CRÍTICA**: El usuario está en Cuba, sin acceso a USD ni tarjetas de crédito. **TODO el stack debe ser 100% gratuito.** No Stripe, no AWS, no Railway, no nada que requiera tarjeta.
|
| 82 |
+
|
| 83 |
+
**Nuevo target**:
|
| 84 |
+
1. **Agentes inmobiliarios en Cuba** (corredores de casas) — vertical real_estate
|
| 85 |
+
2. **Compradores/vendedores mayoristas en Cuba** — vertical wholesale
|
| 86 |
+
3. Plataformas objetivo: Revolico, Porlalivre, Telegram channels, Facebook Marketplace Cuba
|
| 87 |
+
|
| 88 |
+
**Stack gratuito redefinido**:
|
| 89 |
+
- Hosting: HF Spaces (FastAPI + Gradio) + GitHub Pages (frontend estático)
|
| 90 |
+
- Prod DB: SQLite (bien para escala pequeña-media)
|
| 91 |
+
- Bot/entrega: Telegram API (GRATIS, sin límites, sin tarjeta)
|
| 92 |
+
- Scraping: BeautifulSoup + httpx (sin Playwright por RAM limitada)
|
| 93 |
+
- CI/CD: GitHub Actions
|
| 94 |
+
- Dominio: subdominio de HF Spaces (gratis) o Freenom si funciona
|
| 95 |
+
|
| 96 |
+
**Problemas detectados**:
|
| 97 |
+
- 3 tests fallando (1 flaky, 2 bugs en `_to_float`)
|
| 98 |
+
- Fase 2 incompleta y sin commitear
|
| 99 |
+
- PySide6 no sirve para el público objetivo (no pueden instalar apps)
|
| 100 |
+
- WhatsApp API requiere Meta Business Account (no accesible desde Cuba)
|
| 101 |
+
- Playwright requiere muchos recursos (inviable en HF gratis)
|
| 102 |
+
|
| 103 |
+
---
|
| 104 |
+
|
| 105 |
+
### Sesión 4 — 2026-06-02: Fase 1 Completa
|
| 106 |
+
|
| 107 |
+
✅ Fase 1 completa: URL normalizer, adapters YAML, anti-scraping, endpoint, 36 tests
|
| 108 |
+
✅ Suite: 96 tests, 0 fallas (en ese momento)
|
| 109 |
+
✅ Email delivery configurado con Gmail SMTP
|
| 110 |
+
✅ QML UI corregida (padding bugs)
|
| 111 |
+
✅ PythonBridge funcionando
|
| 112 |
+
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
### Sesión 3 — 2026-06-02: Email + Fix QML
|
| 116 |
+
|
| 117 |
+
✅ Email delivery vía .env con Gmail SMTP
|
| 118 |
+
✅ Bug padding QML corregido (Rectangle → Pane)
|
| 119 |
+
✅ Prueba completa exitosa: scraping httpbin → email enviado
|
| 120 |
+
|
| 121 |
+
---
|
| 122 |
+
|
| 123 |
+
### Sesiones 1-2 — App Admin + Arranque
|
| 124 |
+
|
| 125 |
+
✅ PySide6-Essentials instalado
|
| 126 |
+
✅ PythonBridge + QML
|
| 127 |
+
✅ 8 tests de integración
|
| 128 |
+
✅ README creado
|
| 129 |
+
✅ GitHub repo creado
|
| 130 |
+
|
| 131 |
+
---
|
| 132 |
+
|
| 133 |
+
## 🐛 Bugs Conocidos
|
| 134 |
+
|
| 135 |
+
| # | Descripción | Archivo | Prioridad |
|
| 136 |
+
|---|-------------|---------|-----------|
|
| 137 |
+
| 1 | `test_circular_rotation` flaky — `UARotator` arranca con índice aleatorio, el test asume índice 0 | `test_anti_scraping.py:38` | 🟡 Medio |
|
| 138 |
+
| 2 | `_to_float` no maneja coma como decimal europea (`€ 50,00` → 5000.0) | `normalizer.py:73` | 🟢 Fácil |
|
| 139 |
+
| 3 | `_to_float` no limpia texto residual (`$ 25,000 MXN` → None) | `normalizer.py:73` | 🟢 Fácil |
|
| 140 |
+
|
| 141 |
+
---
|
| 142 |
+
|
| 143 |
+
## 📁 Archivos Estratégicos
|
| 144 |
+
|
| 145 |
+
| Archivo | Propósito |
|
| 146 |
+
|---------|-----------|
|
| 147 |
+
| `MEMORIA.md` | **Este archivo** — memoria persistente del proyecto |
|
| 148 |
+
| `CHECKPOINT.md` | Estado técnico detallado + instrucciones de prueba |
|
| 149 |
+
| `PROPUESTA.md` | Propuestas de producto y roadmap |
|
| 150 |
+
| `openspec/` | SDD (Spec-Driven Development) — cambios formales |
|
| 151 |
+
|
| 152 |
+
---
|
| 153 |
+
|
| 154 |
+
## 🚧 WIP: Cambios sin commitear (Fase 2 parcial)
|
| 155 |
+
|
| 156 |
+
**Nuevos:**
|
| 157 |
+
- `modulo_1_servicio/api/routes_search.py` — Endpoint `POST /api/search`
|
| 158 |
+
- `modulo_1_servicio/scraping/normalizer.py` — ResultNormalizer + CanonicalItem
|
| 159 |
+
- `tests/modulo_1/test_normalizer.py` — 19 tests (2 fallan por bugs en `_to_float`)
|
| 160 |
+
|
| 161 |
+
**Modificados:**
|
| 162 |
+
- `adapters/example_httpbin.yaml` — +canonical_map
|
| 163 |
+
- `modulo_1_servicio/main.py` — +search_router
|
| 164 |
+
- `modulo_1_servicio/scraping/adapters/models.py` — +canonical_map field
|
| 165 |
+
- `modulo_2_admin/core/client.py` — +search methods
|
| 166 |
+
- `modulo_2_admin/ui/main.py` — +search bridge
|
| 167 |
+
- `modulo_2_admin/ui/qml/main.qml` — +UI búsqueda
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## ⚙️ Cómo Correr Tests
|
| 172 |
+
|
| 173 |
+
```powershell
|
| 174 |
+
# Todos los tests
|
| 175 |
+
python -m pytest tests/ -v --tb=short
|
| 176 |
+
|
| 177 |
+
# Tests específicos
|
| 178 |
+
python -m pytest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
|
|
|
| 1 |
+
# 🚀 Propuesta Estratégica — ScrapperGenérico
|
| 2 |
+
|
| 3 |
+
> **Contexto**: Cuba, sin USD, sin tarjetas de crédito, sin acceso a servicios de pago.
|
| 4 |
+
> **Stack 100% gratuito** requerido.
|
| 5 |
+
> **Target inicial**: Corredores de casas (Cuba) + Compra/venta mayorista (Cuba)
|
| 6 |
+
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
## 📦 Primera propuesta: SISTEMA COMPLETO GRATUITO
|
| 10 |
+
|
| 11 |
+
### Stack Tecnológico 100% Gratuito
|
| 12 |
+
|
| 13 |
+
| Componente | Tecnología | Por qué |
|
| 14 |
+
|------------|-----------|---------|
|
| 15 |
+
| **Backend API** | FastAPI en Hugging Face Spaces (CPU gratis) | Ya lo tenés, funciona, 0 USD |
|
| 16 |
+
| **Frontend web** | Gradio (embebido en HF Spaces) | Mismo deploy, 0 USD, interfaz limpia |
|
| 17 |
+
| **Base de datos** | SQLite | Ya lo usás, 0 USD, funciona para cientos de usuarios |
|
| 18 |
+
| **Bot de mensajería** | Telegram Bot API | **GRATIS TOTAL**, sin límites, sin tarjeta, sin verificación |
|
| 19 |
+
| **Scraping** | httpx + BeautifulSoup + requests | 0 USD, corren en CPUs |
|
| 20 |
+
| **Calendario / Tareas** | GitHub Actions + cron | 0 USD para repos públicos |
|
| 21 |
+
| **Frontend docs / landing** | GitHub Pages | 0 USD, HTML estático |
|
| 22 |
+
| **Dominio** | `mitu.hf.space` | Gratis, o Freenom .tk si está disponible |
|
| 23 |
+
| **CI/CD** | GitHub Actions | 0 USD |
|
| 24 |
+
| **Email** | Ya tenés Gmail SMTP + dotenv | 0 USD |
|
| 25 |
+
|
| 26 |
+
### Lo que NO podemos usar (requieren tarjeta)
|
| 27 |
+
|
| 28 |
+
| Servicio | Razón |
|
| 29 |
+
|----------|-------|
|
| 30 |
+
| ❌ Railway / Fly.io / Render | Requieren tarjeta aunque tengan free tier |
|
| 31 |
+
| ❌ AWS / Google Cloud / Azure | Requieren tarjeta |
|
| 32 |
+
| ❌ Stripe / Paddle / MercadoPago | Requieren cuenta bancaria/comercio |
|
| 33 |
+
| ❌ OpenAI / Claude API | Requieren tarjeta (aunque sean $5) |
|
| 34 |
+
| ❌ WhatsApp Business API | Requiere Meta Business Account (complicado desde Cuba) |
|
| 35 |
+
| ❌ Playwright | Consume mucha RAM (HF Spaces gratis: 16GB — a veces alcanza, pero es riesgoso) |
|
| 36 |
+
| ❌ Supabase / MongoDB Atlas free | Algunos no requieren tarjeta, pero mejor no depender |
|
| 37 |
+
|
| 38 |
+
---
|
| 39 |
+
|
| 40 |
+
## 🎯 Target Vertical #1: CORREDORES DE CASAS (Cuba)
|
| 41 |
+
|
| 42 |
+
### El problema real
|
| 43 |
+
|
| 44 |
+
En Cuba no existe MLS (Multiple Listing Service). Los corredores usan:
|
| 45 |
+
- **Revolico** (classificados, dueños publican directo)
|
| 46 |
+
- **Porlalivre** (similar)
|
| 47 |
+
- **Telegram** (canales inmensos de ofertas, ej: "Casas en Venta La Habana")
|
| 48 |
+
- **Facebook Marketplace / Grupos de Facebook**
|
| 49 |
+
- **WhatsApp** (cadenas, grupos)
|
| 50 |
+
|
| 51 |
+
**El dolor**: Un corredor tiene que revisar 5+ fuentes manualmente, todos los días, para no perder una oportunidad. Cuando aparece una buena propiedad, en minutos ya tiene 20 interesados.
|
| 52 |
+
|
| 53 |
+
### Solución
|
| 54 |
+
|
| 55 |
+
Un **bot de Telegram** (gratis, funciona en Cuba, no consume datos pesados):
|
| 56 |
+
|
| 57 |
+
```
|
| 58 |
+
1. Usuario escribe al bot: "casas 3 hab La Habana < 30000 USD"
|
| 59 |
+
2. El bot busca en Revolico + Porlalivre + canales de Telegram
|
| 60 |
+
3. Devuelve resultados unificados:
|
| 61 |
+
|
| 62 |
+
🏠 *Resultados para: casas 3 hab La Habana*
|
| 63 |
+
|
| 64 |
+
📍 *Revolico* — 3 resultados nuevos
|
| 65 |
+
1. Casa 3 hab, Vedado, $28,000 → revoli.co/abc
|
| 66 |
+
2. Casa 3 hab, Miramar, $25,000 → revoli.co/def
|
| 67 |
+
|
| 68 |
+
📍 *Porlalivre* — 2 resultados nuevos
|
| 69 |
+
1. Casa 3 hab, Centro Habana, $22,000 → pl.co/ghi
|
| 70 |
+
|
| 71 |
+
4. Bot pregunta: "¿Querés que te avise cuando aparezcan nuevas?"
|
| 72 |
+
5. Usuario dice "Sí" → el bot monitorea y notifica
|
| 73 |
+
```
|
| 74 |
+
|
| 75 |
+
### Por qué Telegram y NO WhatsApp
|
| 76 |
+
|
| 77 |
+
| Aspecto | Telegram | WhatsApp |
|
| 78 |
+
|---------|----------|----------|
|
| 79 |
+
| **Costo** | 100% GRATIS, ilimitado | Requiere Meta Business Account |
|
| 80 |
+
| **En Cuba** | ✅ Funciona bien | ✅ Funciona |
|
| 81 |
+
| **Bot API** | ✅ Pública, documentada, simple | ❌ Webhook complejo, requiere servidor verificado |
|
| 82 |
+
| **Notificaciones** | ✅ Push ilimitadas | ❌ Solo service window (24h) o templates pagados |
|
| 83 |
+
| **Archivos** | ✅ Fotos, docs, hasta 2GB | ❌ Limitado |
|
| 84 |
+
| **Canales públicos** | ✅ Podés scrapear canales | ❌ No |
|
| 85 |
+
| **Programación** | ✅ python-telegram-bot, simple | ❌ httpx + Meta Cloud API, engorroso |
|
| 86 |
+
|
| 87 |
+
### ¿Qué scrapeamos?
|
| 88 |
+
|
| 89 |
+
| Fuente | Método | Prioridad |
|
| 90 |
+
|--------|--------|-----------|
|
| 91 |
+
| **Revolico** — `revolico.com` | HTTP directo + BeautifulSoup | 🔴 Alta |
|
| 92 |
+
| **Porlalivre** — `porlalivre.com` | HTTP directo + BeautifulSoup | 🔴 Alta |
|
| 93 |
+
| **Canales de Telegram** | `Telegram API` scraping (telethon) o entrada manual | 🟡 Media |
|
| 94 |
+
| **Facebook Marketplace Cuba** | Difícil (requiere login, JS) | 🟢 Baja (Fase 2) |
|
| 95 |
+
|
| 96 |
+
### Monetización (a futuro, cuando haya acceso a pagos)
|
| 97 |
+
|
| 98 |
+
Mientras tanto, **MVP gratuito que genere valor real**:
|
| 99 |
+
- Corredor usa el bot GRATIS
|
| 100 |
+
- El bot lleva conteo de búsquedas
|
| 101 |
+
- Cuando tengas acceso a pagos (MercadoPago Cuba? Transfermovil?): modelo freemium
|
| 102 |
+
- Mientras tanto: el valor está en **tener la base de usuarios y los datos**
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
## 🎯 Target Vertical #2: COMPRA/VENTA MAYORISTA (Cuba)
|
| 107 |
+
|
| 108 |
+
### El problema real
|
| 109 |
+
|
| 110 |
+
En Cuba no hay un "MercadoLibre" funcional para mayoristas. La gente compra/vende por:
|
| 111 |
+
- **Revolico** (categorías de producto)
|
| 112 |
+
- **Grupos de WhatsApp/Telegram** de compra-venta
|
| 113 |
+
- **Facebook Marketplace**
|
| 114 |
+
- **Porlalivre** (también tiene productos)
|
| 115 |
+
|
| 116 |
+
**El dolor**: Un revendedor que busca "zapatos talla 42 al por mayor" tiene que revisar decenas de fuentes. Los precios varían mucho, las ofertas aparecen y desaparecen rápido.
|
| 117 |
+
|
| 118 |
+
### Solución
|
| 119 |
+
|
| 120 |
+
**El mismo bot de Telegram**, con una vertical adicional:
|
| 121 |
+
|
| 122 |
+
```
|
| 123 |
+
/usar "zapatos talla 42 mayoreo La Habana"
|
| 124 |
+
/alertar "zapatos" cada 6h
|
| 125 |
+
/precios "zapatos" — muestra precio promedio, mínimo, máximo
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
### ¿Qué scrapeamos?
|
| 129 |
+
|
| 130 |
+
| Fuente | Método | Prioridad |
|
| 131 |
+
|--------|--------|-----------|
|
| 132 |
+
| **Revolico** (productos) | HTTP + BS4 | 🔴 Alta |
|
| 133 |
+
| **Porlalivre** (productos) | HTTP + BS4 | 🔴 Alta |
|
| 134 |
+
| **Telegram canales de compra-venta** | Telethon API | 🟡 Media |
|
| 135 |
+
|
| 136 |
+
---
|
| 137 |
+
|
| 138 |
+
## 🏗️ Arquitectura Propuesta (Cuba Stack)
|
| 139 |
+
|
| 140 |
+
```
|
| 141 |
+
┌─────────────────────────────────────────────────────┐
|
| 142 |
+
│ Hugging Face Space │
|
| 143 |
+
│ │
|
| 144 |
+
│ ┌──────────────┐ ┌──────────────────────────┐ │
|
| 145 |
+
│ │ FastAPI │ │ Gradio Frontend │ │
|
| 146 |
+
│ │ (scraping │ │ - Búsqueda web │ │
|
| 147 |
+
│ │ engine) │ │ - Dashboard verticales │ │
|
| 148 |
+
│ └──────┬───────┘ │ - Historial │ │
|
| 149 |
+
│ │ └──────────────────────────┘ │
|
| 150 |
+
│ ▼ │
|
| 151 |
+
│ ┌────────────────────────────────────────────┐ │
|
| 152 |
+
│ │ Telegram Bot (python-telegram-bot) │ │
|
| 153 |
+
│ │ - /buscar "query" │ │
|
| 154 |
+
│ │ - /alertar "query" cada N horas │ │
|
| 155 |
+
│ │ - /precios "producto" │ │
|
| 156 |
+
│ └────────────────────────────────────────────┘ │
|
| 157 |
+
│ │ │
|
| 158 |
+
│ ▼ │
|
| 159 |
+
│ ┌────────────────────────────────────────────┐ │
|
| 160 |
+
│ │ Scraping Engine │ │
|
| 161 |
+
│ │ - RevolicoAdapter (httpx + BS4) │ │
|
| 162 |
+
│ │ - PorlalivreAdapter (httpx + BS4) │ │
|
| 163 |
+
│ │ - TelegramChannelScraper (telethon) │ │
|
| 164 |
+
│ └────────────────────────────────────────────┘ │
|
| 165 |
+
│ │ │
|
| 166 |
+
│ ▼ │
|
| 167 |
+
│ ┌────────────────────────────────────────────┐ │
|
| 168 |
+
│ │ SQLite (persistencia) │ │
|
| 169 |
+
│ │ - usuarios_telegram │ │
|
| 170 |
+
│ │ - busquedas_activas │ │
|
| 171 |
+
│ │ - resultados_cache │ │
|
| 172 |
+
│ │ - alertas │ │
|
| 173 |
+
│ └────────────────────────────────────────────┘ │
|
| 174 |
+
│ │
|
| 175 |
+
│ ┌────────────────────────────────────────────┐ │
|
| 176 |
+
│ │ GitHub Actions (cron) │ │
|
| 177 |
+
│ │ - Alertas cada N horas (healthcheck) │ │
|
| 178 |
+
│ │ - Re-scrape periódico │ │
|
| 179 |
+
│ └────────────────────────────────────────────┘ │
|
| 180 |
+
└─────────────────────────────────────────────────────┘
|
| 181 |
+
```
|
| 182 |
+
|
| 183 |
+
---
|
| 184 |
+
|
| 185 |
+
## 📐 Pipeline de Adaptador Cuba (nuevo formato)
|
| 186 |
+
|
| 187 |
+
Los adaptadores YAML actuales funcionan para sitios estructurados. Para Cuba necesitamos adaptadores más flexibles. Propongo:
|
| 188 |
+
|
| 189 |
+
```yaml
|
| 190 |
+
# adapters/revolico_casas.yaml
|
| 191 |
+
name: revolico_casas
|
| 192 |
+
site: revolico.com
|
| 193 |
+
vertical: real_estate_cuba
|
| 194 |
+
country: cuba
|
| 195 |
+
search_url: "https://www.revolico.com/search/{query}?page={page}"
|
| 196 |
+
container_selector: "article.result-item" # <-- selectores reales de Revolico
|
| 197 |
+
fields:
|
| 198 |
+
- name: titulo
|
| 199 |
+
selector: "h2.title a"
|
| 200 |
+
type: text
|
| 201 |
+
- name: precio
|
| 202 |
+
selector: "span.price"
|
| 203 |
+
type: price
|
| 204 |
+
- name: ubicacion
|
| 205 |
+
selector: "span.location"
|
| 206 |
+
type: text
|
| 207 |
+
- name: url
|
| 208 |
+
selector: "h2.title a"
|
| 209 |
+
type: url
|
| 210 |
+
attribute: href
|
| 211 |
+
- name: fecha
|
| 212 |
+
selector: "span.date"
|
| 213 |
+
type: text
|
| 214 |
+
canonical_map:
|
| 215 |
+
title: titulo
|
| 216 |
+
price: precio
|
| 217 |
+
location: ubicacion
|
| 218 |
+
url: url
|
| 219 |
+
date: fecha
|
| 220 |
+
```
|
| 221 |
+
|
| 222 |
+
Y para Telegram:
|
| 223 |
+
```yaml
|
| 224 |
+
# adapters/telegram_casas_habana.yaml
|
| 225 |
+
name: telegram_casas_habana
|
| 226 |
+
site: telegram
|
| 227 |
+
vertical: real_estate_cuba
|
| 228 |
+
country: cuba
|
| 229 |
+
telegram_channel: "@CasasEnVentaLaHabana" # <-- nuevo campo
|
| 230 |
+
search_fields:
|
| 231 |
+
- titulo
|
| 232 |
+
- precio
|
| 233 |
+
- ubicacion
|
| 234 |
+
```
|
| 235 |
+
|
| 236 |
+
---
|
| 237 |
+
|
| 238 |
+
## 📋 Plan de Implementación (Fase Cuba 1 — MVP)
|
| 239 |
+
|
| 240 |
+
### Semana 1: Fundación
|
| 241 |
+
1. ✅ Arreglar los 3 tests fallando (bugs existentes)
|
| 242 |
+
2. ⬜ Commitear el progreso actual de Fase 2
|
| 243 |
+
3. ⬜ Crear adapter real para Revolico (inspeccionar HTML real)
|
| 244 |
+
4. ⬜ Crear adapter real para Porlalivre
|
| 245 |
+
|
| 246 |
+
### Semana 2: Telegram Bot
|
| 247 |
+
5. ⬜ Integrar `python-telegram-bot` en el proyecto
|
| 248 |
+
6. ⬜ Comando `/buscar` que usa el search engine existente
|
| 249 |
+
7. ⬜ Comando `/start` con bienvenida y onboarding
|
| 250 |
+
8. ⬜ Desplegar en HF Spaces con Gradio + Bot
|
| 251 |
+
|
| 252 |
+
### Semana 3: Alertas
|
| 253 |
+
9. ⬜ Comando `/alertar` con intervalo configurable
|
| 254 |
+
10. ⬜ Sistema de cache (no repetir resultados ya vistos)
|
| 255 |
+
11. ⬜ GitHub Actions para healthcheck y rescrape periódico
|
| 256 |
+
|
| 257 |
+
### Semana 4: Pulido
|
| 258 |
+
12. ⬜ Comando `/precios` (stats básicos)
|
| 259 |
+
13. ⬜ Landing page en GitHub Pages
|
| 260 |
+
14. ⬜ Probar con 1-2 corredores de casas reales en Cuba
|
| 261 |
+
|
| 262 |
+
---
|
| 263 |
+
|
| 264 |
+
## 💡 Otras Ideas Low-Tech para Cuba
|
| 265 |
+
|
| 266 |
+
### Opción offline / baja conectividad
|
| 267 |
+
Si internet en Cuba es el bottleneck (ETECSA, datos móviles caros):
|
| 268 |
+
- El bot de Telegram funciona con **texto plano**, consume < 1KB por mensaje
|
| 269 |
+
- Las búsquedas se hacen del lado del servidor (HF Spaces)
|
| 270 |
+
- El usuario solo recibe texto → **mínimo consumo de datos**
|
| 271 |
+
|
| 272 |
+
### Opción SMS (cuando Telegram no esté disponible)
|
| 273 |
+
- Cuba tiene buena cobertura SMS
|
| 274 |
+
- Hay APIs de SMS gratuitas (Twilio no, pero algunas locales)
|
| 275 |
+
- **Postergado**: el SMS es más complejo y caro que Telegram
|
| 276 |
+
|
| 277 |
+
### Opcion "corredor power user"
|
| 278 |
+
- Además del bot, ofrecer un **panel web** (Gradio) donde el corredor vea en una pantalla todas las ofertas de todas las fuentes
|
| 279 |
+
- Ideal para el que tiene WiFi en casa (Nauta)
|
| 280 |
+
|
| 281 |
+
---
|
| 282 |
+
|
| 283 |
+
## ⚠️ Riesgos y Mitigaciones (contexto Cuba)
|
| 284 |
+
|
| 285 |
+
| Riesgo | Probabilidad | Mitigación |
|
| 286 |
+
|--------|-------------|------------|
|
| 287 |
+
| Revolico cambia HTML | Alta | Tests de integración que detectan cambios |
|
| 288 |
+
| HF Spaces se duerme (free tier) | Alta | GitHub Actions cada 30min hace ping |
|
| 289 |
+
| Internet inestable en Cuba | Alta | Bot funciona con mensajes de texto (mínimo ancho de banda) |
|
| 290 |
+
| Telegram bloqueado en Cuba | Baja (hoy) | Tener plan B con SMS o web app |
|
| 291 |
+
| ETECSA bloquea el scraping | Baja | Rate limiting, respetar robots.txt |
|
| 292 |
+
|
| 293 |
+
---
|
| 294 |
+
|
| 295 |
+
## 🧪 Lo que YA tenemos que sirve
|
| 296 |
+
|
| 297 |
+
| Recurso | Estado | Para qué sirve en Cuba |
|
| 298 |
+
|---------|--------|----------------------|
|
| 299 |
+
| FastAPI + Orchestrator | ✅ Listo | Backend del bot y la web |
|
| 300 |
+
| AdapterLoader YAML | ✅ Listo | Cargar adaptadores de Cuba |
|
| 301 |
+
| ResultNormalizer | ⚠️ Con bugs | Unificar resultados de Revolico, Porlalivre, Telegram |
|
| 302 |
+
| Endpoint `/api/search` | ✅ Creado | Motor de búsqueda multi-fuente |
|
| 303 |
+
| SQLite | ✅ Listo | Guardar usuarios, búsquedas, cache |
|
| 304 |
+
| GitHub CI | ✅ Listo | Build + test |
|
| 305 |
+
| Gmail SMTP | ✅ Listo | Notificaciones por email (alternativa al bot) |
|
| 306 |
+
|
| 307 |
+
---
|
| 308 |
+
|
| 309 |
+
## 📌 Conclusión
|
| 310 |
+
|
| 311 |
+
**El proyecto es viable 100% gratis.** La clave está en:
|
| 312 |
+
|
| 313 |
+
1. **Telegram Bot como interfaz principal** — es lo que funciona en Cuba, es gratis, es liviano
|
| 314 |
+
2. **Revolico + Porlalivre como fuentes iniciales** — son los clasificados más grandes de Cuba
|
| 315 |
+
3. **HF Spaces + SQLite como backend** — cero costo, cero tarjeta
|
| 316 |
+
4. **Agregar valor con alertas y unificación** — el corredor deja de revisar 5 sitios
|
| 317 |
+
|
| 318 |
+
**No necesitamos USD para construir el MVP.** Necesitamos USD cuando queramos monetizar (y para entonces habrá opciones como Transfermovil, QR desde el exterior, o MercadoPago Cuba si algún día llega).
|
| 319 |
+
|
| 320 |
+
---
|
| 321 |
+
|
| 322 |
+
*Próxima sesión: Arreglar bugs → commitear → adapter Revolico real → bot de Telegram*
|
adapters/example_httpbin.yaml
CHANGED
|
@@ -11,3 +11,8 @@ fields:
|
|
| 11 |
- name: parrafo
|
| 12 |
selector: p
|
| 13 |
type: text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
- name: parrafo
|
| 12 |
selector: p
|
| 13 |
type: text
|
| 14 |
+
|
| 15 |
+
# Mapeo a schema canónico (Fase 2)
|
| 16 |
+
canonical_map:
|
| 17 |
+
title: titulo
|
| 18 |
+
description: parrafo
|
app.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Entry point para HuggingFace Spaces.
|
| 2 |
+
|
| 3 |
+
Monta el frontend Gradio sobre la API FastAPI existente.
|
| 4 |
+
HF Spaces busca este archivo automáticamente en la raíz.
|
| 5 |
+
|
| 6 |
+
Gradio maneja la ruta raíz (/) como home page.
|
| 7 |
+
La API REST sigue disponible en /api/*.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import gradio as gr
|
| 13 |
+
|
| 14 |
+
from modulo_1_servicio.main import app as fastapi_app
|
| 15 |
+
from modulo_1_servicio.ui.gradio_app import build_app
|
| 16 |
+
|
| 17 |
+
# Eliminar la ruta raíz de FastAPI para que Gradio pueda manejarla
|
| 18 |
+
fastapi_app.router.routes = [
|
| 19 |
+
r
|
| 20 |
+
for r in fastapi_app.router.routes
|
| 21 |
+
if not (getattr(r, "path", None) == "/" and getattr(r, "methods", None) == {"GET"})
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
# Construir y montar Gradio sobre FastAPI
|
| 25 |
+
gradio_ui = build_app()
|
| 26 |
+
app = gr.mount_gradio_app(fastapi_app, gradio_ui, path="/")
|
modulo_1_servicio/api/routes_search.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rutas de búsqueda multi-adaptador con normalización de resultados.
|
| 2 |
+
|
| 3 |
+
Fase 2: endpoint ``POST /api/search`` que recibe una consulta y vertical,
|
| 4 |
+
encuentra adaptadores YAML, ejecuta scraping en cada uno y normaliza
|
| 5 |
+
los resultados a un schema canónico.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
from typing import Annotated, Any
|
| 12 |
+
from urllib.parse import quote
|
| 13 |
+
|
| 14 |
+
from fastapi import APIRouter, HTTPException
|
| 15 |
+
from pydantic import BaseModel, Field
|
| 16 |
+
|
| 17 |
+
from modulo_1_servicio.scraping.adapters.loader import AdapterLoader
|
| 18 |
+
from modulo_1_servicio.scraping.engine import Orchestrator
|
| 19 |
+
from modulo_1_servicio.scraping.extractors.beautifulsoup_extractor import (
|
| 20 |
+
BeautifulSoupExtractor,
|
| 21 |
+
)
|
| 22 |
+
from modulo_1_servicio.scraping.models import FieldDefinition, FieldType, ScrapeConfig
|
| 23 |
+
from modulo_1_servicio.scraping.normalizer import ResultNormalizer
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
router = APIRouter(prefix="/api", tags=["search"])
|
| 28 |
+
|
| 29 |
+
# Singleton compartido con routes_scrape
|
| 30 |
+
_orchestrator = Orchestrator()
|
| 31 |
+
_orchestrator.register_engine("web_page", BeautifulSoupExtractor())
|
| 32 |
+
|
| 33 |
+
_adapter_loader = AdapterLoader()
|
| 34 |
+
_adapter_loader.load_all()
|
| 35 |
+
|
| 36 |
+
_normalizer = ResultNormalizer()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class SearchRequest(BaseModel):
|
| 40 |
+
"""Payload para búsqueda por adaptadores."""
|
| 41 |
+
|
| 42 |
+
query: str = Field(
|
| 43 |
+
min_length=1,
|
| 44 |
+
description="Término de búsqueda (ej: 'autos usados', 'iphone 15')",
|
| 45 |
+
)
|
| 46 |
+
vertical: str = Field(
|
| 47 |
+
min_length=1,
|
| 48 |
+
description="Vertical a buscar (ej: cars, real_estate, jobs, test)",
|
| 49 |
+
)
|
| 50 |
+
site: str | None = Field(
|
| 51 |
+
default=None,
|
| 52 |
+
description="Opcional: filtrar a un sitio específico por nombre de adaptador",
|
| 53 |
+
)
|
| 54 |
+
max_pages: int = Field(
|
| 55 |
+
default=1,
|
| 56 |
+
ge=1,
|
| 57 |
+
le=5,
|
| 58 |
+
description="Páginas de resultados por adaptador",
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class SearchAdapterResult(BaseModel):
|
| 63 |
+
"""Resultados de un adaptador individual en la búsqueda."""
|
| 64 |
+
|
| 65 |
+
adapter_name: str
|
| 66 |
+
site: str
|
| 67 |
+
vertical: str
|
| 68 |
+
items_count: int
|
| 69 |
+
error: str | None = None
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class SearchResponse(BaseModel):
|
| 73 |
+
"""Respuesta completa de búsqueda multi-adaptador."""
|
| 74 |
+
|
| 75 |
+
query: str
|
| 76 |
+
vertical: str
|
| 77 |
+
total_found: int
|
| 78 |
+
adapters_used: int
|
| 79 |
+
adapters: list[SearchAdapterResult]
|
| 80 |
+
items: list[dict[str, Any]]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _expand_search_url(template: str, query: str, page: int = 1) -> str:
|
| 84 |
+
"""Expande un template de URL de búsqueda con query y página.
|
| 85 |
+
|
| 86 |
+
Soporta:
|
| 87 |
+
- ``{query}`` → reemplazado con el query URL-encoded
|
| 88 |
+
- ``{page}`` → reemplazado con el número de página
|
| 89 |
+
"""
|
| 90 |
+
encoded = quote(query)
|
| 91 |
+
url = template.replace("{query}", encoded).replace("{page}", str(page))
|
| 92 |
+
return url
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@router.post("/search")
|
| 96 |
+
async def search_adapters(payload: SearchRequest) -> dict[str, Any]:
|
| 97 |
+
"""Busca en múltiples adaptadores y normaliza resultados.
|
| 98 |
+
|
| 99 |
+
Flujo:
|
| 100 |
+
1. Encuentra adaptadores que coinciden con la vertical
|
| 101 |
+
2. Para cada adaptador, construye la URL de búsqueda
|
| 102 |
+
3. Ejecuta scraping con los selectores del adaptador
|
| 103 |
+
4. Normaliza resultados usando el canonical_map
|
| 104 |
+
5. Retorna items combinados con schema canónico
|
| 105 |
+
"""
|
| 106 |
+
# 1. Encontrar adaptadores
|
| 107 |
+
if payload.site:
|
| 108 |
+
adapter = _adapter_loader.get(payload.site)
|
| 109 |
+
if adapter is None:
|
| 110 |
+
raise HTTPException(
|
| 111 |
+
status_code=404,
|
| 112 |
+
detail=f"Adaptador '{payload.site}' no encontrado",
|
| 113 |
+
)
|
| 114 |
+
if adapter.vertical != payload.vertical:
|
| 115 |
+
raise HTTPException(
|
| 116 |
+
status_code=400,
|
| 117 |
+
detail=f"Adaptador '{payload.site}' no pertenece a vertical '{payload.vertical}'",
|
| 118 |
+
)
|
| 119 |
+
matching = [adapter]
|
| 120 |
+
else:
|
| 121 |
+
matching = _adapter_loader.get_by_vertical(payload.vertical)
|
| 122 |
+
if not matching:
|
| 123 |
+
raise HTTPException(
|
| 124 |
+
status_code=404,
|
| 125 |
+
detail=f"No hay adaptadores para la vertical '{payload.vertical}'",
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
all_items: list[dict[str, Any]] = []
|
| 129 |
+
adapter_results: list[SearchAdapterResult] = []
|
| 130 |
+
total_rank = 0
|
| 131 |
+
|
| 132 |
+
# 2-4. Ejecutar scraping en cada adaptador
|
| 133 |
+
for adapter in matching:
|
| 134 |
+
adapter_result = SearchAdapterResult(
|
| 135 |
+
adapter_name=adapter.name,
|
| 136 |
+
site=adapter.site,
|
| 137 |
+
vertical=adapter.vertical,
|
| 138 |
+
items_count=0,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
try:
|
| 142 |
+
# Construir URL de búsqueda
|
| 143 |
+
search_url = _expand_search_url(adapter.search_url, payload.query)
|
| 144 |
+
|
| 145 |
+
# Si el adapter no usa {query}, usar search_url directamente
|
| 146 |
+
# (como en el caso de httpbin que es una URL fija)
|
| 147 |
+
if "{query}" not in adapter.search_url and "{page}" not in adapter.search_url:
|
| 148 |
+
search_url = adapter.search_url
|
| 149 |
+
|
| 150 |
+
# Construir config de scraping desde el adaptador
|
| 151 |
+
fields = tuple(
|
| 152 |
+
FieldDefinition(
|
| 153 |
+
name=f.name,
|
| 154 |
+
selector=f.selector,
|
| 155 |
+
field_type=FieldType(f.type) if f.type in ("text", "price", "url", "number", "date", "image") else FieldType.TEXT,
|
| 156 |
+
)
|
| 157 |
+
for f in adapter.fields
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
scrape_config = ScrapeConfig(
|
| 161 |
+
source_type="web_page",
|
| 162 |
+
source=search_url,
|
| 163 |
+
fields=fields,
|
| 164 |
+
container_selector=adapter.container_selector,
|
| 165 |
+
rate_limit=1.0,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Ejecutar scraping
|
| 169 |
+
result = await _orchestrator.run(scrape_config)
|
| 170 |
+
|
| 171 |
+
if not result.items:
|
| 172 |
+
logger.info("Adaptador %s: 0 resultados para '%s'", adapter.name, payload.query)
|
| 173 |
+
adapter_results.append(adapter_result)
|
| 174 |
+
continue
|
| 175 |
+
|
| 176 |
+
# Extraer datos crudos
|
| 177 |
+
raw_items = [item.data for item in result.items]
|
| 178 |
+
|
| 179 |
+
# 5. Normalizar usando canonical_map
|
| 180 |
+
if adapter.canonical_map:
|
| 181 |
+
canonical_items = _normalizer.normalize(
|
| 182 |
+
canonical_map=adapter.canonical_map,
|
| 183 |
+
raw_items=raw_items,
|
| 184 |
+
source_site=adapter.name,
|
| 185 |
+
source_url=search_url,
|
| 186 |
+
start_rank=total_rank,
|
| 187 |
+
)
|
| 188 |
+
# Convertir a dicts para serialización
|
| 189 |
+
normalized_dicts = [item.model_dump() for item in canonical_items]
|
| 190 |
+
all_items.extend(normalized_dicts)
|
| 191 |
+
total_rank += len(canonical_items)
|
| 192 |
+
adapter_result.items_count = len(canonical_items)
|
| 193 |
+
else:
|
| 194 |
+
# Sin canonical_map, devolver raw_data envuelto
|
| 195 |
+
for i, raw in enumerate(raw_items):
|
| 196 |
+
all_items.append({
|
| 197 |
+
"title": None,
|
| 198 |
+
"description": None,
|
| 199 |
+
"price": None,
|
| 200 |
+
"currency": None,
|
| 201 |
+
"url": None,
|
| 202 |
+
"image_url": None,
|
| 203 |
+
"date": None,
|
| 204 |
+
"location": None,
|
| 205 |
+
"source_site": adapter.name,
|
| 206 |
+
"source_url": search_url,
|
| 207 |
+
"rank": total_rank + i,
|
| 208 |
+
"raw_data": raw,
|
| 209 |
+
})
|
| 210 |
+
total_rank += len(raw_items)
|
| 211 |
+
adapter_result.items_count = len(raw_items)
|
| 212 |
+
|
| 213 |
+
logger.info(
|
| 214 |
+
"Adaptador %s: %d items para '%s'",
|
| 215 |
+
adapter.name,
|
| 216 |
+
adapter_result.items_count,
|
| 217 |
+
payload.query,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
except Exception as e:
|
| 221 |
+
logger.error("Error en adaptador %s: %s", adapter.name, e)
|
| 222 |
+
adapter_result.error = str(e)
|
| 223 |
+
|
| 224 |
+
adapter_results.append(adapter_result)
|
| 225 |
+
|
| 226 |
+
# Si ningún adaptador produjo resultados, igual retornamos respuesta
|
| 227 |
+
response = {
|
| 228 |
+
"query": payload.query,
|
| 229 |
+
"vertical": payload.vertical,
|
| 230 |
+
"total_found": len(all_items),
|
| 231 |
+
"adapters_used": len(matching),
|
| 232 |
+
"adapters": [a.model_dump() for a in adapter_results],
|
| 233 |
+
"items": all_items,
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
return response
|
modulo_1_servicio/main.py
CHANGED
|
@@ -20,6 +20,7 @@ from fastapi.responses import HTMLResponse
|
|
| 20 |
|
| 21 |
from modulo_1_servicio.api.routes_deliver import router as deliver_router
|
| 22 |
from modulo_1_servicio.api.routes_scrape import router as scrape_router
|
|
|
|
| 23 |
from modulo_1_servicio.api.routes_whatsapp_webhook import (
|
| 24 |
router as whatsapp_router,
|
| 25 |
)
|
|
@@ -37,6 +38,7 @@ app = FastAPI(
|
|
| 37 |
|
| 38 |
app.include_router(scrape_router)
|
| 39 |
app.include_router(deliver_router)
|
|
|
|
| 40 |
app.include_router(whatsapp_router)
|
| 41 |
|
| 42 |
|
|
|
|
| 20 |
|
| 21 |
from modulo_1_servicio.api.routes_deliver import router as deliver_router
|
| 22 |
from modulo_1_servicio.api.routes_scrape import router as scrape_router
|
| 23 |
+
from modulo_1_servicio.api.routes_search import router as search_router
|
| 24 |
from modulo_1_servicio.api.routes_whatsapp_webhook import (
|
| 25 |
router as whatsapp_router,
|
| 26 |
)
|
|
|
|
| 38 |
|
| 39 |
app.include_router(scrape_router)
|
| 40 |
app.include_router(deliver_router)
|
| 41 |
+
app.include_router(search_router)
|
| 42 |
app.include_router(whatsapp_router)
|
| 43 |
|
| 44 |
|
modulo_1_servicio/requirements-hf.txt
CHANGED
|
@@ -11,3 +11,4 @@ pyyaml>=6.0
|
|
| 11 |
jinja2>=3.1
|
| 12 |
python-multipart>=0.0.6
|
| 13 |
sendgrid>=6.11
|
|
|
|
|
|
| 11 |
jinja2>=3.1
|
| 12 |
python-multipart>=0.0.6
|
| 13 |
sendgrid>=6.11
|
| 14 |
+
gradio>=4.0
|
modulo_1_servicio/scraping/adapters/models.py
CHANGED
|
@@ -37,3 +37,11 @@ class SiteAdapter(BaseModel):
|
|
| 37 |
min_length=1,
|
| 38 |
description="Campos a extraer de cada resultado",
|
| 39 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
min_length=1,
|
| 38 |
description="Campos a extraer de cada resultado",
|
| 39 |
)
|
| 40 |
+
canonical_map: Optional[dict[str, str]] = Field(
|
| 41 |
+
default=None,
|
| 42 |
+
description=(
|
| 43 |
+
"Mapeo de campos del adaptador al schema canónico. "
|
| 44 |
+
"Ej: {\"title\": \"nombre\", \"price\": \"precio\"}. "
|
| 45 |
+
"Si es None, no se aplica normalización."
|
| 46 |
+
),
|
| 47 |
+
)
|
modulo_1_servicio/scraping/normalizer.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalización de resultados a schema canónico.
|
| 2 |
+
|
| 3 |
+
Permite que resultados de distintos sitios (cada uno con sus
|
| 4 |
+
propios nombres de campo) se unifiquen en un formato común
|
| 5 |
+
para mostrarlos side-by-side en la UI.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re as _re
|
| 11 |
+
from typing import Any, Optional
|
| 12 |
+
|
| 13 |
+
from pydantic import BaseModel, Field
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CanonicalItem(BaseModel):
|
| 17 |
+
"""Item normalizado con campos canónicos.
|
| 18 |
+
|
| 19 |
+
Cualquier resultado de scraping, sin importar el sitio de origen,
|
| 20 |
+
se mapea a este schema. Los campos no disponibles quedan como ``None``.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
title: Optional[str] = Field(default=None, description="Título del item")
|
| 24 |
+
description: Optional[str] = Field(default=None, description="Descripción textual")
|
| 25 |
+
price: Optional[float] = Field(default=None, description="Precio numérico")
|
| 26 |
+
currency: Optional[str] = Field(default=None, description="Código de moneda (MXN, USD, etc.)")
|
| 27 |
+
url: Optional[str] = Field(default=None, description="URL del item original")
|
| 28 |
+
image_url: Optional[str] = Field(default=None, description="URL de imagen principal")
|
| 29 |
+
date: Optional[str] = Field(default=None, description="Fecha del listing")
|
| 30 |
+
location: Optional[str] = Field(default=None, description="Ubicación geográfica")
|
| 31 |
+
|
| 32 |
+
# Metadatos
|
| 33 |
+
source_site: str = Field(description="Nombre del sitio/adaptador de origen")
|
| 34 |
+
source_url: str = Field(description="URL de la página donde se encontró")
|
| 35 |
+
rank: int = Field(default=0, description="Posición en resultados")
|
| 36 |
+
|
| 37 |
+
# Datos crudos originales (por si se necesita depuración)
|
| 38 |
+
raw_data: dict[str, Any] = Field(
|
| 39 |
+
default_factory=dict,
|
| 40 |
+
description="Campos originales del adaptador",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Mapeo por defecto: nombre de campo canónico → función de transformación
|
| 45 |
+
# Estas funciones reciben el valor crudo y retornan el valor normalizado.
|
| 46 |
+
_DEFAULT_TRANSFORMS: dict[str, str] = {}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class ResultNormalizer:
|
| 50 |
+
"""Normaliza resultados de scraping usando el canonical_map del adaptador.
|
| 51 |
+
|
| 52 |
+
Uso:
|
| 53 |
+
normalizer = ResultNormalizer()
|
| 54 |
+
items = normalizer.normalize(adapter, raw_items, source_url)
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
# Mapeo de tipos canónicos a funciones de transformación
|
| 58 |
+
TYPE_TRANSFORMS: dict[str, str] = {
|
| 59 |
+
"price": "price",
|
| 60 |
+
"number": "number",
|
| 61 |
+
"url": "url",
|
| 62 |
+
"image": "image",
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def _to_float(value: Any) -> float | None:
|
| 67 |
+
"""Convierte un valor a float, limpiando símbolos de moneda.
|
| 68 |
+
|
| 69 |
+
Soporta formatos:
|
| 70 |
+
- US: ``$1,234.56`` → 1234.56
|
| 71 |
+
- Europeo: ``€ 50,00`` → 50.00
|
| 72 |
+
- Mixto: ``$ 25,000 MXN`` → 25000.0
|
| 73 |
+
- Sin formato: ``gratis`` → None
|
| 74 |
+
"""
|
| 75 |
+
if value is None:
|
| 76 |
+
return None
|
| 77 |
+
if isinstance(value, (int, float)):
|
| 78 |
+
return float(value)
|
| 79 |
+
|
| 80 |
+
s = str(value).strip()
|
| 81 |
+
if not s:
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
# Eliminar símbolos de moneda conocidos
|
| 85 |
+
for ch in ("$", "€", "£", "¥"):
|
| 86 |
+
s = s.replace(ch, "")
|
| 87 |
+
s = s.strip()
|
| 88 |
+
if not s:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
last_comma = s.rfind(",")
|
| 92 |
+
last_dot = s.rfind(".")
|
| 93 |
+
|
| 94 |
+
if last_dot < 0 and last_comma >= 0:
|
| 95 |
+
# Sin puntos, con coma(s): determinar si coma es decimal o miles
|
| 96 |
+
after_comma = s[last_comma + 1:]
|
| 97 |
+
if _re.match(r"^\d{1,2}\D*$", after_comma):
|
| 98 |
+
# Formato europeo: coma es decimal (ej: "50,00")
|
| 99 |
+
s = s.replace(",", ".", 1)
|
| 100 |
+
s = s.replace(",", "")
|
| 101 |
+
else:
|
| 102 |
+
# Formato US: coma es separador de miles (ej: "25,000")
|
| 103 |
+
s = s.replace(",", "")
|
| 104 |
+
elif last_dot >= 0 and last_comma >= 0:
|
| 105 |
+
# Ambos separadores presentes
|
| 106 |
+
if last_comma > last_dot:
|
| 107 |
+
# Europeo: 1.234,56 → coma después del punto = decimal
|
| 108 |
+
s = s.replace(".", "")
|
| 109 |
+
s = s.replace(",", ".")
|
| 110 |
+
else:
|
| 111 |
+
# US: 1,234.56 → punto después de coma = decimal
|
| 112 |
+
s = s.replace(",", "")
|
| 113 |
+
# else: solo puntos o sin separadores, intentar directo
|
| 114 |
+
|
| 115 |
+
try:
|
| 116 |
+
return float(s)
|
| 117 |
+
except (ValueError, TypeError):
|
| 118 |
+
# Último recurso: extraer número con regex
|
| 119 |
+
match = _re.search(r"-?\d+(?:\.\d+)?", s)
|
| 120 |
+
if match:
|
| 121 |
+
try:
|
| 122 |
+
return float(match.group())
|
| 123 |
+
except (ValueError, TypeError):
|
| 124 |
+
return None
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _to_str(value: Any) -> str | None:
|
| 129 |
+
if value is None:
|
| 130 |
+
return None
|
| 131 |
+
return str(value).strip() or None
|
| 132 |
+
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _extract_url(value: Any) -> str | None:
|
| 135 |
+
"""Extrae un href de un elemento si es necesario."""
|
| 136 |
+
if value is None:
|
| 137 |
+
return None
|
| 138 |
+
val = str(value).strip()
|
| 139 |
+
return val if val.startswith(("http://", "https://", "/")) else None
|
| 140 |
+
|
| 141 |
+
def normalize(
|
| 142 |
+
self,
|
| 143 |
+
canonical_map: dict[str, str],
|
| 144 |
+
raw_items: list[dict[str, Any]],
|
| 145 |
+
source_site: str,
|
| 146 |
+
source_url: str,
|
| 147 |
+
start_rank: int = 0,
|
| 148 |
+
) -> list[CanonicalItem]:
|
| 149 |
+
"""Convierte items crudos a CanonicalItem usando el canonical_map.
|
| 150 |
+
|
| 151 |
+
Args:
|
| 152 |
+
canonical_map: Diccionario {campo_canónico: campo_origen}.
|
| 153 |
+
Ej: {"title": "nombre", "price": "precio"}
|
| 154 |
+
raw_items: Lista de items con campos del adaptador.
|
| 155 |
+
source_site: Nombre del sitio/adaptador de origen.
|
| 156 |
+
source_url: URL de la página escrapeada.
|
| 157 |
+
start_rank: Ranking inicial (para paginación).
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
Lista de CanonicalItem normalizados.
|
| 161 |
+
"""
|
| 162 |
+
results: list[CanonicalItem] = []
|
| 163 |
+
|
| 164 |
+
for rank_offset, raw in enumerate(raw_items):
|
| 165 |
+
canonical_kwargs: dict[str, Any] = {
|
| 166 |
+
"source_site": source_site,
|
| 167 |
+
"source_url": source_url,
|
| 168 |
+
"rank": start_rank + rank_offset,
|
| 169 |
+
"raw_data": dict(raw),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
# Mapear cada campo canónico
|
| 173 |
+
for canon_field, source_field in canonical_map.items():
|
| 174 |
+
raw_value = raw.get(source_field)
|
| 175 |
+
if raw_value is None:
|
| 176 |
+
continue
|
| 177 |
+
|
| 178 |
+
if canon_field == "price":
|
| 179 |
+
canonical_kwargs["price"] = self._to_float(raw_value)
|
| 180 |
+
elif canon_field in ("url", "image_url"):
|
| 181 |
+
canonical_kwargs[canon_field] = self._extract_url(raw_value)
|
| 182 |
+
else:
|
| 183 |
+
canonical_kwargs[canon_field] = self._to_str(raw_value)
|
| 184 |
+
|
| 185 |
+
results.append(CanonicalItem(**canonical_kwargs))
|
| 186 |
+
|
| 187 |
+
return results
|
modulo_1_servicio/ui/__init__.py
ADDED
|
File without changes
|
modulo_1_servicio/ui/gradio_app.py
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frontend Gradio para ScrapperGenérico.
|
| 2 |
+
|
| 3 |
+
Se monta sobre la app FastAPI existente para servir en HuggingFace Spaces.
|
| 4 |
+
Incluye búsqueda multi-adaptador, visualización de resultados y estado.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
from urllib.parse import quote
|
| 12 |
+
|
| 13 |
+
import gradio as gr
|
| 14 |
+
|
| 15 |
+
from modulo_1_servicio.scraping.adapters.loader import AdapterLoader
|
| 16 |
+
from modulo_1_servicio.scraping.engine import Orchestrator
|
| 17 |
+
from modulo_1_servicio.scraping.extractors.beautifulsoup_extractor import (
|
| 18 |
+
BeautifulSoupExtractor,
|
| 19 |
+
)
|
| 20 |
+
from modulo_1_servicio.scraping.models import FieldDefinition, FieldType, ScrapeConfig
|
| 21 |
+
from modulo_1_servicio.scraping.normalizer import ResultNormalizer
|
| 22 |
+
|
| 23 |
+
logger = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Singletons compartidos (mismos patron que routes_search.py)
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
_adapter_loader = AdapterLoader()
|
| 29 |
+
_adapter_loader.load_all()
|
| 30 |
+
_orchestrator = Orchestrator()
|
| 31 |
+
_orchestrator.register_engine("web_page", BeautifulSoupExtractor())
|
| 32 |
+
_normalizer = ResultNormalizer()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# ---------------------------------------------------------------------------
|
| 36 |
+
# Helpers
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
def _get_verticals() -> list[str]:
|
| 39 |
+
return sorted({a.vertical for a in _adapter_loader.get_all()})
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _get_adapter_names() -> list[str]:
|
| 43 |
+
return sorted(a.name for a in _adapter_loader.get_all())
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ---------------------------------------------------------------------------
|
| 47 |
+
# Lógica de búsqueda (async para integrar con Orchestrator.run)
|
| 48 |
+
# ---------------------------------------------------------------------------
|
| 49 |
+
async def search_action(
|
| 50 |
+
query: str,
|
| 51 |
+
vertical: str,
|
| 52 |
+
site: str,
|
| 53 |
+
progress: gr.Progress = gr.Progress(),
|
| 54 |
+
) -> tuple[str, list[list], str]:
|
| 55 |
+
"""Ejecuta búsqueda multi-adaptador.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
(summary_markdown, table_data, raw_json)
|
| 59 |
+
"""
|
| 60 |
+
if not query or not query.strip():
|
| 61 |
+
return "⚠️ Ingresa un término de búsqueda.", [], "{}"
|
| 62 |
+
if not vertical:
|
| 63 |
+
return "⚠️ Selecciona una vertical.", [], "{}"
|
| 64 |
+
|
| 65 |
+
query = query.strip()
|
| 66 |
+
|
| 67 |
+
# --- Determinar adaptadores a usar ---
|
| 68 |
+
if site and site != "all":
|
| 69 |
+
adapter = _adapter_loader.get(site)
|
| 70 |
+
matching = [adapter] if adapter else []
|
| 71 |
+
else:
|
| 72 |
+
matching = _adapter_loader.get_by_vertical(vertical)
|
| 73 |
+
|
| 74 |
+
if not matching:
|
| 75 |
+
msg = f"⚠️ No hay adaptadores para la vertical **'{vertical}'**."
|
| 76 |
+
return msg, [], "{}"
|
| 77 |
+
|
| 78 |
+
progress(0.0, desc="Iniciando búsqueda…")
|
| 79 |
+
all_items: list[dict] = []
|
| 80 |
+
total_rank = 0
|
| 81 |
+
|
| 82 |
+
for idx, adapter in enumerate(matching):
|
| 83 |
+
progress(
|
| 84 |
+
(idx + 0.5) / len(matching),
|
| 85 |
+
desc=f"Consultando {adapter.name}…",
|
| 86 |
+
)
|
| 87 |
+
try:
|
| 88 |
+
# Construir URL de búsqueda
|
| 89 |
+
search_url = adapter.search_url
|
| 90 |
+
if "{query}" in search_url:
|
| 91 |
+
search_url = search_url.replace("{query}", quote(query))
|
| 92 |
+
if "{page}" in search_url:
|
| 93 |
+
search_url = search_url.replace("{page}", "1")
|
| 94 |
+
|
| 95 |
+
fields = tuple(
|
| 96 |
+
FieldDefinition(
|
| 97 |
+
name=f.name,
|
| 98 |
+
selector=f.selector,
|
| 99 |
+
field_type=(
|
| 100 |
+
FieldType(f.type)
|
| 101 |
+
if f.type
|
| 102 |
+
in ("text", "price", "url", "number", "date", "image")
|
| 103 |
+
else FieldType.TEXT
|
| 104 |
+
),
|
| 105 |
+
)
|
| 106 |
+
for f in adapter.fields
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
config = ScrapeConfig(
|
| 110 |
+
source_type="web_page",
|
| 111 |
+
source=search_url,
|
| 112 |
+
fields=fields,
|
| 113 |
+
container_selector=adapter.container_selector,
|
| 114 |
+
rate_limit=1.0,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
result = await _orchestrator.run(config)
|
| 118 |
+
|
| 119 |
+
if not result.items:
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
raw_items = [item.data for item in result.items]
|
| 123 |
+
|
| 124 |
+
if adapter.canonical_map:
|
| 125 |
+
canonical = _normalizer.normalize(
|
| 126 |
+
canonical_map=adapter.canonical_map,
|
| 127 |
+
raw_items=raw_items,
|
| 128 |
+
source_site=adapter.name,
|
| 129 |
+
source_url=search_url,
|
| 130 |
+
start_rank=total_rank,
|
| 131 |
+
)
|
| 132 |
+
for item in canonical:
|
| 133 |
+
all_items.append(
|
| 134 |
+
{
|
| 135 |
+
"rank": item.rank + 1,
|
| 136 |
+
"title": item.title or "(Sin título)",
|
| 137 |
+
"description": (item.description or "")[:150],
|
| 138 |
+
"price": (
|
| 139 |
+
f"${item.price:,.2f}"
|
| 140 |
+
if item.price is not None
|
| 141 |
+
else ""
|
| 142 |
+
),
|
| 143 |
+
"site": item.source_site,
|
| 144 |
+
"url": item.url or "",
|
| 145 |
+
}
|
| 146 |
+
)
|
| 147 |
+
total_rank += len(canonical)
|
| 148 |
+
else:
|
| 149 |
+
first_field = adapter.fields[0].name if adapter.fields else ""
|
| 150 |
+
for j, raw in enumerate(raw_items):
|
| 151 |
+
all_items.append(
|
| 152 |
+
{
|
| 153 |
+
"rank": total_rank + j + 1,
|
| 154 |
+
"title": raw.get(first_field, "(Sin título)"),
|
| 155 |
+
"description": "",
|
| 156 |
+
"price": "",
|
| 157 |
+
"site": adapter.name,
|
| 158 |
+
"url": "",
|
| 159 |
+
}
|
| 160 |
+
)
|
| 161 |
+
total_rank += len(raw_items)
|
| 162 |
+
|
| 163 |
+
except Exception as exc:
|
| 164 |
+
logger.error("Error en adaptador %s: %s", adapter.name, exc)
|
| 165 |
+
|
| 166 |
+
progress(1.0, desc="Completado")
|
| 167 |
+
|
| 168 |
+
if not all_items:
|
| 169 |
+
return "😕 No se encontraron resultados.", [], "[]"
|
| 170 |
+
|
| 171 |
+
table = [
|
| 172 |
+
[it["rank"], it["title"], it["description"], it["price"], it["site"]]
|
| 173 |
+
for it in all_items
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
summary = (
|
| 177 |
+
f"✅ **{len(all_items)} resultados** en "
|
| 178 |
+
f"{len(matching)} adaptador(es) para **'{query}'**"
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
return summary, table, json.dumps(all_items, indent=2, ensure_ascii=False)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# ---------------------------------------------------------------------------
|
| 185 |
+
# Construcción de la UI Gradio
|
| 186 |
+
# ---------------------------------------------------------------------------
|
| 187 |
+
def build_app() -> gr.Blocks:
|
| 188 |
+
"""Construye y retorna la aplicación Gradio lista para montar."""
|
| 189 |
+
verticals = _get_verticals()
|
| 190 |
+
adapter_names = _get_adapter_names()
|
| 191 |
+
|
| 192 |
+
css = """
|
| 193 |
+
footer {display:none !important}
|
| 194 |
+
.gradio-container {max-width: 1200px !important; margin: 0 auto !important}
|
| 195 |
+
"""
|
| 196 |
+
|
| 197 |
+
with gr.Blocks(
|
| 198 |
+
title="ScrapperGenérico",
|
| 199 |
+
) as demo:
|
| 200 |
+
# Gradio 6.x: theme y css se setean después de crear el bloque
|
| 201 |
+
demo.theme = gr.themes.Soft()
|
| 202 |
+
demo.css = css
|
| 203 |
+
# Header
|
| 204 |
+
gr.HTML(
|
| 205 |
+
"""
|
| 206 |
+
<div style="text-align:center;padding:24px 0 8px">
|
| 207 |
+
<h1 style="margin:0;font-size:2rem">🕸️ ScrapperGenérico</h1>
|
| 208 |
+
<p style="color:#64748b;margin:4px 0 0;font-size:1.1rem">
|
| 209 |
+
Buscador universal — productos, servicios y ofertas
|
| 210 |
+
en múltiples sitios simultáneamente
|
| 211 |
+
</p>
|
| 212 |
+
</div>
|
| 213 |
+
"""
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
with gr.Tabs():
|
| 217 |
+
# =================================================================
|
| 218 |
+
# TAB 1 — BÚSQUEDA
|
| 219 |
+
# =================================================================
|
| 220 |
+
with gr.Tab("🔍 Buscar"):
|
| 221 |
+
with gr.Row(equal_height=True):
|
| 222 |
+
query_input = gr.Textbox(
|
| 223 |
+
label="¿Qué buscas?",
|
| 224 |
+
placeholder=(
|
| 225 |
+
"Ej: casa 3 habitaciones La Habana, "
|
| 226 |
+
"iPhone 15, zapatos talla 42…"
|
| 227 |
+
),
|
| 228 |
+
scale=3,
|
| 229 |
+
container=True,
|
| 230 |
+
)
|
| 231 |
+
vertical_dropdown = gr.Dropdown(
|
| 232 |
+
label="Vertical",
|
| 233 |
+
choices=verticals,
|
| 234 |
+
value=verticals[0] if verticals else None,
|
| 235 |
+
scale=1,
|
| 236 |
+
interactive=True,
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
with gr.Row(equal_height=True):
|
| 240 |
+
site_dropdown = gr.Dropdown(
|
| 241 |
+
label="Sitio (opcional — vacío = todos)",
|
| 242 |
+
choices=["all"] + adapter_names,
|
| 243 |
+
value="all",
|
| 244 |
+
scale=2,
|
| 245 |
+
interactive=True,
|
| 246 |
+
)
|
| 247 |
+
search_btn = gr.Button(
|
| 248 |
+
"🔍 Buscar", variant="primary", size="lg", scale=1
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
summary_md = gr.Markdown(
|
| 252 |
+
value="",
|
| 253 |
+
label="Resumen",
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
results_table = gr.Dataframe(
|
| 257 |
+
headers=["#", "Título", "Descripción", "Precio", "Sitio"],
|
| 258 |
+
datatype=["number", "str", "str", "str", "str"],
|
| 259 |
+
column_count=(5, "fixed"),
|
| 260 |
+
label="Adaptadores Cargados",
|
| 261 |
+
wrap=True,
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
# Ajustar ancho de columnas para adaptadores
|
| 265 |
+
gr.Markdown(
|
| 266 |
+
f"**Total:** {_adapter_loader.count} adaptadores · "
|
| 267 |
+
f"**Verticales:** {', '.join(verticals)}"
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
# Recargar adaptadores (por si se agregaron nuevos YAML)
|
| 271 |
+
if verticals:
|
| 272 |
+
gr.Markdown("---")
|
| 273 |
+
gr.Markdown(
|
| 274 |
+
"💡 *Agrega archivos ``.yaml`` en el directorio "
|
| 275 |
+
"``adapters/`` y reinicia el servidor.*"
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# =================================================================
|
| 279 |
+
# TAB 3 — ESTADO / AYUDA
|
| 280 |
+
# =================================================================
|
| 281 |
+
with gr.Tab("⚙️ Estado"):
|
| 282 |
+
gr.Markdown("## 🚦 Estado del Servicio")
|
| 283 |
+
gr.Markdown(f"- **Adaptadores cargados:** {_adapter_loader.count}")
|
| 284 |
+
gr.Markdown(
|
| 285 |
+
f"- **Verticales disponibles:** {', '.join(verticals)}"
|
| 286 |
+
)
|
| 287 |
+
gr.Markdown(
|
| 288 |
+
"- **API REST:** Visita "
|
| 289 |
+
"[`/api/docs`](/api/docs) para Swagger"
|
| 290 |
+
)
|
| 291 |
+
gr.Markdown(
|
| 292 |
+
"- **Health Check:** [`/api/health`](/api/health)"
|
| 293 |
+
)
|
| 294 |
+
gr.Markdown(
|
| 295 |
+
"- **Stack:** FastAPI + BeautifulSoup + Gradio "
|
| 296 |
+
"en HuggingFace Spaces"
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
gr.Markdown("---")
|
| 300 |
+
gr.Markdown("## 📖 Cómo usar")
|
| 301 |
+
gr.Markdown(
|
| 302 |
+
"""
|
| 303 |
+
1. Escribe lo que buscas en el campo **¿Qué buscas?**
|
| 304 |
+
2. Selecciona la **Vertical** (categoría)
|
| 305 |
+
3. Opcional: elige un **Sitio** específico
|
| 306 |
+
4. Presiona **Buscar** o la tecla **Enter**
|
| 307 |
+
5. Los resultados aparecen en la tabla inferior
|
| 308 |
+
|
| 309 |
+
Los adaptadores definen qué sitios se buscan y cómo
|
| 310 |
+
se extraen los datos. Puedes crear nuevos adaptadores
|
| 311 |
+
agregando archivos YAML en ``adapters/``.
|
| 312 |
+
"""
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
return demo
|
modulo_2_admin/core/client.py
CHANGED
|
@@ -134,5 +134,70 @@ class ScrapperClient:
|
|
| 134 |
r.raise_for_status()
|
| 135 |
return r.json()
|
| 136 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
def close(self) -> None:
|
| 138 |
self._client.close()
|
|
|
|
| 134 |
r.raise_for_status()
|
| 135 |
return r.json()
|
| 136 |
|
| 137 |
+
# --- Fase 2: Búsqueda por adaptadores ---
|
| 138 |
+
|
| 139 |
+
def list_adapters(self, vertical: str | None = None) -> list[dict[str, Any]]:
|
| 140 |
+
"""Obtiene la lista de adaptadores disponibles.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
vertical: Opcional, filtrar por vertical.
|
| 144 |
+
|
| 145 |
+
Returns:
|
| 146 |
+
Lista de adaptadores con su configuración.
|
| 147 |
+
"""
|
| 148 |
+
params = {}
|
| 149 |
+
if vertical:
|
| 150 |
+
params["vertical"] = vertical
|
| 151 |
+
r = self._client.get(
|
| 152 |
+
f"{self.base_url}/api/adapters",
|
| 153 |
+
params=params,
|
| 154 |
+
)
|
| 155 |
+
r.raise_for_status()
|
| 156 |
+
data = r.json()
|
| 157 |
+
return data.get("adapters", [])
|
| 158 |
+
|
| 159 |
+
def list_verticals(self) -> list[str]:
|
| 160 |
+
"""Obtiene la lista de verticales disponibles.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
Lista de nombres de vertical únicos.
|
| 164 |
+
"""
|
| 165 |
+
adapters = self.list_adapters()
|
| 166 |
+
verticals = sorted({a.get("vertical", "unknown") for a in adapters})
|
| 167 |
+
return verticals
|
| 168 |
+
|
| 169 |
+
def search(
|
| 170 |
+
self,
|
| 171 |
+
query: str,
|
| 172 |
+
vertical: str,
|
| 173 |
+
site: str | None = None,
|
| 174 |
+
max_pages: int = 1,
|
| 175 |
+
) -> dict[str, Any]:
|
| 176 |
+
"""Ejecuta una búsqueda multi-adaptador.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
query: Término de búsqueda.
|
| 180 |
+
vertical: Vertical a buscar.
|
| 181 |
+
site: Opcional, filtrar a un adaptador específico.
|
| 182 |
+
max_pages: Páginas por adaptador.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
Resultados de búsqueda con items normalizados.
|
| 186 |
+
"""
|
| 187 |
+
payload: dict[str, Any] = {
|
| 188 |
+
"query": query,
|
| 189 |
+
"vertical": vertical,
|
| 190 |
+
"max_pages": max_pages,
|
| 191 |
+
}
|
| 192 |
+
if site:
|
| 193 |
+
payload["site"] = site
|
| 194 |
+
|
| 195 |
+
r = self._client.post(
|
| 196 |
+
f"{self.base_url}/api/search",
|
| 197 |
+
json=payload,
|
| 198 |
+
)
|
| 199 |
+
r.raise_for_status()
|
| 200 |
+
return r.json()
|
| 201 |
+
|
| 202 |
def close(self) -> None:
|
| 203 |
self._client.close()
|
modulo_2_admin/ui/main.py
CHANGED
|
@@ -38,6 +38,8 @@ class PythonBridge(QObject):
|
|
| 38 |
lastResultChanged = Signal(str)
|
| 39 |
historyChanged = Signal()
|
| 40 |
operationDetailChanged = Signal(str)
|
|
|
|
|
|
|
| 41 |
|
| 42 |
def __init__(self, parent: QObject | None = None) -> None:
|
| 43 |
super().__init__(parent)
|
|
@@ -46,7 +48,10 @@ class PythonBridge(QObject):
|
|
| 46 |
self._connected = False
|
| 47 |
self._last_result: dict[str, Any] = {}
|
| 48 |
self._operation_detail: dict[str, Any] = {}
|
|
|
|
|
|
|
| 49 |
self._check_connection()
|
|
|
|
| 50 |
|
| 51 |
# --- Propiedades expuestas a QML ---
|
| 52 |
|
|
@@ -212,6 +217,66 @@ class PythonBridge(QObject):
|
|
| 212 |
except Exception as e:
|
| 213 |
return json.dumps({"error": str(e)})
|
| 214 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
|
| 216 |
def main() -> None:
|
| 217 |
app = QGuiApplication(sys.argv)
|
|
|
|
| 38 |
lastResultChanged = Signal(str)
|
| 39 |
historyChanged = Signal()
|
| 40 |
operationDetailChanged = Signal(str)
|
| 41 |
+
searchResultsChanged = Signal(str)
|
| 42 |
+
adaptersChanged = Signal(str)
|
| 43 |
|
| 44 |
def __init__(self, parent: QObject | None = None) -> None:
|
| 45 |
super().__init__(parent)
|
|
|
|
| 48 |
self._connected = False
|
| 49 |
self._last_result: dict[str, Any] = {}
|
| 50 |
self._operation_detail: dict[str, Any] = {}
|
| 51 |
+
self._search_results: dict[str, Any] = {}
|
| 52 |
+
self._adapters: list[dict[str, Any]] = []
|
| 53 |
self._check_connection()
|
| 54 |
+
self._refresh_adapters()
|
| 55 |
|
| 56 |
# --- Propiedades expuestas a QML ---
|
| 57 |
|
|
|
|
| 217 |
except Exception as e:
|
| 218 |
return json.dumps({"error": str(e)})
|
| 219 |
|
| 220 |
+
# --- Fase 2: Búsqueda por vertical ---
|
| 221 |
+
|
| 222 |
+
@Property(str, notify=adaptersChanged)
|
| 223 |
+
def adapters(self) -> str:
|
| 224 |
+
return json.dumps(self._adapters)
|
| 225 |
+
|
| 226 |
+
@Property(str, notify=searchResultsChanged)
|
| 227 |
+
def searchResults(self) -> str:
|
| 228 |
+
return json.dumps(self._search_results)
|
| 229 |
+
|
| 230 |
+
def _refresh_adapters(self) -> None:
|
| 231 |
+
try:
|
| 232 |
+
self._adapters = self._client.list_adapters()
|
| 233 |
+
except Exception:
|
| 234 |
+
self._adapters = []
|
| 235 |
+
self.adaptersChanged.emit(self.adapters)
|
| 236 |
+
|
| 237 |
+
@Slot(result=str)
|
| 238 |
+
def refresh_adapters(self) -> str:
|
| 239 |
+
"""Recarga la lista de adaptadores desde el servicio."""
|
| 240 |
+
self._refresh_adapters()
|
| 241 |
+
return self.adapters
|
| 242 |
+
|
| 243 |
+
@Slot(result=str)
|
| 244 |
+
def get_verticals(self) -> str:
|
| 245 |
+
"""Retorna la lista de verticales disponibles."""
|
| 246 |
+
try:
|
| 247 |
+
verticals = self._client.list_verticals()
|
| 248 |
+
return json.dumps(verticals)
|
| 249 |
+
except Exception as e:
|
| 250 |
+
return json.dumps({"error": str(e)})
|
| 251 |
+
|
| 252 |
+
@Slot(str, str, str, result=str)
|
| 253 |
+
def search_adapters(self, query: str, vertical: str, site: str) -> str:
|
| 254 |
+
"""Ejecuta búsqueda multi-adaptador desde QML.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
query: Término de búsqueda.
|
| 258 |
+
vertical: Vertical (cars, real_estate, etc.).
|
| 259 |
+
site: Nombre de adaptador específico (o vacío para todos).
|
| 260 |
+
|
| 261 |
+
Returns:
|
| 262 |
+
JSON con resultados normalizados.
|
| 263 |
+
"""
|
| 264 |
+
try:
|
| 265 |
+
site_param = site if site and site != "all" else None
|
| 266 |
+
results = self._client.search(
|
| 267 |
+
query=query,
|
| 268 |
+
vertical=vertical,
|
| 269 |
+
site=site_param,
|
| 270 |
+
)
|
| 271 |
+
self._search_results = results
|
| 272 |
+
self.searchResultsChanged.emit(self.searchResults)
|
| 273 |
+
return json.dumps(results)
|
| 274 |
+
except Exception as e:
|
| 275 |
+
error = {"error": str(e)}
|
| 276 |
+
self._search_results = error
|
| 277 |
+
self.searchResultsChanged.emit(self.searchResults)
|
| 278 |
+
return json.dumps(error)
|
| 279 |
+
|
| 280 |
|
| 281 |
def main() -> None:
|
| 282 |
app = QGuiApplication(sys.argv)
|
modulo_2_admin/ui/qml/main.qml
CHANGED
|
@@ -62,6 +62,16 @@ ApplicationWindow {
|
|
| 62 |
font.pixelSize: 13
|
| 63 |
}
|
| 64 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
ToolButton {
|
| 66 |
text: "Nuevo Scraper"
|
| 67 |
highlighted: currentView === "scrape"
|
|
@@ -109,10 +119,11 @@ ApplicationWindow {
|
|
| 109 |
anchors.fill: parent
|
| 110 |
currentIndex: {
|
| 111 |
if (currentView === "dashboard") return 0;
|
| 112 |
-
if (currentView === "
|
| 113 |
-
if (currentView === "
|
| 114 |
-
if (currentView === "
|
| 115 |
-
if (currentView === "
|
|
|
|
| 116 |
return 0;
|
| 117 |
}
|
| 118 |
|
|
@@ -264,7 +275,387 @@ ApplicationWindow {
|
|
| 264 |
}
|
| 265 |
}
|
| 266 |
|
| 267 |
-
// ======== Página 1:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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queda"
|
| 67 |
+
highlighted: currentView === "search"
|
| 68 |
+
onClicked: { currentView = "search"; loadSearchVerticales(); }
|
| 69 |
+
contentItem: Text {
|
| 70 |
+
text: parent.text
|
| 71 |
+
color: currentView === "search" ? accent : "white"
|
| 72 |
+
font.pixelSize: 13
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
ToolButton {
|
| 76 |
text: "Nuevo Scraper"
|
| 77 |
highlighted: currentView === "scrape"
|
|
|
|
| 119 |
anchors.fill: parent
|
| 120 |
currentIndex: {
|
| 121 |
if (currentView === "dashboard") return 0;
|
| 122 |
+
if (currentView === "search") return 1;
|
| 123 |
+
if (currentView === "scrape") return 2;
|
| 124 |
+
if (currentView === "results") return 3;
|
| 125 |
+
if (currentView === "delivery") return 4;
|
| 126 |
+
if (currentView === "history") return 5;
|
| 127 |
return 0;
|
| 128 |
}
|
| 129 |
|
|
|
|
| 275 |
}
|
| 276 |
}
|
| 277 |
|
| 278 |
+
// ======== Página 1: Búsqueda por Vertical ========
|
| 279 |
+
Rectangle {
|
| 280 |
+
color: bgSecondary
|
| 281 |
+
ColumnLayout {
|
| 282 |
+
anchors.fill: parent
|
| 283 |
+
anchors.margins: 24
|
| 284 |
+
spacing: 16
|
| 285 |
+
|
| 286 |
+
Label {
|
| 287 |
+
text: "Búsqueda por Vertical"
|
| 288 |
+
font.pixelSize: 22
|
| 289 |
+
font.weight: Font.Bold
|
| 290 |
+
color: textPrimary
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
// Feedback
|
| 294 |
+
Rectangle {
|
| 295 |
+
id: searchBanner
|
| 296 |
+
Layout.fillWidth: true
|
| 297 |
+
radius: 8
|
| 298 |
+
visible: false
|
| 299 |
+
height: 40
|
| 300 |
+
Label {
|
| 301 |
+
id: searchBannerText
|
| 302 |
+
anchors.centerIn: parent
|
| 303 |
+
color: "white"
|
| 304 |
+
font.pixelSize: 13
|
| 305 |
+
}
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
// Configuración de búsqueda
|
| 309 |
+
Pane {
|
| 310 |
+
Layout.fillWidth: true
|
| 311 |
+
padding: 16
|
| 312 |
+
background: Rectangle {
|
| 313 |
+
color: bgPrimary
|
| 314 |
+
border.color: "#e2e8f0"
|
| 315 |
+
radius: 12
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
ColumnLayout {
|
| 319 |
+
anchors.fill: parent
|
| 320 |
+
spacing: 12
|
| 321 |
+
|
| 322 |
+
Label { text: "Parámetros de Búsqueda"; font.weight: Font.Bold; color: textPrimary }
|
| 323 |
+
|
| 324 |
+
RowLayout {
|
| 325 |
+
spacing: 12
|
| 326 |
+
Layout.fillWidth: true
|
| 327 |
+
|
| 328 |
+
ColumnLayout {
|
| 329 |
+
spacing: 4
|
| 330 |
+
Layout.fillWidth: true
|
| 331 |
+
Label { text: "Vertical"; font.pixelSize: 11; color: textSecondary }
|
| 332 |
+
ComboBox {
|
| 333 |
+
id: verticalCombo
|
| 334 |
+
model: ListModel { id: verticalsModel }
|
| 335 |
+
textRole: "display"
|
| 336 |
+
Layout.fillWidth: true
|
| 337 |
+
onCurrentIndexChanged: {
|
| 338 |
+
if (currentIndex >= 0 && verticalsModel.count > 0) {
|
| 339 |
+
updateSitesForVertical();
|
| 340 |
+
}
|
| 341 |
+
}
|
| 342 |
+
}
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
ColumnLayout {
|
| 346 |
+
spacing: 4
|
| 347 |
+
Layout.fillWidth: true
|
| 348 |
+
Label { text: "Sitio (opcional)"; font.pixelSize: 11; color: textSecondary }
|
| 349 |
+
ComboBox {
|
| 350 |
+
id: siteCombo
|
| 351 |
+
model: ListModel { id: sitesModel }
|
| 352 |
+
textRole: "display"
|
| 353 |
+
Layout.fillWidth: true
|
| 354 |
+
}
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
RowLayout {
|
| 359 |
+
spacing: 12
|
| 360 |
+
Layout.fillWidth: true
|
| 361 |
+
|
| 362 |
+
TextField {
|
| 363 |
+
id: searchQueryInput
|
| 364 |
+
placeholderText: "Ej: autos usados, iPhone 15, departamento en renta..."
|
| 365 |
+
Layout.fillWidth: true
|
| 366 |
+
onAccepted: runSearch()
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
Button {
|
| 370 |
+
id: searchBtn
|
| 371 |
+
text: "🔍 Buscar"
|
| 372 |
+
enabled: searchQueryInput.text.length > 0 && verticalCombo.currentIndex >= 0 && !searchSpinner.running
|
| 373 |
+
background: Rectangle {
|
| 374 |
+
radius: 8
|
| 375 |
+
color: parent.enabled ? accent : "#94a3b8"
|
| 376 |
+
}
|
| 377 |
+
contentItem: Text {
|
| 378 |
+
text: parent.text
|
| 379 |
+
color: "white"
|
| 380 |
+
font.pixelSize: 14
|
| 381 |
+
}
|
| 382 |
+
onClicked: runSearch()
|
| 383 |
+
}
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
RowLayout {
|
| 387 |
+
spacing: 8
|
| 388 |
+
BusyIndicator {
|
| 389 |
+
id: searchSpinner
|
| 390 |
+
running: false
|
| 391 |
+
Layout.preferredWidth: 20
|
| 392 |
+
Layout.preferredHeight: 20
|
| 393 |
+
}
|
| 394 |
+
Label {
|
| 395 |
+
id: searchStatusLabel
|
| 396 |
+
color: textSecondary
|
| 397 |
+
font.pixelSize: 12
|
| 398 |
+
visible: false
|
| 399 |
+
}
|
| 400 |
+
Item { Layout.fillWidth: true }
|
| 401 |
+
Button {
|
| 402 |
+
text: "↻ Recargar Verticales"
|
| 403 |
+
flat: true
|
| 404 |
+
onClicked: loadSearchVerticales()
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
}
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
// Resultados
|
| 411 |
+
Pane {
|
| 412 |
+
Layout.fillWidth: true
|
| 413 |
+
Layout.fillHeight: true
|
| 414 |
+
padding: 16
|
| 415 |
+
visible: searchResultsModel.count > 0
|
| 416 |
+
background: Rectangle {
|
| 417 |
+
color: bgPrimary
|
| 418 |
+
border.color: "#e2e8f0"
|
| 419 |
+
radius: 12
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
ColumnLayout {
|
| 423 |
+
anchors.fill: parent
|
| 424 |
+
spacing: 12
|
| 425 |
+
|
| 426 |
+
// Summary
|
| 427 |
+
RowLayout {
|
| 428 |
+
Layout.fillWidth: true
|
| 429 |
+
Label {
|
| 430 |
+
id: searchSummaryLabel
|
| 431 |
+
text: "0 resultados"
|
| 432 |
+
font.pixelSize: 14
|
| 433 |
+
font.weight: Font.Bold
|
| 434 |
+
color: textPrimary
|
| 435 |
+
}
|
| 436 |
+
Item { Layout.fillWidth: true }
|
| 437 |
+
Label {
|
| 438 |
+
id: searchAdaptersLabel
|
| 439 |
+
text: ""
|
| 440 |
+
font.pixelSize: 12
|
| 441 |
+
color: textSecondary
|
| 442 |
+
}
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
// Results list
|
| 446 |
+
ListView {
|
| 447 |
+
id: searchResultsList
|
| 448 |
+
Layout.fillWidth: true
|
| 449 |
+
Layout.fillHeight: true
|
| 450 |
+
model: ListModel { id: searchResultsModel }
|
| 451 |
+
clip: true
|
| 452 |
+
spacing: 8
|
| 453 |
+
|
| 454 |
+
delegate: Rectangle {
|
| 455 |
+
width: parent.width
|
| 456 |
+
height: {
|
| 457 |
+
// Auto height based on content
|
| 458 |
+
var base = 80;
|
| 459 |
+
if (model.description) base += 20;
|
| 460 |
+
return base;
|
| 461 |
+
}
|
| 462 |
+
radius: 8
|
| 463 |
+
color: bgSecondary
|
| 464 |
+
border.color: "#e2e8f0"
|
| 465 |
+
|
| 466 |
+
ColumnLayout {
|
| 467 |
+
anchors.fill: parent
|
| 468 |
+
anchors.margins: 12
|
| 469 |
+
spacing: 4
|
| 470 |
+
|
| 471 |
+
// Title + Source badge
|
| 472 |
+
RowLayout {
|
| 473 |
+
spacing: 8
|
| 474 |
+
Layout.fillWidth: true
|
| 475 |
+
|
| 476 |
+
Label {
|
| 477 |
+
text: model.title || "(Sin título)"
|
| 478 |
+
font.weight: Font.Bold
|
| 479 |
+
font.pixelSize: 14
|
| 480 |
+
color: textPrimary
|
| 481 |
+
elide: Text.ElideRight
|
| 482 |
+
Layout.fillWidth: true
|
| 483 |
+
}
|
| 484 |
+
|
| 485 |
+
Rectangle {
|
| 486 |
+
color: "#dbeafe"
|
| 487 |
+
radius: 4
|
| 488 |
+
height: 20
|
| 489 |
+
implicitWidth: siteLabel.implicitWidth + 8
|
| 490 |
+
Label {
|
| 491 |
+
id: siteLabel
|
| 492 |
+
text: model.source_site || "?"
|
| 493 |
+
font.pixelSize: 10
|
| 494 |
+
color: "#1e40af"
|
| 495 |
+
anchors.centerIn: parent
|
| 496 |
+
}
|
| 497 |
+
}
|
| 498 |
+
}
|
| 499 |
+
|
| 500 |
+
// Description (if available)
|
| 501 |
+
Label {
|
| 502 |
+
text: model.description || ""
|
| 503 |
+
font.pixelSize: 12
|
| 504 |
+
color: textSecondary
|
| 505 |
+
elide: Text.ElideRight
|
| 506 |
+
maximumLineCount: 2
|
| 507 |
+
visible: text.length > 0
|
| 508 |
+
wrapMode: Text.WordWrap
|
| 509 |
+
Layout.fillWidth: true
|
| 510 |
+
Layout.maximumHeight: 36
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
// Price + Rank row
|
| 514 |
+
RowLayout {
|
| 515 |
+
spacing: 12
|
| 516 |
+
Layout.fillWidth: true
|
| 517 |
+
|
| 518 |
+
Label {
|
| 519 |
+
text: model.price ? "$" + Number(model.price).toLocaleString(Qt.locale(), "f", 2) : ""
|
| 520 |
+
font.pixelSize: 16
|
| 521 |
+
font.weight: Font.Bold
|
| 522 |
+
color: "#059669"
|
| 523 |
+
visible: model.price
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
Label {
|
| 527 |
+
text: model.currency || ""
|
| 528 |
+
font.pixelSize: 11
|
| 529 |
+
color: textSecondary
|
| 530 |
+
visible: model.currency
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
Item { Layout.fillWidth: true }
|
| 534 |
+
|
| 535 |
+
Label {
|
| 536 |
+
text: "#" + (model.rank + 1)
|
| 537 |
+
font.pixelSize: 11
|
| 538 |
+
color: textSecondary
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
Button {
|
| 542 |
+
text: "Abrir"
|
| 543 |
+
flat: true
|
| 544 |
+
enabled: model.url && model.url.length > 0
|
| 545 |
+
onClicked: {
|
| 546 |
+
if (model.url) {
|
| 547 |
+
Qt.openUrlExternally(model.url);
|
| 548 |
+
}
|
| 549 |
+
}
|
| 550 |
+
contentItem: Text {
|
| 551 |
+
text: parent.text
|
| 552 |
+
color: parent.enabled ? accent : textSecondary
|
| 553 |
+
font.pixelSize: 12
|
| 554 |
+
}
|
| 555 |
+
}
|
| 556 |
+
}
|
| 557 |
+
}
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
// Empty state
|
| 561 |
+
Label {
|
| 562 |
+
anchors.centerIn: parent
|
| 563 |
+
text: "Realiza una búsqueda para ver resultados."
|
| 564 |
+
color: textSecondary
|
| 565 |
+
visible: searchResultsModel.count === 0
|
| 566 |
+
font.pixelSize: 14
|
| 567 |
+
}
|
| 568 |
+
}
|
| 569 |
+
}
|
| 570 |
+
}
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
// --- Funciones de la página de búsqueda ---
|
| 574 |
+
|
| 575 |
+
function loadSearchVerticales() {
|
| 576 |
+
var raw = python.get_verticals();
|
| 577 |
+
var data = parseJson(raw);
|
| 578 |
+
if (!data || data.error) return;
|
| 579 |
+
verticalsModel.clear();
|
| 580 |
+
for (var i = 0; i < data.length; i++) {
|
| 581 |
+
verticalsModel.append({ display: data[i], value: data[i] });
|
| 582 |
+
}
|
| 583 |
+
if (verticalsModel.count > 0) {
|
| 584 |
+
verticalCombo.currentIndex = 0;
|
| 585 |
+
}
|
| 586 |
+
}
|
| 587 |
+
|
| 588 |
+
function updateSitesForVertical() {
|
| 589 |
+
var vertical = verticalsModel.get(verticalCombo.currentIndex).value;
|
| 590 |
+
var raw = python.adapters;
|
| 591 |
+
var adapters = parseJson(raw);
|
| 592 |
+
if (!adapters) return;
|
| 593 |
+
sitesModel.clear();
|
| 594 |
+
sitesModel.append({ display: "Todos los sitios", value: "all" });
|
| 595 |
+
for (var i = 0; i < adapters.length; i++) {
|
| 596 |
+
if (adapters[i].vertical === vertical) {
|
| 597 |
+
sitesModel.append({
|
| 598 |
+
display: adapters[i].name,
|
| 599 |
+
value: adapters[i].name
|
| 600 |
+
});
|
| 601 |
+
}
|
| 602 |
+
}
|
| 603 |
+
siteCombo.currentIndex = 0;
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
function runSearch() {
|
| 607 |
+
if (!searchQueryInput.text || verticalCombo.currentIndex < 0) return;
|
| 608 |
+
|
| 609 |
+
searchSpinner.running = true;
|
| 610 |
+
searchStatusLabel.text = "Buscando...";
|
| 611 |
+
searchStatusLabel.visible = true;
|
| 612 |
+
|
| 613 |
+
var vertical = verticalsModel.get(verticalCombo.currentIndex).value;
|
| 614 |
+
var site = siteCombo.currentIndex >= 0 ? sitesModel.get(siteCombo.currentIndex).value : "all";
|
| 615 |
+
|
| 616 |
+
var raw = python.search_adapters(searchQueryInput.text, vertical, site);
|
| 617 |
+
var data = parseJson(raw);
|
| 618 |
+
|
| 619 |
+
searchSpinner.running = false;
|
| 620 |
+
|
| 621 |
+
if (!data || data.error) {
|
| 622 |
+
searchBanner.color = error;
|
| 623 |
+
searchBannerText.text = data ? data.error : "Error en búsqueda";
|
| 624 |
+
searchBanner.visible = true;
|
| 625 |
+
searchStatusLabel.text = "Error";
|
| 626 |
+
searchStatusLabel.color = error;
|
| 627 |
+
return;
|
| 628 |
+
}
|
| 629 |
+
|
| 630 |
+
// Mostrar resultados
|
| 631 |
+
searchResultsModel.clear();
|
| 632 |
+
searchSummaryLabel.text = data.total_found + " resultados";
|
| 633 |
+
searchAdaptersLabel.text = "en " + data.adapters_used + " adaptador(es)";
|
| 634 |
+
|
| 635 |
+
if (data.items) {
|
| 636 |
+
for (var i = 0; i < data.items.length; i++) {
|
| 637 |
+
searchResultsModel.append(data.items[i]);
|
| 638 |
+
}
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
searchBanner.color = success;
|
| 642 |
+
searchBannerText.text = "Búsqueda completada: " + data.total_found + " resultados";
|
| 643 |
+
searchBanner.visible = true;
|
| 644 |
+
searchStatusLabel.text = "OK";
|
| 645 |
+
searchStatusLabel.color = success;
|
| 646 |
+
|
| 647 |
+
// Auto-ocultar banner
|
| 648 |
+
searchHideTimer.start();
|
| 649 |
+
}
|
| 650 |
+
|
| 651 |
+
Timer {
|
| 652 |
+
id: searchHideTimer
|
| 653 |
+
interval: 4000
|
| 654 |
+
onTriggered: searchBanner.visible = false
|
| 655 |
+
}
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// ======== Página 2: Nuevo Scraper ========
|
| 659 |
Rectangle {
|
| 660 |
color: bgSecondary
|
| 661 |
ColumnLayout {
|
pyproject.toml
CHANGED
|
@@ -37,6 +37,7 @@ modulo1 = [
|
|
| 37 |
"uvicorn[standard]>=0.27",
|
| 38 |
"jinja2>=3.1",
|
| 39 |
"python-multipart>=0.0.6",
|
|
|
|
| 40 |
]
|
| 41 |
modulo2 = [
|
| 42 |
"PySide6>=6.6",
|
|
@@ -54,6 +55,7 @@ all = [
|
|
| 54 |
"fastapi>=0.109",
|
| 55 |
"uvicorn[standard]>=0.27",
|
| 56 |
"python-multipart>=0.0.6",
|
|
|
|
| 57 |
"PySide6>=6.6",
|
| 58 |
"httpx>=0.25",
|
| 59 |
"jinja2>=3.1",
|
|
|
|
| 37 |
"uvicorn[standard]>=0.27",
|
| 38 |
"jinja2>=3.1",
|
| 39 |
"python-multipart>=0.0.6",
|
| 40 |
+
"gradio>=4.0",
|
| 41 |
]
|
| 42 |
modulo2 = [
|
| 43 |
"PySide6>=6.6",
|
|
|
|
| 55 |
"fastapi>=0.109",
|
| 56 |
"uvicorn[standard]>=0.27",
|
| 57 |
"python-multipart>=0.0.6",
|
| 58 |
+
"gradio>=4.0",
|
| 59 |
"PySide6>=6.6",
|
| 60 |
"httpx>=0.25",
|
| 61 |
"jinja2>=3.1",
|
tests/modulo_1/test_anti_scraping.py
CHANGED
|
@@ -28,14 +28,13 @@ class TestUARotator:
|
|
| 28 |
assert seen == set(pool)
|
| 29 |
|
| 30 |
def test_circular_rotation(self) -> None:
|
| 31 |
-
"""Después de N llamadas, vuelve al primer UA."""
|
| 32 |
pool = ("A", "B")
|
| 33 |
rotator = UARotator(pool=pool)
|
| 34 |
-
|
| 35 |
-
rotator.get_ua()
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
assert rotator.get_ua() == "A"
|
| 39 |
|
| 40 |
def test_default_pool_not_empty(self) -> None:
|
| 41 |
"""El pool por defecto tiene al menos un UA."""
|
|
|
|
| 28 |
assert seen == set(pool)
|
| 29 |
|
| 30 |
def test_circular_rotation(self) -> None:
|
| 31 |
+
"""Después de N llamadas, vuelve al primer UA (cual sea)."""
|
| 32 |
pool = ("A", "B")
|
| 33 |
rotator = UARotator(pool=pool)
|
| 34 |
+
first = rotator.get_ua()
|
| 35 |
+
second = rotator.get_ua()
|
| 36 |
+
# Tras consumir todos los UAs, debe ciclar al primero
|
| 37 |
+
assert rotator.get_ua() == first
|
|
|
|
| 38 |
|
| 39 |
def test_default_pool_not_empty(self) -> None:
|
| 40 |
"""El pool por defecto tiene al menos un UA."""
|
tests/modulo_1/test_normalizer.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from modulo_1_servicio.scraping.normalizer import CanonicalItem, ResultNormalizer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class TestCanonicalItem:
|
| 11 |
+
def test_minimal_item(self) -> None:
|
| 12 |
+
"""Item con solo campos requeridos."""
|
| 13 |
+
item = CanonicalItem(source_site="test", source_url="https://example.com")
|
| 14 |
+
assert item.source_site == "test"
|
| 15 |
+
assert item.title is None
|
| 16 |
+
assert item.price is None
|
| 17 |
+
|
| 18 |
+
def test_full_item(self) -> None:
|
| 19 |
+
"""Item con todos los campos."""
|
| 20 |
+
item = CanonicalItem(
|
| 21 |
+
title="iPhone 15",
|
| 22 |
+
description="El nuevo iPhone",
|
| 23 |
+
price=999.99,
|
| 24 |
+
currency="USD",
|
| 25 |
+
url="https://example.com/iphone",
|
| 26 |
+
image_url="https://example.com/iphone.jpg",
|
| 27 |
+
date="2024-01-15",
|
| 28 |
+
location="CDMX",
|
| 29 |
+
source_site="mercadolibre",
|
| 30 |
+
source_url="https://mercadolibre.com.mx/search",
|
| 31 |
+
rank=1,
|
| 32 |
+
raw_data={"nombre": "iPhone 15", "precio": "$999.99"},
|
| 33 |
+
)
|
| 34 |
+
assert item.title == "iPhone 15"
|
| 35 |
+
assert item.price == 999.99
|
| 36 |
+
assert item.rank == 1
|
| 37 |
+
|
| 38 |
+
def test_optional_fields_default_none(self) -> None:
|
| 39 |
+
"""Campos opcionales son None por defecto."""
|
| 40 |
+
item = CanonicalItem(source_site="test", source_url="https://example.com")
|
| 41 |
+
assert item.image_url is None
|
| 42 |
+
assert item.location is None
|
| 43 |
+
assert item.raw_data == {}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestNormalizePrice:
|
| 47 |
+
"""Tests para _to_float (transformación de precios)."""
|
| 48 |
+
|
| 49 |
+
def test_none_returns_none(self) -> None:
|
| 50 |
+
assert ResultNormalizer._to_float(None) is None
|
| 51 |
+
|
| 52 |
+
def test_int_converted(self) -> None:
|
| 53 |
+
assert ResultNormalizer._to_float(100) == 100.0
|
| 54 |
+
|
| 55 |
+
def test_float_passthrough(self) -> None:
|
| 56 |
+
assert ResultNormalizer._to_float(99.99) == 99.99
|
| 57 |
+
|
| 58 |
+
def test_string_with_dollar(self) -> None:
|
| 59 |
+
assert ResultNormalizer._to_float("$1,234.56") == 1234.56
|
| 60 |
+
|
| 61 |
+
def test_string_with_euro(self) -> None:
|
| 62 |
+
assert ResultNormalizer._to_float("€ 50,00") == 50.00
|
| 63 |
+
|
| 64 |
+
def test_string_with_peso(self) -> None:
|
| 65 |
+
assert ResultNormalizer._to_float("$ 25,000 MXN") == 25000.0
|
| 66 |
+
|
| 67 |
+
def test_invalid_string_returns_none(self) -> None:
|
| 68 |
+
assert ResultNormalizer._to_float("gratis") is None
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class TestNormalizeURL:
|
| 72 |
+
"""Tests para _extract_url."""
|
| 73 |
+
|
| 74 |
+
def test_https_url(self) -> None:
|
| 75 |
+
assert ResultNormalizer._extract_url("https://example.com") == "https://example.com"
|
| 76 |
+
|
| 77 |
+
def test_http_url(self) -> None:
|
| 78 |
+
assert ResultNormalizer._extract_url("http://example.com") == "http://example.com"
|
| 79 |
+
|
| 80 |
+
def test_relative_path(self) -> None:
|
| 81 |
+
assert ResultNormalizer._extract_url("/producto/123") == "/producto/123"
|
| 82 |
+
|
| 83 |
+
def test_none_returns_none(self) -> None:
|
| 84 |
+
assert ResultNormalizer._extract_url(None) is None
|
| 85 |
+
|
| 86 |
+
def test_random_text_returns_none(self) -> None:
|
| 87 |
+
assert ResultNormalizer._extract_url("not a url") is None
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class TestResultNormalizer:
|
| 91 |
+
"""Tests completos para ResultNormalizer.normalize()."""
|
| 92 |
+
|
| 93 |
+
def test_empty_raw_items(self) -> None:
|
| 94 |
+
"""Lista vacía retorna lista vacía."""
|
| 95 |
+
normalizer = ResultNormalizer()
|
| 96 |
+
result = normalizer.normalize(
|
| 97 |
+
canonical_map={"title": "nombre"},
|
| 98 |
+
raw_items=[],
|
| 99 |
+
source_site="test",
|
| 100 |
+
source_url="https://example.com",
|
| 101 |
+
)
|
| 102 |
+
assert result == []
|
| 103 |
+
|
| 104 |
+
def test_basic_normalization(self) -> None:
|
| 105 |
+
"""Mapeo básico de campos funciona."""
|
| 106 |
+
normalizer = ResultNormalizer()
|
| 107 |
+
raw = [
|
| 108 |
+
{"nombre": "iPhone 15", "precio": "$999.99"},
|
| 109 |
+
{"nombre": "Samsung S24", "precio": "$899.00"},
|
| 110 |
+
]
|
| 111 |
+
result = normalizer.normalize(
|
| 112 |
+
canonical_map={"title": "nombre", "price": "precio"},
|
| 113 |
+
raw_items=raw,
|
| 114 |
+
source_site="test_site",
|
| 115 |
+
source_url="https://example.com/search",
|
| 116 |
+
start_rank=0,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
assert len(result) == 2
|
| 120 |
+
assert result[0].title == "iPhone 15"
|
| 121 |
+
assert result[0].price == 999.99
|
| 122 |
+
assert result[0].source_site == "test_site"
|
| 123 |
+
assert result[0].rank == 0
|
| 124 |
+
assert result[1].title == "Samsung S24"
|
| 125 |
+
assert result[1].price == 899.00
|
| 126 |
+
assert result[1].rank == 1
|
| 127 |
+
|
| 128 |
+
def test_partial_fields(self) -> None:
|
| 129 |
+
"""Campos faltantes quedan como None."""
|
| 130 |
+
normalizer = ResultNormalizer()
|
| 131 |
+
raw = [
|
| 132 |
+
{"nombre": "Producto A"}, # Sin precio
|
| 133 |
+
]
|
| 134 |
+
result = normalizer.normalize(
|
| 135 |
+
canonical_map={"title": "nombre", "price": "precio"},
|
| 136 |
+
raw_items=raw,
|
| 137 |
+
source_site="test",
|
| 138 |
+
source_url="https://example.com",
|
| 139 |
+
)
|
| 140 |
+
assert result[0].title == "Producto A"
|
| 141 |
+
assert result[0].price is None
|
| 142 |
+
|
| 143 |
+
def test_url_extraction(self) -> None:
|
| 144 |
+
"""Urls se extraen correctamente."""
|
| 145 |
+
normalizer = ResultNormalizer()
|
| 146 |
+
raw = [{"link": "https://example.com/item/1", "img": "/images/photo.jpg"}]
|
| 147 |
+
result = normalizer.normalize(
|
| 148 |
+
canonical_map={"url": "link", "image_url": "img"},
|
| 149 |
+
raw_items=raw,
|
| 150 |
+
source_site="test",
|
| 151 |
+
source_url="https://example.com",
|
| 152 |
+
)
|
| 153 |
+
assert result[0].url == "https://example.com/item/1"
|
| 154 |
+
assert result[0].image_url == "/images/photo.jpg"
|
| 155 |
+
|
| 156 |
+
def test_raw_data_preserved(self) -> None:
|
| 157 |
+
"""Los datos originales se preservan en raw_data."""
|
| 158 |
+
normalizer = ResultNormalizer()
|
| 159 |
+
raw = [{"nombre": "Test", "precio": "$10", "extra": "info"}]
|
| 160 |
+
result = normalizer.normalize(
|
| 161 |
+
canonical_map={"title": "nombre", "price": "precio"},
|
| 162 |
+
raw_items=raw,
|
| 163 |
+
source_site="test",
|
| 164 |
+
source_url="https://example.com",
|
| 165 |
+
)
|
| 166 |
+
assert result[0].raw_data == {"nombre": "Test", "precio": "$10", "extra": "info"}
|
| 167 |
+
assert result[0].raw_data["extra"] == "info"
|
| 168 |
+
|
| 169 |
+
def test_rank_increment(self) -> None:
|
| 170 |
+
"""El ranking se incrementa correctamente con start_rank."""
|
| 171 |
+
normalizer = ResultNormalizer()
|
| 172 |
+
raw = [{"n": "A"}, {"n": "B"}, {"n": "C"}]
|
| 173 |
+
result = normalizer.normalize(
|
| 174 |
+
canonical_map={"title": "n"},
|
| 175 |
+
raw_items=raw,
|
| 176 |
+
source_site="test",
|
| 177 |
+
source_url="https://example.com",
|
| 178 |
+
start_rank=10,
|
| 179 |
+
)
|
| 180 |
+
assert result[0].rank == 10
|
| 181 |
+
assert result[1].rank == 11
|
| 182 |
+
assert result[2].rank == 12
|
| 183 |
+
|
| 184 |
+
def test_description_field(self) -> None:
|
| 185 |
+
"""Campo description se mapea como texto."""
|
| 186 |
+
normalizer = ResultNormalizer()
|
| 187 |
+
raw = [{"desc": "Un producto excelente con muchas características"}]
|
| 188 |
+
result = normalizer.normalize(
|
| 189 |
+
canonical_map={"description": "desc"},
|
| 190 |
+
raw_items=raw,
|
| 191 |
+
source_site="test",
|
| 192 |
+
source_url="https://example.com",
|
| 193 |
+
)
|
| 194 |
+
assert result[0].description == "Un producto excelente con muchas características"
|