feat: add summary configuration and sync controls

This commit is contained in:
Benature
2026-11-07 18:46:23 +08:00
parent 3e5ac07183
commit 99ee792c07
10 changed files with 1782 additions and 60 deletions

View File

@ -17,12 +17,34 @@ def _print_json(value):
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
def cmd_web(args):
from snooper_web import WebError, run_web
try:
run_web(
port=args.port,
config_path=args.config,
open_browser=not args.no_browser,
)
return 0
except (WebError, OSError) as error:
print(f"Web 管理页启动失败: {error}", file=sys.stderr)
return 1
def cmd_history(args):
client = LarkClient(LarkAuth())
if args.all or args.date:
if not args.all or not args.date or args.chat_id or args.start is not None:
if args.all or args.date or args.days:
if args.date and args.days:
print("--date 与 --days 不能同时使用", file=sys.stderr)
return 2
if args.days is not None and args.days < 1:
print("--days 必须大于等于 1", file=sys.stderr)
return 2
if not args.all or (not args.date and not args.days) or args.chat_id or args.start is not None:
print(
"按日期批量拉取用法: ./lark_snooper.py history --all --date today --save",
"按日期批量拉取用法: ./lark_snooper.py history --all --date today --save\n"
"或: ./lark_snooper.py history --all --days 30 --save",
file=sys.stderr,
)
return 2
@ -30,24 +52,71 @@ def cmd_history(args):
print("按日期批量拉取必须 --save,且不支持 --json(不输出正文)", file=sys.stderr)
return 2
from snooper_history import HistoryError, sync_all_chats_for_day
from snooper_summary import SummaryError, resolve_day
from snooper_summary import (
SummaryError,
load_config,
resolve_chat_rules,
resolve_day,
)
try:
config = load_config(getattr(args, "config", None))
exclude_chat_ids, _ = resolve_chat_rules(config)
storage = Storage()
if args.days:
from datetime import timedelta
today, _, _, tz = resolve_day("today", "Asia/Shanghai")
total = {
"chats": 0, "scanned": 0, "empty": 0, "matched": 0,
"saved": 0, "failed": 0, "requests": 0, "skipped": 0,
}
for i in range(args.days):
target_day = today - timedelta(days=i)
stats = sync_all_chats_for_day(
client,
storage,
target_day,
tz,
batch_size=args.count,
exclude_chat_ids=exclude_chat_ids,
force=args.force,
)
for key in total:
total[key] += stats[key]
print(
f" {target_day.isoformat()}: 消息 {stats['matched']} 条,"
f"写入 {stats['saved']} 条,跳过会话 {stats['skipped']} 个,"
f"请求 {stats['requests']} 次"
)
stats = total
print(
f"最近 {args.days} 天入库完成: 会话 {stats['chats']} 个,"
f"跳过 {stats['skipped']} 个,日期内消息 {stats['matched']} 条,"
f"写入/补全 {stats['saved']} 条,失败会话 {stats['failed']} 个,"
f"历史请求 {stats['requests']} 次(正文不打印)"
)
return 1 if stats["failed"] else 0
target_day, _, _, tz = resolve_day(args.date, "Asia/Shanghai")
stats = sync_all_chats_for_day(
client,
Storage(),
storage,
target_day,
tz,
batch_size=args.count,
exclude_chat_ids=exclude_chat_ids,
force=args.force,
)
except (HistoryError, SummaryError) as error:
print(f"历史消息入库失败: {error}", file=sys.stderr)
return 1
print(
f"历史消息入库完成: {target_day.isoformat()},会话 {stats['chats']} 个,"
f"日期内消息 {stats['matched']} 条,写入/补全 {stats['saved']} 条,"
f"失败会话 {stats['failed']} 个,历史请求 {stats['requests']} 次(正文不打印)"
f"跳过 {stats['skipped']} 个,日期内消息 {stats['matched']} 条,"
f"写入/补全 {stats['saved']} 条,失败会话 {stats['failed']} 个,"
f"历史请求 {stats['requests']} 次(正文不打印)"
)
return 1 if stats["failed"] else 0
if not args.chat_id:
@ -100,11 +169,14 @@ def cmd_summarize(args):
DEFAULT_TIMEZONE,
MagpieClient,
SummaryError,
add_obsidian_properties,
configured_output_path,
default_dry_run_path,
default_summary_path,
load_output_config,
load_config,
resolve_chat_rules,
resolve_day,
resolve_people_aliases,
serialize_message,
summarize_messages,
write_summary,
@ -127,36 +199,58 @@ def cmd_summarize(args):
if args.check:
print(f"OK Magpie 可用模型: {model}(未读取消息)")
return 0
output_config = {} if args.output else load_output_config(getattr(args, "config", None))
config = load_config(getattr(args, "config", None))
output_config = {} if args.output else config["output"]
exclude_chat_ids, chat_prompts = resolve_chat_rules(config)
people_aliases = resolve_people_aliases(config)
storage = Storage()
if not args.no_fetch:
from snooper_history import sync_all_chats_for_day
try:
fetch_stats = sync_all_chats_for_day(
LarkClient(LarkAuth()),
storage,
target_day,
tz,
batch_size=50,
chat_ids=args.chat,
)
except Exception as error:
raise SummaryError(
f"飞书历史数据同步失败({type(error).__name__});"
"可使用 --no-fetch 明确只读本地库。"
) from error
if fetch_stats["failed"]:
raise SummaryError(
f"有 {fetch_stats['failed']} 个会话同步失败,已停止后续总结;"
"可修复后重试,或使用 --no-fetch 明确只读本地库。"
)
print(
f"数据同步完成: 日期内消息 {fetch_stats['matched']} 条,"
f"写入/补全 {fetch_stats['saved']} 条,失败会话 0 个"
already_local = storage.has_messages_for_day(
int(start.timestamp()),
int(end.timestamp()),
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
)
if already_local and not args.force_fetch:
print(
f"本地已有 {target_day.isoformat()} 的数据,跳过网络同步"
"(--force-fetch 可强制重新拉取)"
)
fetch_stats = None
else:
try:
fetch_stats = sync_all_chats_for_day(
LarkClient(LarkAuth()),
storage,
target_day,
tz,
batch_size=50,
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
force=args.force_fetch,
)
except Exception as error:
raise SummaryError(
f"飞书历史数据同步失败({type(error).__name__});"
"可使用 --no-fetch 明确只读本地库。"
) from error
if fetch_stats["failed"]:
raise SummaryError(
f"有 {fetch_stats['failed']} 个会话同步失败,已停止后续总结;"
"可修复后重试,或使用 --no-fetch 明确只读本地库。"
)
print(
f"数据同步完成: 日期内消息 {fetch_stats['matched']} 条,"
f"写入/补全 {fetch_stats['saved']} 条,"
f"跳过会话 {fetch_stats['skipped']} 个,失败会话 0 个"
)
rows = storage.get_received_messages(
int(start.timestamp()), int(end.timestamp()), chat_ids=args.chat
int(start.timestamp()),
int(end.timestamp()),
chat_ids=args.chat,
exclude_chat_ids=exclude_chat_ids,
)
if args.dry_run:
records = [serialize_message(row, tz) for row in rows]
@ -188,22 +282,42 @@ def cmd_summarize(args):
tz,
max_chars=args.max_chars,
contacts=contacts,
chat_prompts=chat_prompts,
people_aliases=people_aliases,
)
output_path = (
args.output
or configured_output_path(output_config, "summary", target_day)
or default_summary_path(target_day)
)
content = add_obsidian_properties(
content, {"model": model.rsplit("/", 1)[-1]}
)
output = write_summary(output_path, content)
dry_run_path = configured_output_path(
config["output"], "dry_run", target_day
) or default_dry_run_path(target_day)
cleanup_note = ""
if (
dry_run_path.suffix.lower() == ".json"
and dry_run_path.absolute() != output.absolute()
):
try:
dry_run_path.unlink()
except FileNotFoundError:
pass
else:
cleanup_note = ",已清理 dry-run JSON"
print(
f"已生成: {output}({target_day.isoformat()},收到消息 {len(rows)} 条,模型 {model})"
f"已生成: {output}({target_day.isoformat()},收到消息 {len(rows)} 条,"
f"模型 {model}{cleanup_note})"
)
return 0
except SummaryError as error:
print(f"生成失败: {error}", file=sys.stderr)
return 1
except OSError as error:
print(f"写入总结失败: {type(error).__name__}", file=sys.stderr)
print(f"写入总结或清理 dry-run 失败: {type(error).__name__}", file=sys.stderr)
return 1
@ -213,14 +327,23 @@ def main():
)
subparsers = parser.add_subparsers(dest="cmd", required=True)
web = subparsers.add_parser("web", help="打开本机会话搜索与忽略列表管理页")
web.add_argument("--port", type=int, default=8765, help="本机监听端口,默认 8765")
web.add_argument("--config", default="config.yaml", help="要维护的 YAML 配置路径")
web.add_argument("--no-browser", action="store_true", help="不自动打开浏览器")
web.set_defaults(fn=cmd_web)
history = subparsers.add_parser("history", help="拉取历史消息;支持全部可见 INBOX 会话按日期入库")
history.add_argument("chat_id", nargs="?")
history.add_argument("--all", action="store_true", help="枚举全部可见 INBOX 会话,需配合 --date --save")
history.add_argument("--date", help="只入库指定自然日消息:YYYY-MM-DD、today 或 yesterday")
history.add_argument("--days", type=int, help="入库最近 N 天消息(含今天),与 --date 互斥")
history.add_argument("--start", type=int, help="起始 position;不可与 --date 同用")
history.add_argument("--count", type=int, default=20)
history.add_argument("--save", action="store_true", help="同时写入本地库")
history.add_argument("--force", action="store_true", help="忽略本地同步进度,强制重新拉取")
history.add_argument("--json", action="store_true")
history.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
history.set_defaults(fn=cmd_history)
summarize = subparsers.add_parser("summarize", help="按对话分别摘要后,仅用 EFundGPT* 生成每日总结")
@ -233,6 +356,7 @@ def main():
summarize.add_argument("--max-chars", type=int, default=80000, help="每个对话内每块消息最大字符数")
summarize.add_argument("--no-contacts", action="store_true", help="不联网获取相关会话通讯录")
summarize.add_argument("--no-fetch", action="store_true", help="只读取本地已入库记录")
summarize.add_argument("--force-fetch", action="store_true", help="即使本地已有数据也强制重新拉取")
summarize.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
summarize.add_argument("-o", "--output", help="输出路径,优先级高于 YAML")
mode = summarize.add_mutually_exclusive_group()