"""Standalone FastAPI-сервис: headless-скрапер формы расчёта ПЭК. Деплоится в Hugging Face Space (Docker SDK, порт 7860). Один полезный эндпоинт POST /scrape: принимает агрегированные параметры груза и набор CSS-селекторов pecom.ru, отдаёт {price_rub, days_min, days_max}. Авторизация — Bearer-токен (env PEK_SCRAPER_TOKEN), общий с основным FastAPI на Vercel. Stateless: ни БД, ни кэша — кэширование живёт на стороне основного приложения (PekCachedQuote, TTL 24ч). """ from __future__ import annotations import logging import os import re from decimal import Decimal, InvalidOperation from typing import Annotated from fastapi import Depends, FastAPI, Header, HTTPException from pydantic import BaseModel, Field logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) app = FastAPI(title="PEK Scraper", version="1.0.0") _PRICE_DIGITS = re.compile(r"[\d\s.,]+") _DAYS_RANGE = re.compile(r"(\d+)\s*[-–—]\s*(\d+)") _DAYS_SINGLE = re.compile(r"(\d+)") class ScrapeRequest(BaseModel): """Параметры запроса к ПЭК. Селекторы передаются клиентом — менять без передеплоя.""" city: str = Field(..., min_length=1, max_length=100) weight_kg: str volume_m3: str places_count: int = Field(..., ge=1, le=1000) selectors: dict[str, str] class ScrapeResponse(BaseModel): price_rub: str days_min: int days_max: int async def verify_token(authorization: Annotated[str, Header()] = "") -> None: """Проверяет Bearer-токен из заголовка против env PEK_SCRAPER_TOKEN.""" expected = os.environ.get("PEK_SCRAPER_TOKEN", "") if not expected: raise HTTPException(status_code=503, detail="PEK_SCRAPER_TOKEN не задан в env") if authorization != f"Bearer {expected}": raise HTTPException(status_code=401, detail="invalid token") def _parse_price_rub(text: str) -> Decimal: if not text: raise ValueError("пустой текст цены") match = _PRICE_DIGITS.search(text) if not match: raise ValueError(f"не нашёл цифр в цене: {text!r}") cleaned = match.group(0).strip().replace(" ", "").replace(" ", "").replace(",", ".") if cleaned.count(".") > 1: head, _, tail = cleaned.rpartition(".") cleaned = head.replace(".", "") + "." + tail try: return Decimal(cleaned) except InvalidOperation as exc: raise ValueError(f"не распарсил цену: {text!r}") from exc def _parse_days_range(text: str) -> tuple[int, int]: if not text: raise ValueError("пустой текст срока") m = _DAYS_RANGE.search(text) if m: return int(m.group(1)), int(m.group(2)) m = _DAYS_SINGLE.search(text) if m: n = int(m.group(1)) return n, n raise ValueError(f"не распарсил срок: {text!r}") _PEK_FORM_URL = "https://pecom.ru/services-are/shipping-request/" _DEFAULT_TIMEOUT_MS = 15000 @app.get("/health") async def health() -> dict[str, bool]: return {"ok": True} @app.post("/scrape", response_model=ScrapeResponse, dependencies=[Depends(verify_token)]) async def scrape(req: ScrapeRequest) -> ScrapeResponse: """Открывает форму pecom.ru, заполняет, парсит результат.""" try: from playwright.async_api import ( # type: ignore[import-not-found] TimeoutError as PlaywrightTimeoutError, ) from playwright.async_api import async_playwright except ImportError as exc: raise HTTPException(status_code=503, detail=f"playwright not installed: {exc}") from exc sel = req.selectors try: async with async_playwright() as pw: browser = await pw.chromium.launch(headless=True) try: page = await browser.new_page() page.set_default_timeout(_DEFAULT_TIMEOUT_MS) await page.goto(_PEK_FORM_URL) await page.fill(sel["from_city"], "Алматы") await page.fill(sel["to_city"], req.city) await page.fill(sel["weight"], req.weight_kg) await page.fill(sel["volume"], req.volume_m3) await page.fill(sel["places"], str(req.places_count)) await page.click(sel["submit"]) await page.wait_for_selector(sel["result_price"], timeout=_DEFAULT_TIMEOUT_MS) price_text = (await page.text_content(sel["result_price"])) or "" days_text = (await page.text_content(sel["result_days"])) or "" finally: await browser.close() except PlaywrightTimeoutError as exc: logger.warning("PEK form timeout for %s: %s", req.city, exc) raise HTTPException(status_code=502, detail=f"pek timeout: {exc}") from exc except KeyError as exc: raise HTTPException(status_code=400, detail=f"missing selector: {exc}") from exc except Exception as exc: logger.warning("PEK scrape failed for %s: %s", req.city, exc) raise HTTPException(status_code=502, detail=f"pek scrape failed: {exc}") from exc try: price = _parse_price_rub(price_text) days_min, days_max = _parse_days_range(days_text) except ValueError as exc: raise HTTPException(status_code=502, detail=f"parse failed: {exc}") from exc return ScrapeResponse(price_rub=str(price), days_min=days_min, days_max=days_max)