feat: 图片下载与数据目录本地化

- 新增 download_images.py: 批量下载消息图片到 downloads/images/
- 数据库移至 downloads/messages.db,SnifferStorage 默认使用项目目录
- 图片默认保存到 downloads/images/,支持 --out-dir 自定义
- .gitignore 排除 downloads/ 避免提交二进制文件
- 补充腾讯会议号过滤 prompt
- 补充 Obsidian 文档 is_read frontmatter
This commit is contained in:
Benature
2026-11-15 20:07:24 +08:00
parent cceeaf5c78
commit 81b6ff7a39
21 changed files with 2206 additions and 25 deletions

240
backfill_summaries.py Executable file
View File

@ -0,0 +1,240 @@
#!/usr/bin/env python3
"""Resumably generate missing daily summaries from the earliest stored message."""
from __future__ import annotations
import argparse
import json
import os
import subprocess
import sys
from datetime import date, datetime, timedelta
from pathlib import Path
from larkx.auth import LarkAuth
from larkx.storage.models import Message
from sqlalchemy import func
from snooper_client import SnifferLarkClient as LarkClient
from snooper_membership import (
MembershipError,
fetch_self_join_times,
filter_rows_by_membership,
)
from snooper_storage import SnifferStorage
from snooper_summary import (
DEFAULT_BASE_URL,
DEFAULT_MODEL,
DEFAULT_TIMEZONE,
MagpieClient,
SummaryError,
configured_output_path,
default_summary_path,
load_config,
resolve_chat_rules,
resolve_day,
)
from snooper_weekly import week_bounds, weekly_output_path
ROOT = Path(__file__).resolve().parent
DEFAULT_STATE_PATH = Path("~/.larkx/backfill-state.json")
def missing_message_dates(
start: date,
end: date,
has_messages,
output_for_day,
overwrite: bool = False,
):
"""Yield only days that have messages and lack a nonempty summary."""
current = start
while current <= end:
output = Path(output_for_day(current))
exists = output.exists() and output.stat().st_size > 0
if (overwrite or not exists) and has_messages(current):
yield current
current += timedelta(days=1)
def earliest_stored_day(storage: SnifferStorage, timezone: str) -> date:
session = storage.Session()
try:
timestamp = session.query(func.min(Message.create_time)).scalar()
finally:
session.close()
if not timestamp:
raise SummaryError("本地消息库为空。")
_, start, _, _ = resolve_day("today", timezone)
return datetime.fromtimestamp(timestamp, start.tzinfo).date()
def write_state(path: Path, state: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8"
)
temporary.chmod(0o600)
os.replace(temporary, path)
def main():
parser = argparse.ArgumentParser(description="从最早本地消息开始补齐缺失日报")
parser.add_argument("--start-date", help="默认使用本地最早消息日期")
parser.add_argument("--end-date", help="默认今天;格式 YYYY-MM-DD")
parser.add_argument("--timezone", default=DEFAULT_TIMEZONE)
parser.add_argument("--config", default="config.yaml")
parser.add_argument("--model", default=os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL))
parser.add_argument("--base-url", default=os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL))
parser.add_argument("--timeout", type=int, default=600)
parser.add_argument("--overwrite", action="store_true", help="覆盖已有非空日报")
parser.add_argument("--state", default=str(DEFAULT_STATE_PATH))
args = parser.parse_args()
try:
ai_client = MagpieClient(
model=args.model,
base_url=args.base_url,
api_key=os.environ.get("MAGPIE_API_KEY"),
timeout=args.timeout,
)
ai_client.assert_model_available()
config = load_config(args.config)
exclude_chat_ids, _ = resolve_chat_rules(config)
storage = SnifferStorage()
start = (
resolve_day(args.start_date, args.timezone)[0]
if args.start_date
else earliest_stored_day(storage, args.timezone)
)
end = (
resolve_day(args.end_date, args.timezone)[0]
if args.end_date
else resolve_day("today", args.timezone)[0]
)
session = storage.Session()
try:
group_chat_ids = {
str(chat_id)
for (chat_id,) in session.query(Message.chat_id)
.filter(Message.chat_type.in_([2, 3]))
.distinct()
}
finally:
session.close()
join_times = fetch_self_join_times(
LarkClient(LarkAuth()), group_chat_ids, strict=False
)
except (SummaryError, MembershipError) as error:
print(f"初始化失败: {error}", file=sys.stderr)
return 1
if end < start:
print("--end-date 不能早于 --start-date", file=sys.stderr)
return 2
def output_for_day(day: date) -> Path:
return Path(
configured_output_path(config["output"], "summary", day)
or default_summary_path(day)
)
def has_messages(day: date) -> bool:
_, day_start, day_end, _ = resolve_day(day.isoformat(), args.timezone)
rows = storage.get_received_messages(
int(day_start.timestamp()),
int(day_end.timestamp()),
exclude_chat_ids=exclude_chat_ids,
include_outgoing=True,
)
filtered, _ = filter_rows_by_membership(rows, join_times)
return bool(filtered)
state = {
"model": args.model,
"start_date": start.isoformat(),
"end_date": end.isoformat(),
"status": "running",
"completed": 0,
"weekly_completed": 0,
"failed": 0,
"last_completed": None,
"last_attempted": None,
}
state_path = Path(args.state).expanduser()
write_state(state_path, state)
print(f"补日志范围: {start} 至 {end};已有非空日报和无消息日自动跳过", flush=True)
def run_step(command, output, label, weekly=False):
state["last_attempted"] = label
write_state(state_path, state)
print(f"===== {label} 开始 =====", flush=True)
result = subprocess.run(command, cwd=ROOT, check=False)
if result.returncode != 0 or not output.exists() or output.stat().st_size == 0:
state["status"] = "failed"
state["failed"] += 1
write_state(state_path, state)
print(f"补日志在 {label} 停止;修复后重跑会继续", flush=True)
return result.returncode or 1
key = "weekly_completed" if weekly else "completed"
state[key] += 1
state["last_weekly_completed" if weekly else "last_completed"] = label
write_state(state_path, state)
print(f"===== {label} 完成 =====", flush=True)
return 0
current_week, _ = week_bounds(start)
while current_week <= end:
_, natural_week_end = week_bounds(current_week)
day_start = max(start, current_week)
day_end = min(end, natural_week_end)
for day in missing_message_dates(
day_start, day_end, has_messages, output_for_day, args.overwrite
):
command = [
sys.executable, str(ROOT / "lark_snooper.py"), "summarize",
"--date", day.isoformat(), "--timezone", args.timezone,
"--config", args.config, "--model", args.model,
"--base-url", args.base_url, "--timeout", str(args.timeout),
"--no-fetch",
]
result = run_step(command, output_for_day(day), f"补日志 {day}")
if result:
return result
# Only completed weeks get a weekly note; a month-ending partial week waits.
if natural_week_end <= end:
weekly_path = weekly_output_path(config["output"], current_week)
has_daily_note = any(
output_for_day(day_start + timedelta(days=offset)).exists()
for offset in range((day_end - day_start).days + 1)
)
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
if has_daily_note and (args.overwrite or not weekly_exists):
command = [
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
"--week", current_week.isoformat(), "--config", args.config,
"--model", args.model, "--base-url", args.base_url,
"--timeout", str(args.timeout),
]
if args.overwrite:
command.append("--overwrite")
result = run_step(
command, weekly_path, f"周记 {current_week}", weekly=True
)
if result:
return result
current_week += timedelta(days=7)
state["status"] = "completed"
write_state(state_path, state)
print(
f"补日志完成: 新生成 {state['completed']} 天,"
f"周记 {state['weekly_completed']} 篇",
flush=True,
)
return 0
if __name__ == "__main__":
sys.exit(main())