407 lines
15 KiB
Python
Executable File
407 lines
15 KiB
Python
Executable File
#!/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 re
|
||
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_history import HistoryError, sync_all_chats_for_day
|
||
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_monthly import month_bounds, monthly_output_path
|
||
from snooper_weekly import week_bounds, weekly_output_path
|
||
|
||
ROOT = Path(__file__).resolve().parent
|
||
DEFAULT_STATE_PATH = Path("~/.larkx/backfill-state.json")
|
||
|
||
|
||
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))
|
||
|
||
|
||
def missing_message_dates(
|
||
start: date,
|
||
end: date,
|
||
has_messages,
|
||
output_for_day,
|
||
overwrite: bool = False,
|
||
refresh_tagged_from: date | None = None,
|
||
daily_overwrite_from: date | None = None,
|
||
already_overwritten: set[str] | None = None,
|
||
):
|
||
"""Yield message days that are missing, tagged, or pending overwrite."""
|
||
overwritten = already_overwritten or set()
|
||
current = start
|
||
while current <= end:
|
||
output = Path(output_for_day(current))
|
||
exists = output.exists() and output.stat().st_size > 0
|
||
refresh = (
|
||
refresh_tagged_from is not None
|
||
and current >= refresh_tagged_from
|
||
and has_missing_report_tag(output)
|
||
)
|
||
forced = (
|
||
daily_overwrite_from is not None
|
||
and current >= daily_overwrite_from
|
||
and current.isoformat() not in overwritten
|
||
)
|
||
if (overwrite or not exists or refresh or forced) 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("--image-model", help="图片卡片和视频帧使用的 EFundGPT 模型")
|
||
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("--weekly-through", help="先仅补齐此日期前已结束周的周记")
|
||
parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报")
|
||
parser.add_argument("--daily-overwrite-from", help="覆盖此日期起的全部已有日报")
|
||
parser.add_argument("--fetch-missing", 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
|
||
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
|
||
)
|
||
daily_overwrite_from = (
|
||
resolve_day(args.daily_overwrite_from, args.timezone)[0]
|
||
if args.daily_overwrite_from else None
|
||
)
|
||
daily_start = max(start, refresh_tagged_from) if refresh_tagged_from else start
|
||
|
||
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)
|
||
|
||
def ensure_day_synced(day: date) -> None:
|
||
"""Fetch a day's messages only when it has neither local data nor a sync mark."""
|
||
if storage.is_day_synced(day.isoformat()):
|
||
return
|
||
_, day_start, day_end, tz = 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,
|
||
)
|
||
if rows:
|
||
return
|
||
import chinese_calendar
|
||
|
||
if chinese_calendar.is_holiday(day):
|
||
storage.mark_day_synced(day.isoformat(), 0)
|
||
return
|
||
print(f"===== 联网拉取 {day} =====", flush=True)
|
||
try:
|
||
stats = sync_all_chats_for_day(
|
||
LarkClient(LarkAuth()),
|
||
storage,
|
||
day,
|
||
tz,
|
||
batch_size=50,
|
||
exclude_chat_ids=exclude_chat_ids,
|
||
)
|
||
except HistoryError as error:
|
||
print(f"===== 联网拉取 {day} 失败: {error} =====", flush=True)
|
||
return
|
||
print(
|
||
f"===== 联网拉取 {day} 完成:消息 {stats['matched']} 条,"
|
||
f"失败会话 {stats['failed']} 个 =====",
|
||
flush=True,
|
||
)
|
||
|
||
state_path = Path(args.state).expanduser()
|
||
previous_overwritten: set[str] = set()
|
||
if state_path.exists():
|
||
try:
|
||
previous = json.loads(state_path.read_text(encoding="utf-8"))
|
||
previous_overwritten = set(previous.get("overwritten_dates", []))
|
||
except (ValueError, OSError):
|
||
previous_overwritten = set()
|
||
|
||
state = {
|
||
"model": args.model,
|
||
"start_date": start.isoformat(),
|
||
"end_date": end.isoformat(),
|
||
"status": "running",
|
||
"completed": 0,
|
||
"weekly_completed": 0,
|
||
"monthly_completed": 0,
|
||
"failed": 0,
|
||
"last_completed": None,
|
||
"last_attempted": None,
|
||
"overwritten_dates": sorted(previous_overwritten),
|
||
}
|
||
write_state(state_path, state)
|
||
print(
|
||
f"补日志范围: {daily_start} 至 {end};"
|
||
"缺失报告及指定范围内带缺背景标签的日报将重新生成",
|
||
flush=True,
|
||
)
|
||
|
||
def run_step(command, output, label, kind="daily", day: date | None = None):
|
||
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 = {"daily": "completed", "weekly": "weekly_completed", "monthly": "monthly_completed"}[kind]
|
||
state[key] += 1
|
||
state_key = {"daily": "last_completed", "weekly": "last_weekly_completed", "monthly": "last_monthly_completed"}[kind]
|
||
state[state_key] = label
|
||
if day is not None:
|
||
overwritten = set(state.get("overwritten_dates", []))
|
||
overwritten.add(day.isoformat())
|
||
state["overwritten_dates"] = sorted(overwritten)
|
||
write_state(state_path, state)
|
||
print(f"===== {label} 完成 =====", flush=True)
|
||
return 0
|
||
|
||
def run_weekly(current_week, label_prefix="周记"):
|
||
_, natural_week_end = week_bounds(current_week)
|
||
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, "预补周记")
|
||
if result:
|
||
return result
|
||
current_week += timedelta(days=7)
|
||
|
||
# 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)
|
||
|
||
def has_messages_or_fetch(day: date) -> bool:
|
||
if args.fetch_missing:
|
||
ensure_day_synced(day)
|
||
return has_messages(day)
|
||
|
||
for day in missing_message_dates(
|
||
day_start,
|
||
day_end,
|
||
has_messages_or_fetch,
|
||
output_for_day,
|
||
args.overwrite,
|
||
refresh_tagged_from,
|
||
daily_overwrite_from,
|
||
set(state["overwritten_dates"]),
|
||
):
|
||
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",
|
||
]
|
||
if args.image_model:
|
||
command.extend(["--image-model", args.image_model])
|
||
output = output_for_day(day)
|
||
if (
|
||
args.overwrite
|
||
or has_missing_report_tag(output)
|
||
or (daily_overwrite_from and day >= daily_overwrite_from)
|
||
):
|
||
command.append("--overwrite")
|
||
result = run_step(
|
||
command, output, f"补日志 {day}", kind="daily", day=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,
|
||
"--model", args.model, "--base-url", args.base_url,
|
||
"--timeout", str(args.timeout),
|
||
]
|
||
if args.overwrite:
|
||
command.append("--overwrite")
|
||
result = run_step(
|
||
command, monthly_path, f"月记 {month_start:%Y-%m}", kind="monthly"
|
||
)
|
||
if result:
|
||
return result
|
||
month_start = date(
|
||
month_start.year + (month_start.month == 12),
|
||
month_start.month % 12 + 1,
|
||
1,
|
||
)
|
||
|
||
state["status"] = "completed"
|
||
write_state(state_path, state)
|
||
print(
|
||
f"补日志完成: 新生成 {state['completed']} 天,"
|
||
f"周记 {state['weekly_completed']} 篇,月记 {state['monthly_completed']} 篇",
|
||
flush=True,
|
||
)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|