py97 lines4.2 KB
| 1 | """Fail-soft local photo checks for auction listings.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import base64 |
| 6 | import io |
| 7 | import json |
| 8 | import logging |
| 9 | import os |
| 10 | from dataclasses import dataclass |
| 11 | from typing import Any |
| 12 | from urllib.parse import urljoin |
| 13 | |
| 14 | import requests |
| 15 | from PIL import Image |
| 16 | |
| 17 | LOG = logging.getLogger(__name__) |
| 18 | PROMPT = """Identify the primary product shown in these auction photos. Return JSON only: |
| 19 | {"brand":"","exact_model":"","product_type":"","cpu":"","key_specs":{},"condition_notes":""}. |
| 20 | Do not guess a model number; use an empty string when it cannot be read.""" |
| 21 | |
| 22 | |
| 23 | @dataclass(frozen=True) |
| 24 | class VisionConfig: |
| 25 | host: str = os.environ.get("VISION_HOST", "").rstrip("/") |
| 26 | model: str = os.environ.get("VISION_MODEL", "qwen2.5vl:7b") |
| 27 | num_ctx: int = 16384 |
| 28 | max_px: int = 896 |
| 29 | max_photos: int = 8 |
| 30 | timeout: float = 120.0 |
| 31 | num_predict: int = 700 |
| 32 | |
| 33 | |
| 34 | def photo_urls(detail: dict[str, Any]) -> list[str]: |
| 35 | """Build normalized photo URLs from the listing-detail response.""" |
| 36 | server = str(detail.get("imageServer") or "") |
| 37 | paths = str(detail.get("imageUrlString") or detail.get("imageUrls") or "") |
| 38 | if not server or not paths: |
| 39 | return [] |
| 40 | urls = [urljoin(server.rstrip("/") + "/", raw.strip().replace("\\", "/").lstrip("/")) for raw in paths.split(";") if raw.strip()] |
| 41 | return list(dict.fromkeys(urls)) |
| 42 | |
| 43 | |
| 44 | def downscale_jpeg(image_bytes: bytes, max_px: int) -> str: |
| 45 | """Encode an image as a bounded JPEG for the local vision request.""" |
| 46 | with Image.open(io.BytesIO(image_bytes)) as image: |
| 47 | image = image.convert("RGB") |
| 48 | image.thumbnail((max_px, max_px), Image.Resampling.LANCZOS) |
| 49 | output = io.BytesIO() |
| 50 | image.save(output, format="JPEG", quality=85, optimize=True) |
| 51 | return base64.b64encode(output.getvalue()).decode("ascii") |
| 52 | |
| 53 | |
| 54 | def parse_response(content: str | dict[str, Any]) -> dict[str, Any]: |
| 55 | """Normalize the JSON-only response returned by the local model.""" |
| 56 | parsed = content if isinstance(content, dict) else json.loads((content or "").strip().removeprefix("```json").removesuffix("```").strip()) |
| 57 | if not isinstance(parsed, dict): |
| 58 | raise ValueError("vision response was not a JSON object") |
| 59 | return {key: parsed.get(key) or "" for key in ("brand", "exact_model", "product_type", "cpu", "condition_notes")} | {"key_specs": parsed.get("key_specs") or {}} |
| 60 | |
| 61 | |
| 62 | class PhotoChecker: |
| 63 | """Optional local vision client; an offline host becomes a row status.""" |
| 64 | |
| 65 | def __init__(self, config: VisionConfig | None = None, *, http: Any = requests) -> None: |
| 66 | self.config = config or VisionConfig() |
| 67 | self.http = http |
| 68 | |
| 69 | def available(self) -> bool: |
| 70 | if not self.config.host: |
| 71 | return False |
| 72 | try: |
| 73 | response = self.http.get(f"{self.config.host}/api/tags", timeout=min(10.0, self.config.timeout)) |
| 74 | return bool(response.ok) |
| 75 | except Exception as exc: |
| 76 | LOG.info("photo check unavailable: %s", exc) |
| 77 | return False |
| 78 | |
| 79 | def check(self, detail: dict[str, Any]) -> dict[str, Any]: |
| 80 | """Return `unavailable` rather than fail the daily run when the host is off.""" |
| 81 | if not self.available(): |
| 82 | return {"status": "unavailable", "note": "not photo-checked"} |
| 83 | try: |
| 84 | images = [] |
| 85 | for url in photo_urls(detail)[: self.config.max_photos]: |
| 86 | response = self.http.get(url, timeout=self.config.timeout) |
| 87 | response.raise_for_status() |
| 88 | images.append(downscale_jpeg(response.content, self.config.max_px)) |
| 89 | if not images: |
| 90 | return {"status": "skipped", "note": "no photos"} |
| 91 | 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}} |
| 92 | response = self.http.post(f"{self.config.host}/api/chat", json=payload, timeout=self.config.timeout) |
| 93 | response.raise_for_status() |
| 94 | return {"status": "ok", "result": parse_response((response.json().get("message") or {}).get("content", ""))} |
| 95 | except Exception as exc: |
| 96 | LOG.warning("photo check failed: %s", exc) |
| 97 | return {"status": "error", "note": "not photo-checked"} |