Files
Lark-Snooper/snooper_card_images.py
Benature 81b6ff7a39 feat: 图片下载与数据目录本地化
- 新增 download_images.py: 批量下载消息图片到 downloads/images/
- 数据库移至 downloads/messages.db,SnifferStorage 默认使用项目目录
- 图片默认保存到 downloads/images/,支持 --out-dir 自定义
- .gitignore 排除 downloads/ 避免提交二进制文件
- 补充腾讯会议号过滤 prompt
- 补充 Obsidian 文档 is_read frontmatter
2026-11-15 20:07:24 +08:00

96 lines
3.1 KiB
Python

"""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