feat: 按自然月回补日报周报和月报
This commit is contained in:
@ -6,6 +6,7 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import date, datetime, timedelta
|
||||
@ -34,25 +35,40 @@ from snooper_summary import (
|
||||
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,
|
||||
):
|
||||
"""Yield only days that have messages and lack a nonempty summary."""
|
||||
"""Yield message days that are missing or explicitly tagged for refresh."""
|
||||
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):
|
||||
refresh = (
|
||||
refresh_tagged_from is not None
|
||||
and current >= refresh_tagged_from
|
||||
and has_missing_report_tag(output)
|
||||
)
|
||||
if (overwrite or not exists or refresh) and has_messages(current):
|
||||
yield current
|
||||
current += timedelta(days=1)
|
||||
|
||||
@ -88,7 +104,9 @@ def main():
|
||||
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("--overwrite", action="store_true", help="覆盖已有非空日报、周记和月记")
|
||||
parser.add_argument("--weekly-through", help="先仅补齐此日期前已结束周的周记")
|
||||
parser.add_argument("--refresh-tagged-from", help="重新生成此日期起带缺周报/月报标签的日报")
|
||||
parser.add_argument("--state", default=str(DEFAULT_STATE_PATH))
|
||||
args = parser.parse_args()
|
||||
|
||||
@ -132,6 +150,15 @@ def main():
|
||||
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_start = max(start, refresh_tagged_from) if refresh_tagged_from else start
|
||||
|
||||
def output_for_day(day: date) -> Path:
|
||||
return Path(
|
||||
@ -157,15 +184,20 @@ def main():
|
||||
"status": "running",
|
||||
"completed": 0,
|
||||
"weekly_completed": 0,
|
||||
"monthly_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)
|
||||
print(
|
||||
f"补日志范围: {daily_start} 至 {end};"
|
||||
"缺失报告及指定范围内带缺背景标签的日报将重新生成",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
def run_step(command, output, label, weekly=False):
|
||||
def run_step(command, output, label, kind="daily"):
|
||||
state["last_attempted"] = label
|
||||
write_state(state_path, state)
|
||||
print(f"===== {label} 开始 =====", flush=True)
|
||||
@ -176,61 +208,113 @@ def main():
|
||||
write_state(state_path, state)
|
||||
print(f"补日志在 {label} 停止;修复后重跑会继续", flush=True)
|
||||
return result.returncode or 1
|
||||
key = "weekly_completed" if weekly else "completed"
|
||||
key = {"daily": "completed", "weekly": "weekly_completed", "monthly": "monthly_completed"}[kind]
|
||||
state[key] += 1
|
||||
state["last_weekly_completed" if weekly else "last_completed"] = label
|
||||
state_key = {"daily": "last_completed", "weekly": "last_weekly_completed", "monthly": "last_monthly_completed"}[kind]
|
||||
state[state_key] = label
|
||||
write_state(state_path, state)
|
||||
print(f"===== {label} 完成 =====", flush=True)
|
||||
return 0
|
||||
|
||||
current_week, _ = week_bounds(start)
|
||||
while current_week <= end:
|
||||
def run_weekly(current_week, label_prefix="周记"):
|
||||
_, 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}")
|
||||
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)
|
||||
|
||||
# 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):
|
||||
# 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,
|
||||
):
|
||||
command = [
|
||||
sys.executable, str(ROOT / "lark_snooper.py"), "weekly",
|
||||
"--week", current_week.isoformat(), "--config", args.config,
|
||||
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",
|
||||
]
|
||||
output = output_for_day(day)
|
||||
if args.overwrite or has_missing_report_tag(output):
|
||||
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,
|
||||
"--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
|
||||
command, monthly_path, f"月记 {month_start:%Y-%m}", kind="monthly"
|
||||
)
|
||||
if result:
|
||||
return result
|
||||
current_week += timedelta(days=7)
|
||||
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']} 篇",
|
||||
f"周记 {state['weekly_completed']} 篇,月记 {state['monthly_completed']} 篇",
|
||||
flush=True,
|
||||
)
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user