"""Extract and read card images through the approved multimodal model.""" from __future__ import annotations import json import re from typing import Any from larkx.media import download, message_resource_url IMAGE_KEY_PATTERN = re.compile(rb"img_v3_[A-Za-z0-9_-]+") def extract_card_image_keys(data: dict) -> list[str]: """Find image keys in JSON fields and binary rich-text properties.""" keys = [] def add(value): if isinstance(value, bytes): candidates = IMAGE_KEY_PATTERN.findall(value) elif isinstance(value, str) and value.startswith("img_v3_"): candidates = [value] else: candidates = [] for candidate in candidates: key = candidate.decode() if isinstance(candidate, bytes) else candidate if key not in keys: keys.append(key) def walk(value): if isinstance(value, dict): for key, item in value.items(): if key in {"imageKey", "image_key", "key", "property"}: add(item) else: walk(item) elif isinstance(value, list): for item in value: walk(item) walk(data) return keys def complete_image_read( client: Any, image: bytes, content_type: str, ) -> str: """Read image text through MagpieClient.complete_with_image.""" mime = content_type if content_type.startswith("image/") else "image/png" return client.complete_with_image(image, mime) def enrich_card_images( client: Any, ai_client: Any, rows: list[Any], max_images: int = 3, ) -> dict[str, int]: """Best-effort image enrichment for existing message rows, bounded per day.""" stats = {"candidates": 0, "enriched": 0, "failed": 0} for row in rows: if stats["candidates"] >= max_images: break if ( getattr(row, "msg_type", None) != 14 or not getattr(row, "position", 0) or "[图片]" not in (getattr(row, "content", "") or "") ): continue stats["candidates"] += 1 try: messages = client.pull_history( row.chat_id, [row.position], visible_only=True ) if not messages: raise ValueError("empty history response") data = messages[0].get("content_data") or {} keys = extract_card_image_keys(data) if not keys: raise ValueError("no image key") image, content_type = download( client.auth, message_resource_url( row.msg_id, keys[0], row.chat_id, host=client.auth.region.file_host ), ) text = complete_image_read(ai_client, image, content_type).strip() if text: row.content = f"{row.content or ''}\n[图片文字] {text}" stats["enriched"] += 1 except Exception: # noqa: BLE001 - isolate unavailable resources without message content stats["failed"] += 1 return stats