feat: 图片下载与数据目录本地化
- 新增 download_images.py: 批量下载消息图片到 downloads/images/ - 数据库移至 downloads/messages.db,SnifferStorage 默认使用项目目录 - 图片默认保存到 downloads/images/,支持 --out-dir 自定义 - .gitignore 排除 downloads/ 避免提交二进制文件 - 补充腾讯会议号过滤 prompt - 补充 Obsidian 文档 is_read frontmatter
This commit is contained in:
35
tests/test_backfill.py
Normal file
35
tests/test_backfill.py
Normal file
@ -0,0 +1,35 @@
|
||||
from datetime import date
|
||||
|
||||
from backfill_summaries import missing_message_dates
|
||||
|
||||
|
||||
def test_backfill_skips_empty_days_and_existing_nonempty_summaries(tmp_path):
|
||||
messages = {date(2024, 6, 2), date(2024, 6, 3), date(2024, 6, 4)}
|
||||
existing = tmp_path / "2024-06-03.md"
|
||||
existing.write_text("已有日报", encoding="utf-8")
|
||||
empty = tmp_path / "2024-06-04.md"
|
||||
empty.touch()
|
||||
|
||||
days = list(missing_message_dates(
|
||||
date(2024, 6, 1),
|
||||
date(2024, 6, 5),
|
||||
lambda day: day in messages,
|
||||
lambda day: tmp_path / f"{day.isoformat()}.md",
|
||||
))
|
||||
|
||||
assert days == [date(2024, 6, 2), date(2024, 6, 4)]
|
||||
|
||||
|
||||
def test_backfill_overwrite_still_skips_days_without_messages(tmp_path):
|
||||
output = tmp_path / "2024-06-02.md"
|
||||
output.write_text("旧日报", encoding="utf-8")
|
||||
|
||||
days = list(missing_message_dates(
|
||||
date(2024, 6, 2),
|
||||
date(2024, 6, 2),
|
||||
lambda day: True,
|
||||
lambda day: output,
|
||||
overwrite=True,
|
||||
))
|
||||
|
||||
assert days == [date(2024, 6, 2)]
|
||||
48
tests/test_card_images.py
Normal file
48
tests/test_card_images.py
Normal file
@ -0,0 +1,48 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from snooper_card_images import enrich_card_images, extract_card_image_keys
|
||||
|
||||
|
||||
def test_extract_card_image_keys_deduplicates_json_and_binary_properties():
|
||||
key = b"img_v3_02ad_synthetic"
|
||||
data = {
|
||||
"imageKey": key.decode(),
|
||||
"richtext": {"elements": {"dictionary": {"1": {"property": key}}}},
|
||||
}
|
||||
|
||||
assert extract_card_image_keys(data) == [key.decode()]
|
||||
|
||||
|
||||
def test_enrich_card_images_uses_approved_vision_client(monkeypatch):
|
||||
key = b"img_v3_02ad_synthetic"
|
||||
client = SimpleNamespace(
|
||||
auth=SimpleNamespace(region=SimpleNamespace(file_host="https://example.com")),
|
||||
pull_history=lambda chat_id, positions, visible_only: [
|
||||
{
|
||||
"content_data": {
|
||||
"richtext": {
|
||||
"elements": {"dictionary": {"1": {"property": key}}}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"snooper_card_images.download",
|
||||
lambda auth, url: (b"synthetic-image", "image/png"),
|
||||
)
|
||||
ai_client = SimpleNamespace(
|
||||
complete_with_image=lambda image, mime: "合成图片文字"
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
msg_type=14,
|
||||
position=1,
|
||||
chat_id="chat-a",
|
||||
msg_id="message-a",
|
||||
content="[卡片] [图片]",
|
||||
)
|
||||
|
||||
stats = enrich_card_images(client, ai_client, [row])
|
||||
|
||||
assert stats == {"candidates": 1, "enriched": 1, "failed": 0}
|
||||
assert "合成图片文字" in row.content
|
||||
67
tests/test_client.py
Normal file
67
tests/test_client.py
Normal file
@ -0,0 +1,67 @@
|
||||
import json
|
||||
|
||||
from larkx.proto import proto_pb2 as P
|
||||
from snooper_client import extract_card_text
|
||||
from snooper_storage import SnifferStorage as Storage
|
||||
|
||||
|
||||
def test_card_text_extracts_json_fields_and_rich_text():
|
||||
rich_property = P.TextProperty(content="合成富文本卡片正文").SerializeToString()
|
||||
data = {
|
||||
"jsonCard": json.dumps(
|
||||
{
|
||||
"title": "合成卡片标题",
|
||||
"elements": [
|
||||
{"tag": "text", "text": "合成卡片内容"},
|
||||
{"tag": "action", "url": "https://example.com/card"},
|
||||
],
|
||||
}
|
||||
),
|
||||
"richtext": {
|
||||
"elementIds": ["1"],
|
||||
"elements": {
|
||||
"dictionary": {
|
||||
"1": {"tag": 1, "property": rich_property},
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
text = extract_card_text(data)
|
||||
|
||||
assert "合成卡片标题" in text
|
||||
assert "合成卡片内容" in text
|
||||
assert "https://example.com/card" in text
|
||||
assert "合成富文本卡片正文" in text
|
||||
|
||||
|
||||
def test_backfill_card_text_updates_existing_rows_once():
|
||||
storage = Storage(url="sqlite:///:memory:")
|
||||
data = {
|
||||
"jsonCard": json.dumps({"title": "合成卡片标题", "text": "合成卡片正文"})
|
||||
}
|
||||
storage.save_message(
|
||||
{
|
||||
"msg_id": "card-1",
|
||||
"chat_id": "chat-a",
|
||||
"chat_type": 2,
|
||||
"from_id": "sender-a",
|
||||
"msg_type": 14,
|
||||
"msg_type_name": "CARD",
|
||||
"create_time": 1_792_000_000,
|
||||
"content": "[卡片]",
|
||||
"content_data": data,
|
||||
},
|
||||
direction="in",
|
||||
)
|
||||
|
||||
assert storage.backfill_card_text() == 1
|
||||
assert storage.backfill_card_text() == 0
|
||||
row = storage.get_messages("chat-a")[0]
|
||||
assert "合成卡片标题" in row.content
|
||||
assert "合成卡片正文" in row.content
|
||||
assert row.content.count("合成卡片正文") == 1
|
||||
|
||||
|
||||
def test_card_text_ignores_placeholder_only_rich_text():
|
||||
assert extract_card_text({"richtext": {}}) == ""
|
||||
78
tests/test_membership.py
Normal file
78
tests/test_membership.py
Normal file
@ -0,0 +1,78 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from snooper_membership import (
|
||||
MembershipError,
|
||||
fetch_self_join_times,
|
||||
filter_rows_by_membership,
|
||||
)
|
||||
|
||||
|
||||
def row(chat_id, chat_type, create_time):
|
||||
return SimpleNamespace(
|
||||
chat_id=chat_id, chat_type=chat_type, create_time=create_time
|
||||
)
|
||||
|
||||
|
||||
def test_membership_filter_excludes_prejoin_and_unknown_group_history():
|
||||
rows = [
|
||||
row("group-a", 2, 99),
|
||||
row("group-a", 2, 100),
|
||||
row("group-a", 2, 101),
|
||||
row("group-unknown", 2, 101),
|
||||
row("private-a", 1, 1),
|
||||
]
|
||||
|
||||
filtered, stats = filter_rows_by_membership(rows, {"group-a": 100})
|
||||
|
||||
assert [row.create_time for row in filtered] == [100, 101, 1]
|
||||
assert stats["excluded_before_join"] == 1
|
||||
assert stats["excluded_unknown"] == 1
|
||||
assert stats["excluded_chats"] == 2
|
||||
|
||||
|
||||
def test_fetch_join_time_paginates_and_caches_positive_evidence(tmp_path):
|
||||
client = SimpleNamespace(
|
||||
auth=SimpleNamespace(user_id="self"),
|
||||
responses=[
|
||||
{"joinTimesSec": {"other": 1}, "nextCursor": "next"},
|
||||
{"joinTimesSec": {"self": 123}, "nextCursor": None},
|
||||
],
|
||||
calls=[],
|
||||
)
|
||||
|
||||
def api(name, request):
|
||||
client.calls.append(request)
|
||||
return client.responses.pop(0)
|
||||
|
||||
client.api = api
|
||||
cache = tmp_path / "join-times.json"
|
||||
first = fetch_self_join_times(client, {"chat-a"}, cache)
|
||||
second = fetch_self_join_times(client, {"chat-a"}, cache)
|
||||
|
||||
assert first["chat-a"] == 123
|
||||
assert second["chat-a"] == 123
|
||||
assert len(client.calls) == 2
|
||||
assert client.calls[1]["cursor"] == "next"
|
||||
|
||||
|
||||
def test_missing_user_id_fails_closed(tmp_path):
|
||||
client = SimpleNamespace(auth=SimpleNamespace(user_id=""))
|
||||
|
||||
with pytest.raises(MembershipError):
|
||||
fetch_self_join_times(client, {"chat-a"}, tmp_path / "cache.json")
|
||||
|
||||
|
||||
def test_batch_prefetch_marks_inaccessible_group_unknown(tmp_path):
|
||||
client = SimpleNamespace(auth=SimpleNamespace(user_id="self"))
|
||||
|
||||
def fail_api(name, request):
|
||||
raise RuntimeError("synthetic inaccessible group")
|
||||
|
||||
client.api = fail_api
|
||||
result = fetch_self_join_times(
|
||||
client, {"chat-old"}, tmp_path / "cache.json", strict=False
|
||||
)
|
||||
|
||||
assert result["chat-old"] == 0
|
||||
@ -20,9 +20,11 @@ from snooper_summary import (
|
||||
format_followup_checkboxes,
|
||||
load_previous_summary,
|
||||
normalize_heading_breaks,
|
||||
normalize_self_name,
|
||||
previous_workday,
|
||||
require_efund_model,
|
||||
resolve_day,
|
||||
sanitize_wikilink_pipes,
|
||||
shorten_headings,
|
||||
summarize_messages,
|
||||
write_summary,
|
||||
@ -66,6 +68,22 @@ class FakeSession:
|
||||
})
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fake_membership_filter(monkeypatch):
|
||||
"""Keep legacy CLI tests offline; membership behavior has dedicated tests."""
|
||||
def identity(client, rows):
|
||||
return rows, {
|
||||
"included": len(rows),
|
||||
"excluded_before_join": 0,
|
||||
"excluded_unknown": 0,
|
||||
"excluded_chats": 0,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"snooper_membership.filter_rows_with_membership", identity
|
||||
)
|
||||
|
||||
|
||||
def synthetic_row(
|
||||
msg_id="m1",
|
||||
content="合成消息",
|
||||
@ -90,6 +108,32 @@ def synthetic_row(
|
||||
)
|
||||
|
||||
|
||||
def test_sanitize_wikilink_pipes_preserves_table_and_other_text():
|
||||
content = "| [[审核群|指数内容部落]] | 普通|文本 |\n[[人物|称呼]]"
|
||||
|
||||
assert sanitize_wikilink_pipes(content) == (
|
||||
"| [[审核群|指数内容部落]] | 普通|文本 |\n[[人物|称呼]]"
|
||||
)
|
||||
|
||||
|
||||
def test_system_only_private_chat_does_not_require_a_person_name():
|
||||
row = synthetic_row(chat_type=1, chat_name="", content="[系统消息]")
|
||||
row.msg_type = 6
|
||||
row.msg_type_name = "SYSTEM"
|
||||
session = FakeSession()
|
||||
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
|
||||
|
||||
result = summarize_messages(
|
||||
MagpieClient(DEFAULT_MODEL, session=session),
|
||||
[row],
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
)
|
||||
|
||||
assert "本日未收到消息" in result
|
||||
assert session.post_calls == []
|
||||
|
||||
|
||||
def test_model_policy_checks_actual_model_after_optional_routing_prefix():
|
||||
assert require_efund_model(DEFAULT_MODEL) == DEFAULT_MODEL
|
||||
assert require_efund_model("EFundGPT-other") == "EFundGPT-other"
|
||||
@ -216,8 +260,8 @@ def test_summary_is_per_conversation_before_daily_combination():
|
||||
|
||||
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
|
||||
|
||||
assert result == "最终日度总结"
|
||||
assert len(session.post_calls) == 3
|
||||
assert result == "同事甲:最终日度总结"
|
||||
assert len(session.post_calls) == 4
|
||||
prompts = [
|
||||
kwargs["json"]["messages"][1]["content"]
|
||||
for _, kwargs in session.post_calls
|
||||
@ -343,7 +387,7 @@ def test_summary_orders_chats_by_participation_private_human_and_bot():
|
||||
},
|
||||
)
|
||||
|
||||
assert result == "最终日度总结"
|
||||
assert result == "私聊:最终日度总结"
|
||||
prompts = [
|
||||
kwargs["json"]["messages"][1]["content"]
|
||||
for _, kwargs in session.post_calls
|
||||
@ -409,7 +453,7 @@ def test_private_chat_labels_keep_only_the_other_party():
|
||||
)
|
||||
|
||||
final_prompt = session.post_calls[1][1]["json"]["messages"][1]["content"]
|
||||
assert "### 排班" in final_prompt
|
||||
assert "### 排班([[赵六]])" in final_prompt
|
||||
assert "### 模型([[赵六]])" in final_prompt
|
||||
assert "私聊:" not in final_prompt
|
||||
assert "[[王五]] 与 [[赵六]]" not in final_prompt
|
||||
@ -470,6 +514,10 @@ def test_private_chat_name_is_derived_from_incoming_contact():
|
||||
assert result == "### 排班([[赵六]])"
|
||||
|
||||
|
||||
def test_generic_self_references_use_configured_self_name():
|
||||
assert normalize_self_name("当前用户与本人;伦伦本人", "Ben", set()) == "Ben与Ben;伦伦本人"
|
||||
|
||||
|
||||
def test_summary_uses_configured_self_name():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
@ -511,7 +559,7 @@ def test_summary_uses_configured_self_name():
|
||||
assert result == "[[Ben]] 与 [[赵六]] 确认"
|
||||
|
||||
|
||||
def test_private_name_may_be_omitted_from_topic_headings():
|
||||
def test_missing_human_private_summary_is_restored_with_chat_name():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
(DEFAULT_MODEL, "### 排班([[赵六]])"),
|
||||
@ -540,8 +588,9 @@ def test_private_name_may_be_omitted_from_topic_headings():
|
||||
sender_types={"other": 1},
|
||||
)
|
||||
|
||||
assert len(session.post_calls) == 2
|
||||
assert "私聊补充" not in result
|
||||
assert len(session.post_calls) == 3
|
||||
assert "### 排班([[赵六]])" in result
|
||||
assert result.count("### 排班([[赵六]])") == 1
|
||||
|
||||
|
||||
def test_multiple_private_sources_are_repaired_from_conversation_summaries():
|
||||
@ -676,6 +725,30 @@ def test_summary_applies_heading_normalization_to_model_output():
|
||||
assert "### 合成事项\n- 张三 确认。" in result
|
||||
|
||||
|
||||
def test_person_named_group_allows_missing_members_and_count_suffix():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五等8人]]:讨论需求"),
|
||||
(DEFAULT_MODEL, "[[吴九, [[李四]], 王五等8人]]:已确认需求"),
|
||||
]
|
||||
)
|
||||
client = MagpieClient(DEFAULT_MODEL, session=session)
|
||||
group_name = "吴九, 李四, 王五等8人"
|
||||
rows = [synthetic_row(chat_id="group-a", chat_name=group_name)]
|
||||
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
|
||||
|
||||
result = summarize_messages(
|
||||
client,
|
||||
rows,
|
||||
date(2026, 11, 3),
|
||||
tz,
|
||||
contacts={"group-a": {"u1": "吴九", "u2": "李四", "sender-test": "吴九"}},
|
||||
)
|
||||
|
||||
assert result == "吴九, 李四, 王五等8人:已确认需求"
|
||||
assert "[[吴九, [[李四]], 王五等8人]]" not in result
|
||||
|
||||
|
||||
def test_previous_day_summary_is_used_for_continuity():
|
||||
session = FakeSession(completions=[
|
||||
(DEFAULT_MODEL, "今日摘要"),
|
||||
@ -699,6 +772,22 @@ def test_previous_day_summary_is_used_for_continuity():
|
||||
assert "今日未见延续" in final_prompt
|
||||
|
||||
|
||||
def test_bare_group_name_heading_becomes_topic_heading():
|
||||
session = FakeSession(
|
||||
completions=[
|
||||
(DEFAULT_MODEL, "### [[项目群]]"),
|
||||
(DEFAULT_MODEL, "### [[项目群]]"),
|
||||
]
|
||||
)
|
||||
client = MagpieClient(DEFAULT_MODEL, session=session)
|
||||
rows = [synthetic_row(chat_id="group-a", chat_name="项目群")]
|
||||
_, _, _, tz = resolve_day("2026-11-03", "Asia/Shanghai")
|
||||
|
||||
result = summarize_messages(client, rows, date(2026, 11, 3), tz)
|
||||
|
||||
assert result == "### 沟通事项:[[项目群]]"
|
||||
|
||||
|
||||
def test_summary_enriches_names_and_requests_obsidian_wikilinks():
|
||||
session = FakeSession(completions=[
|
||||
(DEFAULT_MODEL, "张三确认了事项"),
|
||||
@ -735,8 +824,8 @@ def test_summary_enriches_names_and_requests_obsidian_wikilinks():
|
||||
assert "不通过通讯录强行补全本名" in system_prompt
|
||||
assert "[[会话名]]" in system_prompt
|
||||
assert "#tag" in system_prompt
|
||||
assert "[[张三]]" not in final_prompt
|
||||
assert "[[张三]]" not in result
|
||||
assert "[[张三]]确认了事项" in final_prompt
|
||||
assert "[[张三]]确认了事项" in result
|
||||
assert "Wikilink" in final_prompt
|
||||
|
||||
|
||||
@ -1142,6 +1231,7 @@ def test_cli_end_to_end_with_synthetic_db_and_fake_magpie(
|
||||
no_contacts=True,
|
||||
no_fetch=True,
|
||||
no_calendar=True,
|
||||
no_card_images=True,
|
||||
)
|
||||
assert cmd_summarize(args) == 0
|
||||
output_text = output.read_text(encoding="utf-8")
|
||||
@ -1304,6 +1394,7 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
||||
no_contacts=True,
|
||||
no_fetch=False,
|
||||
no_calendar=True,
|
||||
no_card_images=True,
|
||||
force_fetch=False,
|
||||
)
|
||||
|
||||
@ -1320,7 +1411,7 @@ def test_cli_summarize_prefetches_before_reading(tmp_path, monkeypatch):
|
||||
assert output.read_text(encoding="utf-8") == (
|
||||
"---\nversion: 0.1.0.dev0+test\n"
|
||||
f"model: {DEFAULT_MODEL}\nis_read: false\n"
|
||||
"tags:\n- no_previous_day_log\n---\n\n# 合成总结\n")
|
||||
"tags:\n- no_previous_day_log\n- no_previous_weekly\n---\n\n# 合成总结\n")
|
||||
|
||||
|
||||
def test_cli_model_failure_happens_before_storage_is_opened(monkeypatch):
|
||||
|
||||
187
tests/test_videos.py
Normal file
187
tests/test_videos.py
Normal file
@ -0,0 +1,187 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from snooper_summary import DEFAULT_MODEL, MagpieClient
|
||||
from snooper_videos import (
|
||||
_download_resumable,
|
||||
enrich_videos,
|
||||
frame_timestamps,
|
||||
video_path,
|
||||
)
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
status_code = 200
|
||||
|
||||
def json(self):
|
||||
return {
|
||||
"model": DEFAULT_MODEL,
|
||||
"choices": [{"message": {"content": "合成画面摘要"}}],
|
||||
}
|
||||
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self):
|
||||
self.post_calls = []
|
||||
|
||||
def post(self, url, **kwargs):
|
||||
self.post_calls.append((url, kwargs))
|
||||
return FakeResponse()
|
||||
|
||||
|
||||
class FakeAI:
|
||||
model = DEFAULT_MODEL
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def complete_with_images(self, images, prompt):
|
||||
self.calls.append((images, prompt))
|
||||
return "合成视频画面"
|
||||
|
||||
|
||||
def video_row(msg_id):
|
||||
return SimpleNamespace(
|
||||
msg_id=msg_id,
|
||||
msg_type=15,
|
||||
chat_id="chat-test",
|
||||
content="[视频]",
|
||||
content_data=json.dumps({
|
||||
"name": "synthetic.mp4",
|
||||
"duration": 120_000,
|
||||
"key": "synthetic-key",
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
def test_frame_timestamps_cover_entire_video_with_per_video_cap():
|
||||
timestamps = frame_timestamps(1696.4, max_frames=12)
|
||||
|
||||
assert len(timestamps) == 12
|
||||
assert timestamps[0] > 0
|
||||
assert timestamps[-1] < 1696.4
|
||||
assert timestamps[-1] - timestamps[0] > 1500
|
||||
assert frame_timestamps(1, max_frames=12) == [0.5]
|
||||
|
||||
|
||||
def test_video_path_uses_non_descriptive_stable_name(tmp_path):
|
||||
assert video_path(video_row("message-a"), tmp_path).name == "message-a.mp4"
|
||||
|
||||
|
||||
def test_download_resumes_partial_file(monkeypatch, tmp_path):
|
||||
path = tmp_path / "video.part"
|
||||
path.write_bytes(b"abc")
|
||||
calls = []
|
||||
|
||||
class Response:
|
||||
status_code = 206
|
||||
|
||||
def __init__(self):
|
||||
self.headers = {"content-length": "3"}
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return None
|
||||
|
||||
def raise_for_status(self):
|
||||
return None
|
||||
|
||||
def iter_content(self, size):
|
||||
yield b"def"
|
||||
|
||||
def fake_get(url, **kwargs):
|
||||
calls.append(kwargs)
|
||||
return Response()
|
||||
|
||||
monkeypatch.setattr("snooper_videos.requests.get", fake_get)
|
||||
_download_resumable(
|
||||
SimpleNamespace(cookies={}), "https://example.invalid", path, 1024
|
||||
)
|
||||
|
||||
assert path.read_bytes() == b"abcdef"
|
||||
assert calls[0]["headers"] == {"Range": "bytes=3-"}
|
||||
|
||||
|
||||
def test_complete_with_images_sends_all_frames_to_approved_model():
|
||||
session = FakeSession()
|
||||
client = MagpieClient(DEFAULT_MODEL, session=session)
|
||||
|
||||
result = client.complete_with_images(
|
||||
[(b"first", "image/jpeg"), (b"second", "image/jpeg")],
|
||||
"合成测试提示",
|
||||
)
|
||||
|
||||
assert result == "合成画面摘要"
|
||||
content = session.post_calls[0][1]["json"]["messages"][1]["content"]
|
||||
assert content[0] == {"type": "text", "text": "合成测试提示"}
|
||||
assert len(content) == 3
|
||||
assert all(item["type"] == "image_url" for item in content[1:])
|
||||
|
||||
|
||||
def test_enrich_videos_processes_every_row_and_local_audio(monkeypatch, tmp_path):
|
||||
rows = [video_row("message-a"), video_row("message-b")]
|
||||
ai = FakeAI()
|
||||
|
||||
def fake_download(client, row, directory):
|
||||
path = video_path(row, directory)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"video")
|
||||
return path, True
|
||||
|
||||
monkeypatch.setattr("snooper_videos.ensure_video_downloaded", fake_download)
|
||||
monkeypatch.setattr(
|
||||
"snooper_videos.extract_video_frames",
|
||||
lambda path, duration, max_frames: [(1.0, b"frame-a"), (2.0, b"frame-b")],
|
||||
)
|
||||
monkeypatch.setattr("snooper_videos.video_has_audio", lambda path: True)
|
||||
monkeypatch.setattr("snooper_videos.transcribe_video", lambda path, model: "合成音轨")
|
||||
|
||||
stats = enrich_videos(
|
||||
SimpleNamespace(), ai, rows,
|
||||
video_dir=tmp_path / "videos", analysis_dir=tmp_path / "analysis",
|
||||
)
|
||||
|
||||
assert stats["candidates"] == 2
|
||||
assert stats["enriched"] == 2
|
||||
assert stats["failed"] == 0
|
||||
assert stats["audio_transcribed"] == 2
|
||||
assert len(ai.calls) == 2
|
||||
assert len(ai.calls[0][0]) == 2
|
||||
for row in rows:
|
||||
assert "[视频画面] 合成视频画面" in row.content
|
||||
assert "[视频音轨转写] 合成音轨" in row.content
|
||||
|
||||
|
||||
def test_visual_analysis_is_cached_when_audio_needs_retry(monkeypatch, tmp_path):
|
||||
row = video_row("message-a")
|
||||
ai = FakeAI()
|
||||
|
||||
def fake_download(client, row, directory):
|
||||
path = video_path(row, directory)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b"video")
|
||||
return path, True
|
||||
|
||||
monkeypatch.setattr("snooper_videos.ensure_video_downloaded", fake_download)
|
||||
monkeypatch.setattr(
|
||||
"snooper_videos.extract_video_frames",
|
||||
lambda path, duration, max_frames: [(1.0, b"frame")],
|
||||
)
|
||||
monkeypatch.setattr("snooper_videos.video_has_audio", lambda path: True)
|
||||
|
||||
def fail_transcription(path, model):
|
||||
raise RuntimeError("synthetic transcription failure")
|
||||
|
||||
monkeypatch.setattr("snooper_videos.transcribe_video", fail_transcription)
|
||||
kwargs = {
|
||||
"video_dir": tmp_path / "videos", "analysis_dir": tmp_path / "analysis"
|
||||
}
|
||||
first = enrich_videos(SimpleNamespace(), ai, [row], **kwargs)
|
||||
second = enrich_videos(SimpleNamespace(), ai, [row], **kwargs)
|
||||
|
||||
assert first["audio_failed"] == 1
|
||||
assert second["audio_failed"] == 1
|
||||
assert second["cached"] == 1
|
||||
assert len(ai.calls) == 1
|
||||
118
tests/test_weekly.py
Normal file
118
tests/test_weekly.py
Normal file
@ -0,0 +1,118 @@
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from snooper_summary import summarize_messages
|
||||
from snooper_weekly import (
|
||||
WeeklyError,
|
||||
generate_weekly,
|
||||
load_previous_weekly_background,
|
||||
week_bounds,
|
||||
)
|
||||
|
||||
|
||||
def test_week_bounds_use_monday_and_sunday():
|
||||
assert week_bounds(date(2024, 7, 4)) == (
|
||||
date(2024, 7, 1), date(2024, 7, 7)
|
||||
)
|
||||
|
||||
|
||||
def test_previous_weekly_background_uses_previous_monday(tmp_path):
|
||||
output = {
|
||||
"summary": str(tmp_path / "Daily" / "Msg{date}.md"),
|
||||
"weekly": str(tmp_path / "Weekly" / "Week{date}.md"),
|
||||
}
|
||||
weekly = tmp_path / "Weekly" / "Week2024-07-01.md"
|
||||
weekly.parent.mkdir(parents=True)
|
||||
weekly.write_text("---\ntype: weekly\n---\n\n上周合成周记", encoding="utf-8")
|
||||
|
||||
content, missing = load_previous_weekly_background(output, date(2024, 7, 8))
|
||||
|
||||
assert content == "上周合成周记"
|
||||
assert missing is False
|
||||
|
||||
|
||||
def test_generate_weekly_reads_previous_week_and_sanitizes_links(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
daily = tmp_path / "Daily"
|
||||
weekly = tmp_path / "Weekly"
|
||||
daily.mkdir()
|
||||
weekly.mkdir()
|
||||
for day in ("2024-07-08", "2024-07-09"):
|
||||
(daily / f"Msg{day}.md").write_text(
|
||||
f"---\nmodel: synthetic\n---\n\n# {day}\n合成进展", encoding="utf-8"
|
||||
)
|
||||
(weekly / "Week2024-07-01.md").write_text("上周合成周记", encoding="utf-8")
|
||||
config = tmp_path / "config.yaml"
|
||||
config.write_text(
|
||||
f"output:\n summary: '{daily}/Msg{{date}}.md'\n"
|
||||
f" weekly: '{weekly}/Week{{date}}.md'\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, **kwargs):
|
||||
self.prompts = []
|
||||
self.responses = ["分日报提取", "周记[[审核群|指数内容部落]]"]
|
||||
|
||||
def assert_model_available(self):
|
||||
return None
|
||||
|
||||
def complete(self, prompt):
|
||||
self.prompts.append(prompt)
|
||||
return self.responses.pop(0)
|
||||
|
||||
clients = []
|
||||
monkeypatch.setattr(
|
||||
"snooper_weekly.MagpieClient",
|
||||
lambda **kwargs: clients.append(FakeClient(**kwargs)) or clients[-1],
|
||||
)
|
||||
|
||||
output = generate_weekly("2024-07-08", config_path=str(config))
|
||||
|
||||
text = output.read_text(encoding="utf-8")
|
||||
assert "[[审核群|指数内容部落]]" in text
|
||||
assert "type: weekly" in text
|
||||
assert "上周合成周记" in clients[0].prompts[-1]
|
||||
|
||||
|
||||
def test_existing_weekly_does_not_call_model(tmp_path):
|
||||
config = tmp_path / "config.yaml"
|
||||
output = tmp_path / "Week2024-07-08.md"
|
||||
output.write_text("已有周记", encoding="utf-8")
|
||||
config.write_text(
|
||||
f"output:\n weekly: '{output}'\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
with pytest.raises(WeeklyError, match="已存在"):
|
||||
generate_weekly("2024-07-08", config_path=str(config))
|
||||
|
||||
|
||||
def test_daily_final_prompt_receives_previous_weekly():
|
||||
class FakeAI:
|
||||
def __init__(self):
|
||||
self.prompts = []
|
||||
|
||||
def complete(self, prompt):
|
||||
self.prompts.append(prompt)
|
||||
return "单对话摘要" if len(self.prompts) == 1 else "最终日报"
|
||||
|
||||
row = SimpleNamespace(
|
||||
msg_id="m1", create_time=1_720_000_000, chat_id="group-a",
|
||||
chat_name="合成群", chat_type=2, sender_id="sender-a",
|
||||
sender_name="同事甲", msg_type=4, msg_type_name="TEXT",
|
||||
direction="in", content="合成消息", scope="chat", anchor="",
|
||||
root_id="", parent_id="", is_read=False,
|
||||
)
|
||||
ai = FakeAI()
|
||||
|
||||
result = summarize_messages(
|
||||
ai, [row], date(2024, 7, 8), ZoneInfo("Asia/Shanghai"),
|
||||
previous_weekly_summary="上周合成周记",
|
||||
)
|
||||
|
||||
assert result == "最终日报"
|
||||
assert "上周合成周记" in ai.prompts[-1]
|
||||
Reference in New Issue
Block a user