Files
Lark-Snooper/lark_snooper.py
Benature 105d10b3a7 refactor: 月记改用周报和上月月报,不再读日报
- MONTHLY_EXTRACT_PROMPT: 输入从日报片段改为周记片段
- MONTHLY_FINAL_PROMPT: 对照上月月记而非本月周记,结构调整为上月工作延续
- generate_monthly: 移除日报读取逻辑,添加读取上月月报逻辑
- 2024-08 月记已用新逻辑重新生成
2026-11-21 22:46:21 +08:00

564 lines
24 KiB
Python
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Lark Snooper CLI; LarkAgentX is an external dependency."""
import argparse
import json
import os
import sys
from datetime import datetime
from larkx.auth import LarkAuth
from snooper_client import SnifferLarkClient as LarkClient
from snooper_storage import SnifferStorage as Storage
from snooper_version import get_version
def _print_json(value):
print(json.dumps(value, ensure_ascii=False, indent=2, default=str))
def _report_history_failures(target_day, stats):
if not stats.get("failed"):
return
from snooper_history import format_history_failures, write_history_failures
failures = stats.get("failures", [])
details = format_history_failures(failures) or "无会话明细"
try:
log_path = write_history_failures(target_day, failures)
except OSError as error:
log_note = f"失败日志写入失败: {type(error).__name__}"
else:
log_note = f"失败日志: {log_path}"
print(
f"历史同步失败明细[{target_day.isoformat()}]: {details};{log_note}",
file=sys.stderr,
)
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 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\n"
"或: ./lark_snooper.py history --all --days 30 --save",
file=sys.stderr,
)
return 2
if not args.save or args.json:
print("按日期批量拉取必须 --save,且不支持 --json(不输出正文)", file=sys.stderr)
return 2
from snooper_history import HistoryError, sync_all_chats_for_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,
)
_report_history_failures(target_day, stats)
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,
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
_report_history_failures(target_day, stats)
print(
f"历史消息入库完成: {target_day.isoformat()},会话 {stats['chats']} 个,"
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:
print("请指定 chat_id,或使用 --all --date today --save", file=sys.stderr)
return 2
chat_id = args.chat_id
if args.start is not None:
start = args.start
else:
info = client.get_chat_info(chat_id)
if not info or not info.get("lastMessagePosition"):
print("拿不到会话的最新 position,请用 --start 指定", file=sys.stderr)
return 1
start = int(info["lastMessagePosition"]) - args.count + 1
if info.get("name"):
storage = Storage()
storage.update_chat_name(
chat_id,
info["name"],
info.get("type", 0) if isinstance(info.get("type"), int) else 0,
)
positions = list(range(max(1, start), max(1, start) + args.count))
storage = Storage() if args.save else None
messages = client.pull_history(chat_id, positions, save_storage=storage)
for message in messages:
if args.json:
continue
timestamp = (
datetime.fromtimestamp(message["create_time"]).strftime("%m-%d %H:%M")
if message.get("create_time")
else ""
)
scope = f"[{message['scope']}:{message['anchor'][:8]}]" if message["anchor"] else ""
content = message["content"] or ""
shown = content[:120] + ("…" if len(content) > 120 else "")
print(f"{message['position']:>6} [{timestamp}]{scope} {message['from_id']}: {shown}")
if args.json:
_print_json(
[{key: value for key, value in message.items() if key != "content_data"} for message in messages]
)
if args.save:
print(f"已入库 {len(messages)} 条")
return 0
def cmd_summarize(args):
from snooper_summary import (
DEFAULT_BASE_URL,
DEFAULT_MODEL,
DEFAULT_TIMEZONE,
MagpieClient,
SummaryError,
add_obsidian_properties,
configured_output_path,
default_dry_run_path,
default_summary_path,
escape_obsidian_tags,
format_followup_checkboxes,
load_config,
load_previous_summary,
resolve_chat_rules,
resolve_day,
resolve_people_aliases,
resolve_self_name,
serialize_message,
shorten_headings,
summarize_messages,
write_summary,
)
try:
target_day, start, end, tz = resolve_day(
args.date, args.timezone or DEFAULT_TIMEZONE
)
model = args.model or os.environ.get("MAGPIE_MODEL", DEFAULT_MODEL)
base_url = args.base_url or os.environ.get("MAGPIE_BASE_URL", DEFAULT_BASE_URL)
client = MagpieClient(
model=model,
base_url=base_url,
api_key=os.environ.get("MAGPIE_API_KEY"),
timeout=args.timeout,
)
# The EFundGPT preflight must pass before history sync or storage access.
client.assert_model_available()
if args.check:
print(f"OK Magpie 可用模型: {model}(未读取消息)")
return 0
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)
self_name = resolve_self_name(config)
storage = Storage()
if not args.no_fetch:
from snooper_history import sync_all_chats_for_day
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
_report_history_failures(target_day, fetch_stats)
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,
exclude_chat_ids=exclude_chat_ids,
include_outgoing=True,
)
from snooper_membership import MembershipError, filter_rows_with_membership
try:
rows, membership_stats = filter_rows_with_membership(
LarkClient(LarkAuth()), rows
)
except MembershipError as error:
raise SummaryError(
f"入群时间校验失败({error});已停止读取和总结。"
) from error
if membership_stats["excluded_chats"]:
print(
f"入群时间过滤: 排除未入群消息 "
f"{membership_stats['excluded_before_join']} 条,"
f"入群时间未知消息 {membership_stats['excluded_unknown']} 条,"
f"涉及 {membership_stats['excluded_chats']} 个群聊"
)
if args.dry_run:
records = [serialize_message(row, tz) for row in rows]
output_path = (
args.output
or configured_output_path(output_config, "dry_run", target_day)
or default_dry_run_path(target_day)
)
output = write_summary(
output_path, json.dumps(records, ensure_ascii=False, indent=2)
)
print(
f"DRY RUN 已导出: {output}"
f"({target_day.isoformat()},纳入消息 {len(rows)} 条,未发送给模型)"
)
return 0
if not getattr(args, "no_card_images", False):
from snooper_card_images import enrich_card_images
image_stats = enrich_card_images(
LarkClient(LarkAuth()), client, rows, max_images=3
)
if image_stats["candidates"]:
print(
f"卡片图片读取: 成功 {image_stats['enriched']} 张,"
f"失败/不可用 {image_stats['failed']} 张"
)
if not getattr(args, "no_videos", False):
from snooper_videos import enrich_videos
video_stats = enrich_videos(
LarkClient(LarkAuth()),
client,
rows,
max_frames=getattr(args, "video_frames", 12),
transcribe_audio=not getattr(args, "no_video_audio", False),
)
if video_stats["candidates"]:
print(
f"视频读取: 成功 {video_stats['enriched']} 个,"
f"失败/不可用 {video_stats['failed']} 个,"
f"新下载 {video_stats['downloaded']} 个,"
f"音轨转写 {video_stats['audio_transcribed']}/{video_stats['audio']},"
f"音轨失败 {video_stats['audio_failed']} 个"
)
previous_summary, previous_day_missing = load_previous_summary(
config["output"], target_day
)
from snooper_weekly import load_previous_weekly_background
previous_weekly_summary, previous_weekly_missing = (
load_previous_weekly_background(config["output"], target_day)
)
from snooper_monthly import load_previous_monthly_background
previous_monthly_summary, previous_monthly_missing = (
load_previous_monthly_background(config["output"], target_day)
)
calendar_events = []
calendar_error = None
unmatched_ai_notes = []
if not getattr(args, "no_calendar", False):
from snooper_calendar import (
CalendarError,
fetch_calendar_events,
resolve_calendar_links,
)
unmatched_ai_notes = []
try:
calendar_events, unmatched_ai_notes = fetch_calendar_events(
LarkClient(LarkAuth()),
target_day,
tz,
meeting_links=resolve_calendar_links(config),
storage=storage,
)
except CalendarError as error:
calendar_error = str(error)
print(
f"日历获取失败({error}),继续生成日报", file=sys.stderr
)
contacts = None
sender_types = {}
if rows and not args.no_contacts:
from snooper_contacts import ContactsError, fetch_contacts
try:
contacts = fetch_contacts(
LarkClient(LarkAuth()), rows, sender_types=sender_types
)
except ContactsError as error:
raise SummaryError(str(error)) from error
content = summarize_messages(
client,
rows,
target_day,
tz,
max_chars=args.max_chars,
contacts=contacts,
chat_prompts=chat_prompts,
people_aliases=people_aliases,
sender_types=sender_types,
previous_summary=previous_summary,
calendar_events=calendar_events,
calendar_error=calendar_error,
self_name=self_name,
previous_weekly_summary=previous_weekly_summary,
previous_monthly_summary=previous_monthly_summary,
)
output_path = (
args.output
or configured_output_path(output_config, "summary", target_day)
or default_summary_path(target_day)
)
content = format_followup_checkboxes(shorten_headings(content))
content = escape_obsidian_tags(content)
# Append unmatched AI Notes links within the meeting section
if unmatched_ai_notes:
lines = ["", "### 相关智能纪要", ""]
for link in unmatched_ai_notes:
topic = link.get("topic", "")
url = link["url"]
if topic:
lines.append(f"- [{topic}]({url})")
else:
lines.append(f"- {url}")
# Insert before the next major section (## 三、关键沟通与结论)
marker = "## 三、关键沟通与结论"
if marker in content:
content = content.replace(marker, "\n".join(lines) + "\n\n" + marker, 1)
else:
content += "\n".join(lines)
properties = {
"version": get_version(),
"model": model.rsplit("/", 1)[-1],
"is_read": False,
}
missing_background_tags = []
if previous_day_missing:
missing_background_tags.append("no_previous_day_log")
if previous_weekly_missing:
missing_background_tags.append("no_previous_weekly")
if missing_background_tags:
properties["tags"] = missing_background_tags
content = add_obsidian_properties(content, properties)
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)} 条,"
f"模型 {model}{cleanup_note})"
)
return 0
except SummaryError as error:
print(f"生成失败: {error}", file=sys.stderr)
return 1
except OSError as error:
print(f"写入总结或清理 dry-run 失败: {type(error).__name__}", file=sys.stderr)
return 1
def cmd_weekly(args):
from snooper_summary import SummaryError
from snooper_weekly import WeeklyError, generate_weekly
try:
generate_weekly(
week=args.week,
model=args.model or os.environ.get("MAGPIE_MODEL", "EFundGPT-dsv4-pro"),
base_url=args.base_url
or os.environ.get("MAGPIE_BASE_URL", "http://127.0.0.1:3425/v1"),
api_key=os.environ.get("MAGPIE_API_KEY"),
timeout=args.timeout,
config_path=args.config,
output=args.output,
overwrite=args.overwrite,
)
return 0
except (WeeklyError, SummaryError) as error:
print(f"周记生成失败: {error}", file=sys.stderr)
return 1
except OSError as error:
print(f"周记写入失败: {type(error).__name__}", file=sys.stderr)
return 1
def main():
parser = argparse.ArgumentParser(
prog="lark_snooper.py", description="LarkAgentX 历史同步与 EFundGPT 日度总结"
)
subparsers = parser.add_subparsers(dest="cmd", required=True)
weekly = subparsers.add_parser("weekly", help="根据日报生成周记并读取上周周记")
weekly.add_argument("--week", required=True, help="周内任意日期 YYYY-MM-DD")
weekly.add_argument("--model", help="实际模型段必须以 EFundGPT 开头")
weekly.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
weekly.add_argument("--timeout", type=int, default=600)
weekly.add_argument("--config", help="YAML 配置路径;默认读取当前目录 config.yaml")
weekly.add_argument("-o", "--output", help="覆盖周记输出路径")
weekly.add_argument("--overwrite", action="store_true", help="覆盖已有周记")
weekly.set_defaults(fn=cmd_weekly)
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* 生成每日总结")
summarize.add_argument("--date", default="today", help="YYYY-MM-DD、today(默认) 或 yesterday")
summarize.add_argument("--timezone", default="Asia/Shanghai", help="统计日边界时区")
summarize.add_argument("--chat", action="append", help="只汇总指定 chat_id;可重复")
summarize.add_argument("--model", help="实际模型段必须以 EFundGPT 开头;也可设 MAGPIE_MODEL")
summarize.add_argument("--base-url", help="Magpie OpenAI 兼容地址")
summarize.add_argument("--timeout", type=int, default=180, help="单次 Magpie 请求超时秒数")
summarize.add_argument("--max-chars", type=int, default=80000, help="每个对话内每块消息最大字符数")
summarize.add_argument("--no-contacts", action="store_true", help="不联网获取相关会话通讯录")
summarize.add_argument("--no-calendar", action="store_true", help="不获取主日历日程")
summarize.add_argument("--no-card-images", action="store_true", help="不读取卡片图片")
summarize.add_argument("--no-videos", action="store_true", help="不下载或读取视频消息")
summarize.add_argument("--video-frames", type=int, default=12, help="每个视频最多抽帧数,默认 12;视频数量不设上限")
summarize.add_argument("--no-video-audio", 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()
mode.add_argument("--check", action="store_true", help="只检查模型,不同步或读取消息")
mode.add_argument("--dry-run", action="store_true", help="只导出消息 JSON,不发送给模型")
summarize.set_defaults(fn=cmd_summarize)
args = parser.parse_args()
sys.exit(args.fn(args))
if __name__ == "__main__":
main()