2026-11-15 20:07:24 +08:00
|
|
|
|
#!/usr/bin/env python3
|
|
|
|
|
|
"""Resumably generate missing daily summaries from the earliest stored message."""
|
|
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
|
|
import argparse
|
|
|
|
|
|
import json
|
|
|
|
|
|
import os
|
2026-11-22 20:52:23 +08:00
|
|
|
|
import re
|
2026-11-15 20:07:24 +08:00
|
|
|
|
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,
|
|
|
|
|
|
)
|
2026-11-22 20:52:23 +08:00
|
|
|
|
from snooper_monthly import month_bounds, monthly_output_path
|
2026-11-15 20:07:24 +08:00
|
|
|
|
from snooper_weekly import week_bounds, weekly_output_path
|
|
|
|
|
|
|
|
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
|
|
|
|
DEFAULT_STATE_PATH = Path("~/.larkx/backfill-state.json")
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-22 20:52:23 +08:00
|
|
|
|
def has_missing_report_tag(path: Path) -> bool:
|
|
|
|
|
|
"""Return whether frontmatter marks a weekly or monthly background gap."""
|
|
|
|
|
|
if not path.exists() or path.stat().st_size == 0:
|
|
|
|
|
|
return False
|
|
|
|
|
|
frontmatter = path.read_text(encoding="utf-8").split("\n---", 1)[0]
|
|
|
|
|
|
return bool(re.search(r"(?m)^- no_previous_(?:weekly|monthly)\s*$", frontmatter))
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-11-15 20:07:24 +08:00
|
|
|
|
def missing_message_dates(
|
|
|
|
|
|
start: date,
|
|
|
|
|
|
end: date,
|
|
|
|
|
|
has_messages,
|
|
|
|
|
|
output_for_day,
|
|
|
|
|
|
overwrite: bool = False,
|
2026-11-22 20:52:23 +08:00
|
|
|
|
refresh_tagged_from: date | None = None,
|
2026-11-27 23:13:34 +08:00
|
|
|
|
daily_overwrite_from: date | None = None,
|
2026-11-15 20:07:24 +08:00
|
|
|
|
):
|
2026-11-22 20:52:23 +08:00
|
|
|
|
"""Yield message days that are missing or explicitly tagged for refresh."""
|
2026-11-15 20:07:24 +08:00
|
|
|
|
current = start
|
|
|
|
|
|
while current <= end:
|
|
|
|
|
|
output = Path(output_for_day(current))
|
|
|
|
|
|
exists = output.exists() and output.stat().st_size > 0
|
2026-11-22 20:52:23 +08:00
|
|
|
|
refresh = (
|
|
|
|
|
|
refresh_tagged_from is not None
|
|
|
|
|
|
and current >= refresh_tagged_from
|
|
|
|
|
|
and has_missing_report_tag(output)
|
|
|
|
|
|
)
|
2026-11-27 23:13:34 +08:00
|
|
|
|
forced = daily_overwrite_from is not None and current >= daily_overwrite_from
|
|
|
|
|
|
if (overwrite or not exists or refresh or forced) and has_messages(current):
|
2026-11-15 20:07:24 +08:00
|
|
|
|
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))
|
2026-11-27 23:13:34 +08:00
|
|
|
|
parser.add_argument("--image-model", help="图片卡片和视频帧使用的 EFundGPT 模型")
|
2026-11-15 20:07:24 +08:00
|
|
|
|
parser.add_argument("--base-url", default=os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL))
|
|
|
|
|
|
parser.add_argument("--timeout", type=int, default=600)
|
2026-11-22 20:52:23 +08:00
|
|
|
|
parser.add_argument("--overwrite", action="store_true", help="覆盖已有非空日报、周记和月记")
|
|
|
|
|
|
parser.add_argument("--weekly-through", help="先仅补齐此日期前已结束周的周记")
|
|
|
|
|
|
parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报")
|
2026-11-27 23:13:34 +08:00
|
|
|
|
parser.add_argument("--daily-overwrite-from", help="覆盖此日期起的全部已有日报")
|
2026-11-15 20:07:24 +08:00
|
|
|
|
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
|
2026-11-22 20:52:23 +08:00
|
|
|
|
weekly_through = (
|
|
|
|
|
|
resolve_day(args.weekly_through, args.timezone)[0]
|
|
|
|
|
|
if args.weekly_through else None
|
|
|
|
|
|
)
|
|
|
|
|
|
refresh_tagged_from = (
|
|
|
|
|
|
resolve_day(args.refresh_tagged_from, args.timezone)[0]
|
|
|
|
|
|
if args.refresh_tagged_from else None
|
|
|
|
|
|
)
|
2026-11-27 23:13:34 +08:00
|
|
|
|
daily_overwrite_from = (
|
|
|
|
|
|
resolve_day(args.daily_overwrite_from, args.timezone)[0]
|
|
|
|
|
|
if args.daily_overwrite_from else None
|
|
|
|
|
|
)
|
2026-11-22 20:52:23 +08:00
|
|
|
|
daily_start = max(start, refresh_tagged_from) if refresh_tagged_from else start
|
2026-11-15 20:07:24 +08:00
|
|
|
|
|
|
|
|
|
|
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,
|
2026-11-22 20:52:23 +08:00
|
|
|
|
"monthly_completed": 0,
|
2026-11-15 20:07:24 +08:00
|
|
|
|
"failed": 0,
|
|
|
|
|
|
"last_completed": None,
|
|
|
|
|
|
"last_attempted": None,
|
|
|
|
|
|
}
|
|
|
|
|
|
state_path = Path(args.state).expanduser()
|
|
|
|
|
|
write_state(state_path, state)
|
2026-11-22 20:52:23 +08:00
|
|
|
|
print(
|
|
|
|
|
|
f"补日志范围: {daily_start} 至 {end};"
|
|
|
|
|
|
"缺失报告及指定范围内带缺背景标签的日报将重新生成",
|
|
|
|
|
|
flush=True,
|
|
|
|
|
|
)
|
2026-11-15 20:07:24 +08:00
|
|
|
|
|
2026-11-22 20:52:23 +08:00
|
|
|
|
def run_step(command, output, label, kind="daily"):
|
2026-11-15 20:07:24 +08:00
|
|
|
|
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
|
2026-11-22 20:52:23 +08:00
|
|
|
|
key = {"daily": "completed", "weekly": "weekly_completed", "monthly": "monthly_completed"}[kind]
|
2026-11-15 20:07:24 +08:00
|
|
|
|
state[key] += 1
|
2026-11-22 20:52:23 +08:00
|
|
|
|
state_key = {"daily": "last_completed", "weekly": "last_weekly_completed", "monthly": "last_monthly_completed"}[kind]
|
|
|
|
|
|
state[state_key] = label
|
2026-11-15 20:07:24 +08:00
|
|
|
|
write_state(state_path, state)
|
|
|
|
|
|
print(f"===== {label} 完成 =====", flush=True)
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
2026-11-22 20:52:23 +08:00
|
|
|
|
def run_weekly(current_week, label_prefix="周记"):
|
2026-11-15 20:07:24 +08:00
|
|
|
|
_, natural_week_end = week_bounds(current_week)
|
2026-11-22 20:52:23 +08:00
|
|
|
|
weekly_path = weekly_output_path(config["output"], current_week)
|
|
|
|
|
|
has_daily_note = any(
|
|
|
|
|
|
output_for_day(current_week + timedelta(days=offset)).exists()
|
|
|
|
|
|
for offset in range(7)
|
|
|
|
|
|
)
|
|
|
|
|
|
weekly_exists = weekly_path.exists() and weekly_path.stat().st_size > 0
|
|
|
|
|
|
if natural_week_end > end or not has_daily_note:
|
|
|
|
|
|
return 0
|
|
|
|
|
|
if weekly_exists and not args.overwrite:
|
|
|
|
|
|
return 0
|
|
|
|
|
|
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")
|
|
|
|
|
|
return run_step(
|
|
|
|
|
|
command, weekly_path, f"{label_prefix} {current_week}", kind="weekly"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# Phase 1: establish weekly continuity before refreshing dependent daily notes.
|
|
|
|
|
|
if weekly_through:
|
|
|
|
|
|
current_week, _ = week_bounds(start)
|
|
|
|
|
|
while current_week <= weekly_through:
|
|
|
|
|
|
result = run_weekly(current_week, "预补周记")
|
2026-11-15 20:07:24 +08:00
|
|
|
|
if result:
|
|
|
|
|
|
return result
|
2026-11-22 20:52:23 +08:00
|
|
|
|
current_week += timedelta(days=7)
|
2026-11-15 20:07:24 +08:00
|
|
|
|
|
2026-11-22 20:52:23 +08:00
|
|
|
|
# Phase 2: process one calendar month at a time; each month ends with its note.
|
|
|
|
|
|
month_start = daily_start.replace(day=1)
|
|
|
|
|
|
while month_start <= end:
|
|
|
|
|
|
_, natural_month_end = month_bounds(month_start.year, month_start.month)
|
|
|
|
|
|
month_end = min(end, natural_month_end)
|
|
|
|
|
|
print(f"##### 处理自然月 {month_start:%Y-%m} #####", flush=True)
|
|
|
|
|
|
current_week, _ = week_bounds(month_start)
|
|
|
|
|
|
while current_week <= month_end:
|
|
|
|
|
|
_, natural_week_end = week_bounds(current_week)
|
|
|
|
|
|
day_start = max(daily_start, month_start, current_week)
|
|
|
|
|
|
day_end = min(month_end, natural_week_end)
|
|
|
|
|
|
for day in missing_message_dates(
|
|
|
|
|
|
day_start,
|
|
|
|
|
|
day_end,
|
|
|
|
|
|
has_messages,
|
|
|
|
|
|
output_for_day,
|
|
|
|
|
|
args.overwrite,
|
|
|
|
|
|
refresh_tagged_from,
|
2026-11-27 23:13:34 +08:00
|
|
|
|
daily_overwrite_from,
|
2026-11-22 20:52:23 +08:00
|
|
|
|
):
|
2026-11-15 20:07:24 +08:00
|
|
|
|
command = [
|
2026-11-22 20:52:23 +08:00
|
|
|
|
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",
|
|
|
|
|
|
]
|
2026-11-27 23:13:34 +08:00
|
|
|
|
if args.image_model:
|
|
|
|
|
|
command.extend(["--image-model", args.image_model])
|
2026-11-22 20:52:23 +08:00
|
|
|
|
output = output_for_day(day)
|
2026-11-27 23:13:34 +08:00
|
|
|
|
if (
|
|
|
|
|
|
args.overwrite
|
|
|
|
|
|
or has_missing_report_tag(output)
|
|
|
|
|
|
or (daily_overwrite_from and day >= daily_overwrite_from)
|
|
|
|
|
|
):
|
2026-11-22 20:52:23 +08:00
|
|
|
|
command.append("--overwrite")
|
|
|
|
|
|
result = run_step(command, output, f"补日志 {day}")
|
|
|
|
|
|
if result:
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
result = run_weekly(current_week)
|
|
|
|
|
|
if result:
|
|
|
|
|
|
return result
|
|
|
|
|
|
current_week += timedelta(days=7)
|
|
|
|
|
|
|
|
|
|
|
|
if natural_month_end <= end:
|
|
|
|
|
|
monthly_path = monthly_output_path(config["output"], month_start)
|
|
|
|
|
|
monthly_exists = monthly_path.exists() and monthly_path.stat().st_size > 0
|
|
|
|
|
|
if args.overwrite or not monthly_exists:
|
|
|
|
|
|
command = [
|
|
|
|
|
|
sys.executable, str(ROOT / "lark_snooper.py"), "monthly",
|
|
|
|
|
|
"--month", f"{month_start:%Y-%m}", "--config", args.config,
|
2026-11-15 20:07:24 +08:00
|
|
|
|
"--model", args.model, "--base-url", args.base_url,
|
|
|
|
|
|
"--timeout", str(args.timeout),
|
|
|
|
|
|
]
|
|
|
|
|
|
if args.overwrite:
|
|
|
|
|
|
command.append("--overwrite")
|
|
|
|
|
|
result = run_step(
|
2026-11-22 20:52:23 +08:00
|
|
|
|
command, monthly_path, f"月记 {month_start:%Y-%m}", kind="monthly"
|
2026-11-15 20:07:24 +08:00
|
|
|
|
)
|
|
|
|
|
|
if result:
|
|
|
|
|
|
return result
|
2026-11-22 20:52:23 +08:00
|
|
|
|
month_start = date(
|
|
|
|
|
|
month_start.year + (month_start.month == 12),
|
|
|
|
|
|
month_start.month % 12 + 1,
|
|
|
|
|
|
1,
|
|
|
|
|
|
)
|
2026-11-15 20:07:24 +08:00
|
|
|
|
|
|
|
|
|
|
state["status"] = "completed"
|
|
|
|
|
|
write_state(state_path, state)
|
|
|
|
|
|
print(
|
|
|
|
|
|
f"补日志完成: 新生成 {state['completed']} 天,"
|
2026-11-22 20:52:23 +08:00
|
|
|
|
f"周记 {state['weekly_completed']} 篇,月记 {state['monthly_completed']} 篇",
|
2026-11-15 20:07:24 +08:00
|
|
|
|
flush=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
sys.exit(main())
|