"""Fail-soft local photo checks for auction listings.""" from __future__ import annotations import base64 import io import json import logging import os from dataclasses import dataclass from typing import Any from urllib.parse import urljoin import requests from PIL import Image LOG = logging.getLogger(__name__) PROMPT = """Identify the primary product shown in these auction photos. Return JSON only: {"brand":"","exact_model":"","product_type":"","cpu":"","key_specs":{},"condition_notes":""}. Do not guess a model number; use an empty string when it cannot be read.""" @dataclass(frozen=True) class VisionConfig: host: str = os.environ.get("VISION_HOST", "").rstrip("/") model: str = os.environ.get("VISION_MODEL", "qwen2.5vl:7b") num_ctx: int = 16384 max_px: int = 896 max_photos: int = 8 timeout: float = 120.0 num_predict: int = 700 def photo_urls(detail: dict[str, Any]) -> list[str]: """Build normalized photo URLs from the listing-detail response.""" server = str(detail.get("imageServer") or "") paths = str(detail.get("imageUrlString") or detail.get("imageUrls") or "") if not server or not paths: return [] urls = [urljoin(server.rstrip("/") + "/", raw.strip().replace("\\", "/").lstrip("/")) for raw in paths.split(";") if raw.strip()] return list(dict.fromkeys(urls)) def downscale_jpeg(image_bytes: bytes, max_px: int) -> str: """Encode an image as a bounded JPEG for the local vision request.""" with Image.open(io.BytesIO(image_bytes)) as image: image = image.convert("RGB") image.thumbnail((max_px, max_px), Image.Resampling.LANCZOS) output = io.BytesIO() image.save(output, format="JPEG", quality=85, optimize=True) return base64.b64encode(output.getvalue()).decode("ascii") def parse_response(content: str | dict[str, Any]) -> dict[str, Any]: """Normalize the JSON-only response returned by the local model.""" parsed = content if isinstance(content, dict) else json.loads((content or "").strip().removeprefix("```json").removesuffix("```").strip()) if not isinstance(parsed, dict): raise ValueError("vision response was not a JSON object") return {key: parsed.get(key) or "" for key in ("brand", "exact_model", "product_type", "cpu", "condition_notes")} | {"key_specs": parsed.get("key_specs") or {}} class PhotoChecker: """Optional local vision client; an offline host becomes a row status.""" def __init__(self, config: VisionConfig | None = None, *, http: Any = requests) -> None: self.config = config or VisionConfig() self.http = http def available(self) -> bool: if not self.config.host: return False try: response = self.http.get(f"{self.config.host}/api/tags", timeout=min(10.0, self.config.timeout)) return bool(response.ok) except Exception as exc: LOG.info("photo check unavailable: %s", exc) return False def check(self, detail: dict[str, Any]) -> dict[str, Any]: """Return `unavailable` rather than fail the daily run when the host is off.""" if not self.available(): return {"status": "unavailable", "note": "not photo-checked"} try: images = [] for url in photo_urls(detail)[: self.config.max_photos]: response = self.http.get(url, timeout=self.config.timeout) response.raise_for_status() images.append(downscale_jpeg(response.content, self.config.max_px)) if not images: return {"status": "skipped", "note": "no photos"} payload = {"model": self.config.model, "stream": False, "format": "json", "messages": [{"role": "user", "content": PROMPT, "images": images}], "options": {"temperature": 0, "num_ctx": self.config.num_ctx, "num_predict": self.config.num_predict}} response = self.http.post(f"{self.config.host}/api/chat", json=payload, timeout=self.config.timeout) response.raise_for_status() return {"status": "ok", "result": parse_response((response.json().get("message") or {}).get("content", ""))} except Exception as exc: LOG.warning("photo check failed: %s", exc) return {"status": "error", "note": "not photo-checked"}