Spaces:
Sleeping
Sleeping
File size: 5,874 Bytes
42db121 c4d0b23 42db121 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | """Cliente HTTP para comunicarse con el Módulo 1 (Servicio de Scraping).
Esta es la API layer que será reutilizada por Flutter en el futuro.
NO tiene dependencias de Qt — solo Python puro con httpx.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import httpx
@dataclass
class ScrapeResponse:
"""Respuesta de una operación de scraping."""
operation_id: str
status: str
total_found: int
total_errors: int
endpoint: str
@dataclass
class ResultsResponse:
"""Resultados de una operación de scraping."""
operation_id: str
source: str
total_found: int
errors: list[str]
elapsed_seconds: float | None
items: list[dict[str, Any]]
class ScrapperClient:
"""Cliente HTTP para el servicio de scraping.
Preparado para migración a Flutter:
- Mismos endpoints, mismo payload
- En Flutter: reemplazar httpx por http package
"""
def __init__(self, base_url: str = "http://localhost:8000") -> None:
self.base_url = base_url.rstrip("/")
self._client = httpx.Client(timeout=60.0)
def health(self) -> bool:
"""Verifica que el servicio esté activo."""
try:
r = self._client.get(f"{self.base_url}/api/health")
return r.status_code == 200
except Exception:
return False
def run_scrape(self, config: dict[str, Any]) -> ScrapeResponse:
"""Envía una configuración de scraping al servicio.
Args:
config: Diccionario con la configuración (source, fields, filters, etc.)
Returns:
ScrapeResponse con el ID de la operación.
"""
r = self._client.post(
f"{self.base_url}/api/scrape",
json=config,
)
r.raise_for_status()
data = r.json()
return ScrapeResponse(
operation_id=data["operation_id"],
status=data["status"],
total_found=data["total_found"],
total_errors=data["total_errors"],
endpoint=data["endpoint"],
)
def get_results(self, operation_id: str) -> ResultsResponse:
"""Obtiene los resultados de una operación."""
r = self._client.get(
f"{self.base_url}/api/results/{operation_id}"
)
r.raise_for_status()
data = r.json()
return ResultsResponse(
operation_id=data["operation_id"],
source=data["source"],
total_found=data["total_found"],
errors=data["errors"],
elapsed_seconds=data["elapsed_seconds"],
items=data["items"],
)
def get_results_web(self, operation_id: str) -> str:
"""Obtiene la página HTML de resultados."""
r = self._client.get(
f"{self.base_url}/api/results/{operation_id}/web"
)
r.raise_for_status()
return r.text
def deliver_results(
self,
operation_id: str,
emails: list[str] | None = None,
whatsapp_numbers: list[str] | None = None,
generate_web: bool = True,
) -> dict[str, Any]:
"""Solicita la entrega de resultados por los canales configurados."""
payload: dict[str, Any] = {"generate_web": generate_web}
if emails:
payload["emails"] = emails
if whatsapp_numbers:
payload["whatsapp_numbers"] = whatsapp_numbers
r = self._client.post(
f"{self.base_url}/api/deliver/{operation_id}",
json=payload,
)
r.raise_for_status()
return r.json()
def send_whatsapp_activation(
self, email: str, phone: str
) -> dict[str, Any]:
"""Solicita el envío de email de activación de WhatsApp."""
r = self._client.post(
f"{self.base_url}/api/whatsapp/send-activation",
json={"email": email, "phone": phone},
)
r.raise_for_status()
return r.json()
# --- Fase 2: Búsqueda por adaptadores ---
def list_adapters(self, vertical: str | None = None) -> list[dict[str, Any]]:
"""Obtiene la lista de adaptadores disponibles.
Args:
vertical: Opcional, filtrar por vertical.
Returns:
Lista de adaptadores con su configuración.
"""
params = {}
if vertical:
params["vertical"] = vertical
r = self._client.get(
f"{self.base_url}/api/adapters",
params=params,
)
r.raise_for_status()
data = r.json()
return data.get("adapters", [])
def list_verticals(self) -> list[str]:
"""Obtiene la lista de verticales disponibles.
Returns:
Lista de nombres de vertical únicos.
"""
adapters = self.list_adapters()
verticals = sorted({a.get("vertical", "unknown") for a in adapters})
return verticals
def search(
self,
query: str,
vertical: str,
site: str | None = None,
max_pages: int = 1,
) -> dict[str, Any]:
"""Ejecuta una búsqueda multi-adaptador.
Args:
query: Término de búsqueda.
vertical: Vertical a buscar.
site: Opcional, filtrar a un adaptador específico.
max_pages: Páginas por adaptador.
Returns:
Resultados de búsqueda con items normalizados.
"""
payload: dict[str, Any] = {
"query": query,
"vertical": vertical,
"max_pages": max_pages,
}
if site:
payload["site"] = site
r = self._client.post(
f"{self.base_url}/api/search",
json=payload,
)
r.raise_for_status()
return r.json()
def close(self) -> None:
self._client.close()
|