- 新增 download_images.py: 批量下载消息图片到 downloads/images/ - 数据库移至 downloads/messages.db,SnifferStorage 默认使用项目目录 - 图片默认保存到 downloads/images/,支持 --out-dir 自定义 - .gitignore 排除 downloads/ 避免提交二进制文件 - 补充腾讯会议号过滤 prompt - 补充 Obsidian 文档 is_read frontmatter
348 lines
12 KiB
Python
348 lines
12 KiB
Python
"""Download every video and enrich summaries with frames and local audio transcripts."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import math
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
import requests
|
|
from larkx.media import extract_resource_key, message_resource_url
|
|
|
|
DEFAULT_VIDEO_DIR = Path("~/.larkx/videos")
|
|
DEFAULT_ANALYSIS_DIR = Path("~/.larkx/video-analysis")
|
|
DEFAULT_TRANSCRIPTION_MODEL = "mlx-community/whisper-large-v3-turbo"
|
|
ANALYSIS_VERSION = 1
|
|
|
|
|
|
class VideoError(RuntimeError):
|
|
"""A video could not be downloaded or read without exposing its content."""
|
|
|
|
|
|
def _message_data(row: Any) -> dict:
|
|
try:
|
|
data = json.loads(getattr(row, "content_data", "") or "{}")
|
|
except (TypeError, ValueError) as exc:
|
|
raise VideoError("invalid video content_data") from exc
|
|
if not isinstance(data, dict):
|
|
raise VideoError("invalid video content_data")
|
|
return data
|
|
|
|
|
|
def video_path(row: Any, directory: Path | str = DEFAULT_VIDEO_DIR) -> Path:
|
|
"""Use a stable, non-descriptive local filename."""
|
|
data = _message_data(row)
|
|
suffix = Path(str(data.get("name") or "")).suffix.lower()
|
|
if not re.fullmatch(r"\.[a-z0-9]{1,8}", suffix):
|
|
suffix = {
|
|
"video/quicktime": ".mov",
|
|
"video/webm": ".webm",
|
|
"video/x-matroska": ".mkv",
|
|
}.get(str(data.get("mime") or ""), ".mp4")
|
|
return Path(directory).expanduser() / f"{row.msg_id}{suffix}"
|
|
|
|
|
|
def _download_resumable(
|
|
auth: Any,
|
|
url: str,
|
|
path: Path,
|
|
max_bytes: int,
|
|
attempts: int = 4,
|
|
) -> None:
|
|
"""Resume interrupted large downloads without logging URLs or response bodies."""
|
|
last_error = None
|
|
for attempt in range(attempts):
|
|
existing = path.stat().st_size if path.exists() else 0
|
|
headers = {"Range": f"bytes={existing}-"} if existing else {}
|
|
try:
|
|
with requests.get(
|
|
url,
|
|
cookies=auth.cookies,
|
|
headers=headers,
|
|
timeout=(30, 120),
|
|
stream=True,
|
|
) as response:
|
|
response.raise_for_status()
|
|
append = bool(existing and response.status_code == 206)
|
|
mode = "ab" if append else "wb"
|
|
written = existing if append else 0
|
|
expected = None
|
|
content_length = response.headers.get("content-length")
|
|
if content_length and content_length.isdigit():
|
|
expected = written + int(content_length)
|
|
with path.open(mode) as output:
|
|
for chunk in response.iter_content(1024 * 1024):
|
|
if not chunk:
|
|
continue
|
|
written += len(chunk)
|
|
if written > max_bytes:
|
|
raise VideoError("video exceeds the download size limit")
|
|
output.write(chunk)
|
|
if expected is not None and written != expected:
|
|
raise VideoError("incomplete video download")
|
|
if written == 0:
|
|
raise VideoError("empty video download")
|
|
path.chmod(0o600)
|
|
return
|
|
except (OSError, requests.RequestException, VideoError) as exc:
|
|
last_error = exc
|
|
if attempt + 1 < attempts:
|
|
time.sleep(2**attempt)
|
|
raise VideoError("video download failed after retries") from last_error
|
|
|
|
|
|
def ensure_video_downloaded(
|
|
client: Any,
|
|
row: Any,
|
|
directory: Path | str = DEFAULT_VIDEO_DIR,
|
|
max_bytes: int = 2 * 1024 * 1024 * 1024,
|
|
) -> tuple[Path, bool]:
|
|
"""Download one video atomically; return its path and whether it was new."""
|
|
path = video_path(row, directory)
|
|
if path.exists() and path.stat().st_size > 0:
|
|
return path, False
|
|
data = _message_data(row)
|
|
key = extract_resource_key(15, data)
|
|
if not key:
|
|
raise VideoError("video resource key is missing")
|
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
try:
|
|
path.parent.chmod(0o700)
|
|
except OSError:
|
|
pass
|
|
temporary = path.with_suffix(path.suffix + ".part")
|
|
url = message_resource_url(
|
|
row.msg_id, key, row.chat_id, host=client.auth.region.file_host
|
|
)
|
|
_download_resumable(client.auth, url, temporary, max_bytes)
|
|
os.replace(temporary, path)
|
|
path.chmod(0o600)
|
|
return path, True
|
|
|
|
|
|
def _probe_duration(path: Path) -> float:
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"ffprobe", "-v", "error", "-show_entries", "format=duration",
|
|
"-of", "default=noprint_wrappers=1:nokey=1", str(path),
|
|
],
|
|
capture_output=True,
|
|
check=True,
|
|
timeout=60,
|
|
)
|
|
return max(0.0, float(result.stdout.decode().strip()))
|
|
except (OSError, ValueError, subprocess.SubprocessError) as exc:
|
|
raise VideoError("ffprobe could not read video duration") from exc
|
|
|
|
|
|
def video_duration(row: Any, path: Path) -> float:
|
|
milliseconds = _message_data(row).get("duration") or 0
|
|
try:
|
|
duration = float(milliseconds) / 1000
|
|
except (TypeError, ValueError):
|
|
duration = 0.0
|
|
return duration if duration > 0 else _probe_duration(path)
|
|
|
|
|
|
def frame_timestamps(duration: float, max_frames: int = 12) -> list[float]:
|
|
"""Cover the whole video, including its final portion, with bounded frames."""
|
|
if max_frames < 1:
|
|
raise ValueError("max_frames must be positive")
|
|
if duration <= 0:
|
|
return [0.0]
|
|
count = min(max_frames, max(1, math.ceil(duration / 30)))
|
|
return [
|
|
min(duration - 0.05, max(0.0, duration * (index + 0.5) / count))
|
|
for index in range(count)
|
|
]
|
|
|
|
|
|
def extract_video_frames(
|
|
path: Path,
|
|
duration: float,
|
|
max_frames: int = 12,
|
|
) -> list[tuple[float, bytes]]:
|
|
"""Extract JPEG frames across the full timeline; all videos are handled by caller."""
|
|
frames = []
|
|
errors = []
|
|
for timestamp in frame_timestamps(duration, max_frames):
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"ffmpeg", "-v", "error", "-ss", f"{timestamp:.3f}", "-i", str(path),
|
|
"-frames:v", "1", "-vf", "scale='min(960,iw)':-2",
|
|
"-q:v", "3", "-f", "image2pipe", "-vcodec", "mjpeg", "pipe:1",
|
|
],
|
|
capture_output=True,
|
|
check=True,
|
|
timeout=90,
|
|
)
|
|
if not result.stdout:
|
|
raise VideoError("empty video frame")
|
|
frames.append((timestamp, result.stdout))
|
|
except (OSError, subprocess.SubprocessError, VideoError) as exc:
|
|
errors.append(exc)
|
|
if not frames:
|
|
raise VideoError("ffmpeg could not extract any video frame") from (
|
|
errors[-1] if errors else None
|
|
)
|
|
return frames
|
|
|
|
|
|
def video_has_audio(path: Path) -> bool:
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"ffprobe", "-v", "error", "-select_streams", "a",
|
|
"-show_entries", "stream=index", "-of", "csv=p=0", str(path),
|
|
],
|
|
capture_output=True,
|
|
check=True,
|
|
timeout=60,
|
|
)
|
|
except (OSError, subprocess.SubprocessError) as exc:
|
|
raise VideoError("ffprobe could not inspect the audio track") from exc
|
|
return bool(result.stdout.strip())
|
|
|
|
|
|
def transcribe_video(
|
|
path: Path,
|
|
model: str = DEFAULT_TRANSCRIPTION_MODEL,
|
|
) -> str:
|
|
"""Transcribe locally so audio is never sent to another cloud provider."""
|
|
try:
|
|
import mlx_whisper
|
|
except ImportError as exc:
|
|
raise VideoError("mlx-whisper is not installed") from exc
|
|
try:
|
|
result = mlx_whisper.transcribe(
|
|
str(path), path_or_hf_repo=model, verbose=False
|
|
)
|
|
except Exception as exc:
|
|
raise VideoError("local audio transcription failed") from exc
|
|
text = result.get("text") if isinstance(result, dict) else None
|
|
if not isinstance(text, str) or not text.strip():
|
|
raise VideoError("local audio transcription returned empty text")
|
|
return text.strip()
|
|
|
|
|
|
def _analysis_path(
|
|
row: Any,
|
|
ai_client: Any,
|
|
directory: Path | str,
|
|
max_frames: int,
|
|
) -> Path:
|
|
identity = f"{ANALYSIS_VERSION}|{ai_client.model}|{max_frames}"
|
|
digest = hashlib.sha256(identity.encode()).hexdigest()[:16]
|
|
return Path(directory).expanduser() / f"{row.msg_id}.{digest}.json"
|
|
|
|
|
|
def _load_analysis(path: Path) -> dict:
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except FileNotFoundError:
|
|
return {}
|
|
except (OSError, ValueError) as exc:
|
|
raise VideoError("invalid cached video analysis") from exc
|
|
return data if isinstance(data, dict) else {}
|
|
|
|
|
|
def _save_analysis(path: Path, data: dict) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
try:
|
|
path.parent.chmod(0o700)
|
|
except OSError:
|
|
pass
|
|
temporary = path.with_suffix(path.suffix + ".tmp")
|
|
temporary.write_text(
|
|
json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8"
|
|
)
|
|
temporary.chmod(0o600)
|
|
os.replace(temporary, path)
|
|
|
|
|
|
def enrich_videos(
|
|
client: Any,
|
|
ai_client: Any,
|
|
rows: list[Any],
|
|
video_dir: Path | str = DEFAULT_VIDEO_DIR,
|
|
analysis_dir: Path | str = DEFAULT_ANALYSIS_DIR,
|
|
max_frames: int = 12,
|
|
transcribe_audio: bool = True,
|
|
transcription_model: str = DEFAULT_TRANSCRIPTION_MODEL,
|
|
) -> dict[str, int]:
|
|
"""Process every MEDIA row, isolating failures and reusing successful analysis."""
|
|
stats = {
|
|
"candidates": 0,
|
|
"downloaded": 0,
|
|
"cached": 0,
|
|
"enriched": 0,
|
|
"failed": 0,
|
|
"audio": 0,
|
|
"audio_transcribed": 0,
|
|
"audio_failed": 0,
|
|
}
|
|
for row in rows:
|
|
if getattr(row, "msg_type", None) != 15:
|
|
continue
|
|
stats["candidates"] += 1
|
|
try:
|
|
path, downloaded = ensure_video_downloaded(client, row, video_dir)
|
|
stats["downloaded"] += int(downloaded)
|
|
analysis_path = _analysis_path(row, ai_client, analysis_dir, max_frames)
|
|
analysis = _load_analysis(analysis_path)
|
|
visual_text = analysis.get("visual_text") or ""
|
|
if visual_text:
|
|
stats["cached"] += 1
|
|
else:
|
|
duration = video_duration(row, path)
|
|
frames = extract_video_frames(path, duration, max_frames)
|
|
timestamps = ", ".join(f"{seconds:.1f}s" for seconds, _ in frames)
|
|
prompt = (
|
|
"这些图片按时间顺序来自同一段飞书视频,对应时间点为 "
|
|
f"{timestamps}。请合并重复内容,只提取实际可见的文字、数字、图表、"
|
|
"链接和与工作相关的关键画面变化;不要推测画面外事实。"
|
|
)
|
|
visual_text = ai_client.complete_with_images(
|
|
[(image, "image/jpeg") for _, image in frames], prompt
|
|
).strip()
|
|
analysis = {
|
|
"version": ANALYSIS_VERSION,
|
|
"visual_text": visual_text,
|
|
"audio_present": video_has_audio(path),
|
|
}
|
|
_save_analysis(analysis_path, analysis)
|
|
|
|
additions = []
|
|
if visual_text:
|
|
additions.append(f"[视频画面] {visual_text}")
|
|
audio_present = bool(analysis.get("audio_present"))
|
|
if audio_present:
|
|
stats["audio"] += 1
|
|
transcript = analysis.get("transcript") or ""
|
|
if audio_present and transcribe_audio and not transcript:
|
|
try:
|
|
transcript = transcribe_video(path, transcription_model)
|
|
analysis["transcript"] = transcript
|
|
_save_analysis(analysis_path, analysis)
|
|
except Exception: # noqa: BLE001 - preserve visual text and retry audio later
|
|
stats["audio_failed"] += 1
|
|
if transcript:
|
|
stats["audio_transcribed"] += 1
|
|
additions.append(f"[视频音轨转写] {transcript}")
|
|
if additions:
|
|
row.content = f"{getattr(row, 'content', '') or ''}\n" + "\n".join(
|
|
additions
|
|
)
|
|
stats["enriched"] += 1
|
|
except Exception: # noqa: BLE001 - isolate unavailable resources per video
|
|
stats["failed"] += 1
|
|
return stats
|