Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: 增量分析浏览记录口味

longmeidao50db7abc0594
diff --git a/README.md b/README.md
index d06724a21..c9ae369fd 100644
--- a/README.md
+++ b/README.md
@@ -106,6 +106,31 @@ worktree 目录。跨机器继续任务时 push 分支,在另一台按分支
`avatars`、`logos`、`covers`),走 Syncthing 单向复制,见下文「两台机器怎么保持一致」;
其余 durable artifacts 仍要先从缓存与本机状态里拆出来才能同步。
+### 浏览记录口味刷新
+
+`scripts/taste_history.py` 自动发现 Windows 的 Firefox、Zen、Chrome,以及 macOS 的
+Firefox、Zen、Chrome、Safari。它先用 SQLite backup API 取得浏览器仍在写入时也一致的只读副本,
+再把访问记录增量写入 `peach-data/sources/taste-history/history.sqlite`。原始 URL 和标题只在这个
+私有源库中;`peach-data/review/taste-history/` 的 Markdown/CSV 只包含聚合域名、口味维度和
+creator/tag candidate,不写 ledger,不自动批准。
+
+刷新本机全部浏览器并生成报告:
+
+```powershell
+python scripts/taste_history.py refresh
+```
+
+只用已有源库重新分析,或限制到某个时间点以后:
+
+```powershell
+python scripts/taste_history.py analyze --since 2026-08-01T00:00:00+00:00
+```
+
+Safari 的省事入口是让 iPhone/iPad 与 Mac 登录同一 Apple Account,并在两端 iCloud 设置中开启
+Safari;脚本读取 Mac 同步后的 `~/Library/Safari/History.db`,无需从 iPhone 手工导出。首次运行时
+终端/Codex 需要获得 macOS「完全磁盘访问权限」。Safari 历史有保留期限,因此至少每周刷新一次;
+Mac 外置盘未挂载导致 `peach-data/sources` 断链时必须报错,不得静默丢证据。
+
以上是约定的分层。Mac 上的实际形状有出入:真实目录名是 `artifacts`,`generated` 是指向它的
符号链接,另有 `review`、`tmp`,`archive`/`sources`/`tools` 指向外置盘,盘不在时是断链。
排查路径问题时以 `docs/STATUS.md` 的实测记录为准,不要按这张表推断某个目录一定存在。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index f73e6a3e3..cee476958 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -9,7 +9,7 @@
3. **在线追更**:kemono/coomer/pawchive、rule34video、rule34.xxx、f95zone 五类连接器、WIP/alt/跨站重复判定、`follow_source`/`follow_item`、`peach follow`、看的 `/follow` 与管的 `/follow-manage` 两个页面(粘链接或只给名字/id,自动跨六个来源查找)已上线;仍缺定时轮询(APScheduler)、媒体下载落地,以及 simpcity 的可用入口(DDoS-Guard,未取得)。
4. **首尾帧出处与不完整候选**:已有受限 FFmpeg 首尾抽帧、Windows 内置 OCR、证据帧缓存、来源/Full version 候选和 `/review`;仍需决定全库批次范围,并把用户批准后的不完整版判断接到更好版本目标。
5. **厂牌 Logo 补齐与持续校验**:14 个已确认社交 handle 已有内容缓存、provenance、精确/感知哈希、质量与重复门槛及健康报告;仍有 72 个厂牌没有可信 handle,必须继续从官网/公开来源取证,不能猜账号。
-6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;2026-08-13 的浏览器、Takeout、Telegram、关注列表与库存原始输入也保留在外置盘 `peach-data/sources`。仍需实现 Windows/macOS 浏览器库的一致性快照、来源 manifest、只处理新增时间段的归一化与差异报告、按月生成可复核的创作者/tag/缺口候选;原始 URL 不进 Git、不进日志,AI 结论不得直接改真相字段。
+6. **口味证据持续刷新**:ledger 已实时记录搜索、播放、高潮、喜欢/理由、不合口味和稍后看;浏览器历史现可用 SQLite 一致性副本增量进入私有源库,并生成不含 URL/标题的 creator/tag candidate 与聚合报告。旧 2026-08-13 原始包已确认不在 Windows 外置盘;仍需在 Mac 开启 iCloud Safari、完成首次导入,并把两端每周刷新装成系统计划任务。AI 结论不得直接改真相字段。
## 尚未实现(6 项)
diff --git a/docs/STATUS.md b/docs/STATUS.md
index eb989f6af..e31e09745 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -70,11 +70,16 @@
当时已从 `R:\Resources\Sources` 完整迁到 `R:\peach-data\sources`,共 67 个文件、
约 421.5 MB;Mac 传回的 `mac/` 包含 `zen-places.sqlite`、`zen-history.tsv`、
`zen-visits.tsv`、`safari-History.db` 和 `taste-raw.zip`,其余分在 `takeout/`、
- `browsers/`、`telegram/`、`follows/`、`inventories/`、`dedup/`、`reports/`。当前 Windows
- 未挂载 `R:`,所以这些外置盘文件的现存状态**未取得**;Windows 内置盘
- `peach-data/sources` 目前只有 `metadata/`。现有 ledger 已持续保存搜索、播放、高潮、
- 喜欢/理由、不合口味和稍后看等行为,但浏览器/Takeout 原始证据在 2026-08-13 后没有
- 正式的增量快照、差异报告和口味候选刷新入口。
+ `browsers/`、`telegram/`、`follows/`、`inventories/`、`dedup/`、`reports/`。随后在 Windows
+ 实测 `R:` 已挂载为 `RESOURCES`(exFAT,约 1 TB),但 `R:\peach-data\sources`、旧
+ `R:\Resources\Sources` 和回收站都没有这批文件,按已删除处理;Mac 上旧副本的现存状态
+ **未取得**。
+- 浏览记录增量刷新已实现:`scripts/taste_history.py` 用 SQLite backup API 一致性读取浏览器活库,
+ 原始 URL/标题只增量写入本机 `peach-data/sources/taste-history/history.sqlite`,聚合报告与
+ creator/tag candidate 写 `peach-data/review/taste-history/`,不写 ledger。2026-08-26 Windows
+ 首批发现 Chrome 1、Firefox 4、Zen 2 共 7 个 profile,导入 382,781 次访问,时间范围
+ 2025-11-08 至 2026-08-26;报告不含完整 URL 或标题。Mac Safari 活库本轮**未取得**,待
+ iCloud Safari 同步开启且 Mac 可执行后补入同一流程。
- 追更的「查找」在只读端一度返回 409:`/api/follow/resolve` 只联网发现、不碰账本,
却因为是 POST 被写入端闸门一并拦掉。已按 `READ_ONLY_POST_ROUTES` 白名单放行;
真正会写的 `check`/`save`/`status`/`source` 仍受闸门管辖。
diff --git a/scripts/taste_history.py b/scripts/taste_history.py
new file mode 100644
index 000000000..328723c7a
--- /dev/null
+++ b/scripts/taste_history.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+from peach.config import DATA_ROOT, SOURCES_DIR, STATE_DIR
+from peach.taste_history import (
+ HistorySource,
+ analyze_history,
+ discover_history_sources,
+ refresh_history,
+ write_manifest,
+)
+
+
+def _parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="增量采集并分析 Firefox、Zen、Chrome、Safari 浏览记录")
+ parser.add_argument("action", choices=("discover", "refresh", "analyze"))
+ parser.add_argument("--store", type=Path, default=SOURCES_DIR / "taste-history" / "history.sqlite")
+ parser.add_argument("--output", type=Path, default=DATA_ROOT / "review" / "taste-history")
+ parser.add_argument("--manifest", type=Path, default=STATE_DIR / "taste-history" / "manifest.json")
+ parser.add_argument("--since", help="只分析此 ISO 时间之后的记录")
+ parser.add_argument(
+ "--source",
+ action="append",
+ default=[],
+ metavar="BROWSER=PATH",
+ help="显式增加浏览器数据库;可重复指定",
+ )
+ return parser
+
+
+def _explicit_sources(values: list[str]) -> list[HistorySource]:
+ sources: list[HistorySource] = []
+ for value in values:
+ browser, separator, raw_path = value.partition("=")
+ if not separator or browser not in {"chrome", "firefox", "safari", "zen"}:
+ raise SystemExit(f"无效 --source:{value};格式应为 BROWSER=PATH")
+ path = Path(raw_path).expanduser()
+ if not path.is_file():
+ raise SystemExit(f"浏览记录数据库不存在:{path}")
+ sources.append(HistorySource(browser, path.parent.name, path))
+ return sources
+
+
+def main() -> int:
+ args = _parser().parse_args()
+ sources = discover_history_sources() + _explicit_sources(args.source)
+ unique = {(source.browser, source.profile, source.path.resolve()): source for source in sources}
+ sources = list(unique.values())
+ if args.action == "discover":
+ print(json.dumps([
+ {"browser": source.browser, "profile": source.profile, "path": str(source.path)}
+ for source in sources
+ ], ensure_ascii=False, indent=2))
+ return 0
+ refresh_results: list[dict[str, object]] = []
+ if args.action == "refresh":
+ if not sources:
+ raise SystemExit("未发现浏览器历史数据库")
+ refresh_results = refresh_history(sources, args.store)
+ if not args.store.is_file():
+ raise SystemExit(f"历史库不存在:{args.store}")
+ analysis = analyze_history(args.store, args.output, since=args.since)
+ write_manifest(args.manifest, refresh_results, analysis)
+ print(json.dumps({"refresh": refresh_results, "analysis": analysis}, ensure_ascii=False, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/peach/taste_history.py b/src/peach/taste_history.py
new file mode 100644
index 000000000..3a12726fa
--- /dev/null
+++ b/src/peach/taste_history.py
@@ -0,0 +1,400 @@
+from __future__ import annotations
+
+import csv
+import hashlib
+import json
+import re
+import socket
+import sqlite3
+import tempfile
+from collections import Counter, defaultdict
+from contextlib import closing
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from pathlib import Path
+from urllib.parse import parse_qs, unquote, urlparse
+
+
+@dataclass(frozen=True)
+class HistorySource:
+ browser: str
+ profile: str
+ path: Path
+
+
+@dataclass(frozen=True)
+class HistoryVisit:
+ visit_key: str
+ visited_at: str
+ url: str
+ title: str
+
+
+QUERY_KEYS = {"q", "query", "search", "keyword", "keywords", "tag", "tags", "term"}
+CREATOR_MARKERS = {"artist", "artists", "author", "channel", "creator", "creators", "model", "models", "profile"}
+CREATOR_HOSTS = {"fansly.com", "onlyfans.com", "patreon.com", "rule34video.com"}
+RESERVED_HANDLES = {
+ "about", "account", "creator", "creators", "explore", "home", "login", "messages", "model",
+ "models", "notifications", "post", "posts", "search", "settings", "share", "user", "users",
+}
+STOPWORDS = {
+ "and", "com", "download", "for", "from", "html", "http", "https", "in", "index", "is",
+ "login", "of", "one", "page", "search", "the", "this", "to", "video", "watch", "www",
+ "图片", "搜索", "视频",
+}
+TASTE_DOMAIN_SUFFIXES = {
+ "cangku.moe", "coomer.st", "e-hentai.org", "exhentai.org", "f95zone.to", "fanbox.cc",
+ "fansly.com", "fantia.jp", "gelbooru.com", "hanime1.me", "jable.tv", "javbus.com",
+ "javdb.com", "kemono.cr", "kemono.su", "missav.com", "nhentai.net", "onlyfans.com",
+ "patreon.com", "pawchive.com", "pixiv.net", "pornhub.com", "redgifs.com", "rule34.xxx",
+ "rule34video.com", "simpcity.cr", "simpcity.su", "south-plus.org", "spankbang.com",
+ "supjav.com", "xhamster.com", "xsijishe.com", "xvideos.com",
+}
+CATEGORY_TERMS: dict[str, set[str]] = {
+ "足系": {"feet", "foot", "footjob", "soles", "toes", "足", "足交", "脚", "脚交"},
+ "3D/动画": {"3d", "animation", "blender", "daz", "sfm", "动画"},
+ "制服/角色扮演": {"cosplay", "jk", "maid", "schoolgirl", "uniform", "制服", "女仆", "角色扮演"},
+ "乳系": {"bigbreasts", "bigboobs", "boobs", "breasts", "tits", "巨乳", "乳"},
+ "口交": {"blowjob", "deepthroat", "oral", "口交", "深喉"},
+ "马眼/尿道/龟头": {"glans", "glansjob", "sounding", "urethra", "尿道", "马眼", "龟头"},
+ "ASMR/音声": {"asmr", "audio", "音声"},
+ "游戏同人": {"game", "gamecg", "hgame", "游戏", "同人"},
+ "反差/泄密/探花": {"leak", "leaked", "private", "反差", "探花", "泄密", "流出"},
+}
+
+
+def discover_history_sources(
+ *,
+ home: Path | None = None,
+ appdata: Path | None = None,
+ localappdata: Path | None = None,
+ platform_name: str | None = None,
+) -> list[HistorySource]:
+ platform_name = platform_name or ("windows" if __import__("os").name == "nt" else "macos")
+ home = home or Path.home()
+ candidates: list[tuple[str, Path]] = []
+ if platform_name == "windows":
+ appdata = appdata or home / "AppData" / "Roaming"
+ localappdata = localappdata or home / "AppData" / "Local"
+ candidates.extend(
+ [
+ ("firefox", appdata / "Mozilla" / "Firefox" / "Profiles"),
+ ("zen", appdata / "zen" / "Profiles"),
+ ("chrome", localappdata / "Google" / "Chrome" / "User Data"),
+ ]
+ )
+ else:
+ candidates.extend(
+ [
+ ("firefox", home / "Library" / "Application Support" / "Firefox" / "Profiles"),
+ ("zen", home / "Library" / "Application Support" / "zen" / "Profiles"),
+ ("chrome", home / "Library" / "Application Support" / "Google" / "Chrome"),
+ ]
+ )
+
+ found: list[HistorySource] = []
+ for browser, root in candidates:
+ if not root.is_dir():
+ continue
+ filename = "History" if browser == "chrome" else "places.sqlite"
+ for path in root.glob(f"*/{filename}"):
+ if path.is_file():
+ found.append(HistorySource(browser, path.parent.name, path))
+ if platform_name == "macos":
+ safari = home / "Library" / "Safari" / "History.db"
+ if safari.is_file():
+ found.append(HistorySource("safari", "iCloud", safari))
+ return sorted(found, key=lambda source: (source.browser, source.profile.casefold()))
+
+
+def _readonly_uri(path: Path) -> str:
+ return f"file:{path.resolve().as_posix()}?mode=ro"
+
+
+def _consistent_copy(source: Path, destination: Path) -> None:
+ with closing(sqlite3.connect(_readonly_uri(source), uri=True)) as source_db:
+ with closing(sqlite3.connect(destination)) as destination_db:
+ source_db.backup(destination_db)
+
+
+def _iso_from_unix_microseconds(value: int | float) -> str:
+ return datetime.fromtimestamp(float(value) / 1_000_000, UTC).isoformat()
+
+
+def _iso_from_chrome(value: int | float) -> str:
+ return (datetime(1601, 1, 1, tzinfo=UTC) + timedelta(microseconds=float(value))).isoformat()
+
+
+def _iso_from_safari(value: int | float) -> str:
+ return (datetime(2001, 1, 1, tzinfo=UTC) + timedelta(seconds=float(value))).isoformat()
+
+
+def _read_visits(snapshot: Path, browser: str) -> list[HistoryVisit]:
+ with closing(sqlite3.connect(snapshot)) as db:
+ if browser in {"firefox", "zen"}:
+ rows = db.execute(
+ "SELECT v.id, v.visit_date, p.url, COALESCE(p.title, '') "
+ "FROM moz_historyvisits v JOIN moz_places p ON p.id = v.place_id "
+ "WHERE v.visit_date IS NOT NULL AND p.url IS NOT NULL"
+ )
+ convert = _iso_from_unix_microseconds
+ elif browser == "chrome":
+ rows = db.execute(
+ "SELECT v.id, v.visit_time, u.url, COALESCE(u.title, '') "
+ "FROM visits v JOIN urls u ON u.id = v.url "
+ "WHERE v.visit_time IS NOT NULL AND u.url IS NOT NULL"
+ )
+ convert = _iso_from_chrome
+ elif browser == "safari":
+ rows = db.execute(
+ "SELECT v.id, v.visit_time, i.url, COALESCE(v.title, '') "
+ "FROM history_visits v JOIN history_items i ON i.id = v.history_item "
+ "WHERE v.visit_time IS NOT NULL AND i.url IS NOT NULL"
+ )
+ convert = _iso_from_safari
+ else:
+ raise ValueError(f"不支持的浏览器类型:{browser}")
+ return [HistoryVisit(str(row[0]), convert(row[1]), row[2], row[3]) for row in rows]
+
+
+def _source_key(source: HistorySource, host: str) -> str:
+ identity = f"{host}\0{source.browser}\0{source.profile}\0{source.path.resolve()}"
+ return hashlib.sha256(identity.encode("utf-8")).hexdigest()
+
+
+def _prepare_store(db: sqlite3.Connection) -> None:
+ db.executescript(
+ """
+ PRAGMA journal_mode=WAL;
+ CREATE TABLE IF NOT EXISTS history_source (
+ source_key TEXT PRIMARY KEY,
+ browser TEXT NOT NULL,
+ profile TEXT NOT NULL,
+ host TEXT NOT NULL,
+ path_hash TEXT NOT NULL,
+ first_seen_at TEXT NOT NULL,
+ last_seen_at TEXT NOT NULL
+ );
+ CREATE TABLE IF NOT EXISTS history_visit (
+ source_key TEXT NOT NULL REFERENCES history_source(source_key),
+ visit_key TEXT NOT NULL,
+ visited_at TEXT NOT NULL,
+ url TEXT NOT NULL,
+ title TEXT NOT NULL,
+ PRIMARY KEY (source_key, visit_key)
+ );
+ CREATE INDEX IF NOT EXISTS history_visit_time_idx ON history_visit(visited_at);
+ """
+ )
+
+
+def refresh_history(
+ sources: list[HistorySource],
+ store_path: Path,
+ *,
+ host: str | None = None,
+) -> list[dict[str, object]]:
+ host = host or socket.gethostname()
+ store_path.parent.mkdir(parents=True, exist_ok=True)
+ now = datetime.now(UTC).isoformat()
+ results: list[dict[str, object]] = []
+ with closing(sqlite3.connect(store_path)) as store:
+ _prepare_store(store)
+ for source in sources:
+ with tempfile.TemporaryDirectory(prefix="peach-history-") as temp_dir:
+ snapshot = Path(temp_dir) / "history.sqlite"
+ _consistent_copy(source.path, snapshot)
+ visits = _read_visits(snapshot, source.browser)
+ source_key = _source_key(source, host)
+ path_hash = hashlib.sha256(str(source.path.resolve()).encode("utf-8")).hexdigest()
+ store.execute(
+ "INSERT INTO history_source VALUES (?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(source_key) DO UPDATE SET last_seen_at=excluded.last_seen_at",
+ (source_key, source.browser, source.profile, host, path_hash, now, now),
+ )
+ before = store.total_changes
+ store.executemany(
+ "INSERT OR IGNORE INTO history_visit(source_key, visit_key, visited_at, url, title) "
+ "VALUES (?, ?, ?, ?, ?)",
+ ((source_key, visit.visit_key, visit.visited_at, visit.url, visit.title) for visit in visits),
+ )
+ added = store.total_changes - before
+ results.append(
+ {"browser": source.browser, "profile": source.profile, "visits": len(visits), "added": added}
+ )
+ store.commit()
+ return results
+
+
+def _tokens(value: str) -> set[str]:
+ decoded = unquote(value).casefold().replace("_", " ").replace("-", " ")
+ values = re.findall(r"[a-z0-9]{2,}|[\u3400-\u9fff]{1,12}", decoded)
+ return {value for value in values if value not in STOPWORDS and not value.isdigit()}
+
+
+def _is_taste_domain(domain: str) -> bool:
+ return any(domain == suffix or domain.endswith(f".{suffix}") for suffix in TASTE_DOMAIN_SUFFIXES)
+
+
+def _creator_candidate(value: str) -> str | None:
+ candidate = unquote(value).casefold().strip("@ ")
+ if candidate in RESERVED_HANDLES or candidate.isdigit() or not (3 <= len(candidate) <= 80):
+ return None
+ if re.fullmatch(r"[0-9a-f]{24,}", candidate):
+ return None
+ if not re.fullmatch(r"[a-z0-9._-]+|[\u3400-\u9fff][\u3400-\u9fff·._-]*", candidate):
+ return None
+ return candidate
+
+
+def _url_candidates(url: str) -> tuple[str | None, set[str], set[str]]:
+ parsed = urlparse(url)
+ if parsed.scheme not in {"http", "https"}:
+ return None, set(), set()
+ domain = (parsed.hostname or "").casefold()
+ if domain.startswith("www."):
+ domain = domain[4:]
+ if not _is_taste_domain(domain):
+ return domain or None, set(), set()
+ tags: set[str] = set()
+ for key, values in parse_qs(parsed.query).items():
+ if key.casefold() in QUERY_KEYS:
+ for value in values:
+ tags.update(_tokens(value))
+
+ segments = [unquote(segment).casefold() for segment in parsed.path.split("/") if segment]
+ creators: set[str] = set()
+ for index, segment in enumerate(segments[:-1]):
+ candidate = _creator_candidate(segments[index + 1])
+ if segment in CREATOR_MARKERS and candidate:
+ creators.add(candidate)
+ if domain in CREATOR_HOSTS and segments:
+ if domain != "rule34video.com" or segments[0] in {"model", "models"}:
+ candidate = _creator_candidate(segments[-1] if domain == "rule34video.com" else segments[0])
+ if candidate:
+ creators.add(candidate)
+ return domain or None, tags, creators
+
+
+def analyze_history(store_path: Path, output_dir: Path, *, since: str | None = None) -> dict[str, object]:
+ output_dir.mkdir(parents=True, exist_ok=True)
+ query = (
+ "SELECT v.source_key, v.visited_at, v.url, s.browser, s.profile "
+ "FROM history_visit v JOIN history_source s ON s.source_key = v.source_key"
+ )
+ params: tuple[str, ...] = ()
+ if since:
+ query += " WHERE v.visited_at >= ?"
+ params = (since,)
+ domains: Counter[str] = Counter()
+ tag_visits: Counter[str] = Counter()
+ creator_visits: Counter[str] = Counter()
+ tag_urls: dict[str, set[str]] = defaultdict(set)
+ creator_urls: dict[str, set[str]] = defaultdict(set)
+ tag_sources: dict[str, set[str]] = defaultdict(set)
+ creator_sources: dict[str, set[str]] = defaultdict(set)
+ category_visits: Counter[str] = Counter()
+ min_time: str | None = None
+ max_time: str | None = None
+ total = 0
+ with closing(sqlite3.connect(store_path)) as db:
+ source_count = db.execute("SELECT COUNT(*) FROM history_source").fetchone()[0]
+ for source_key, visited_at, url, browser, profile in db.execute(query, params):
+ total += 1
+ min_time = visited_at if min_time is None or visited_at < min_time else min_time
+ max_time = visited_at if max_time is None or visited_at > max_time else max_time
+ domain, tags, creators = _url_candidates(url)
+ if domain:
+ domains[domain] += 1
+ url_hash = hashlib.sha256(url.encode("utf-8")).hexdigest()
+ source_label = f"{browser}:{profile}"
+ for tag in tags:
+ tag_visits[tag] += 1
+ tag_urls[tag].add(url_hash)
+ tag_sources[tag].add(source_label)
+ compact = tag.replace(" ", "")
+ for category, terms in CATEGORY_TERMS.items():
+ if compact in terms or tag in terms:
+ category_visits[category] += 1
+ for creator in creators:
+ creator_visits[creator] += 1
+ creator_urls[creator].add(url_hash)
+ creator_sources[creator].add(source_label)
+
+ stamp = datetime.now().astimezone().strftime("%Y%m%d-%H%M%S")
+ tag_path = output_dir / f"taste-tag-candidates-{stamp}.csv"
+ creator_path = output_dir / f"taste-creator-candidates-{stamp}.csv"
+ report_path = output_dir / f"taste-report-{stamp}.md"
+ _write_candidates(tag_path, "tag", tag_visits, tag_urls, tag_sources)
+ _write_candidates(creator_path, "creator", creator_visits, creator_urls, creator_sources)
+
+ lines = [
+ "# 浏览记录口味分析",
+ "",
+ f"- 生成时间:{datetime.now().astimezone().isoformat(timespec='seconds')}",
+ f"- 范围:{min_time or '无'} 至 {max_time or '无'}",
+ f"- 访问记录:{total:,}",
+ f"- 数据源:{source_count}",
+ "- 隐私:报告不含完整 URL、页面标题或原始搜索记录;所有结论均为 candidate。",
+ "",
+ ]
+ _append_ranking(lines, "口味维度候选", category_visits)
+ _append_ranking(lines, "Tag 候选", tag_visits)
+ _append_ranking(lines, "创作者候选", creator_visits)
+ _append_ranking(lines, "高频域名", domains)
+ report_path.write_text("\n".join(lines), encoding="utf-8")
+ return {
+ "visits": total,
+ "sources": source_count,
+ "range_start": min_time,
+ "range_end": max_time,
+ "report": str(report_path),
+ "tags": str(tag_path),
+ "creators": str(creator_path),
+ }
+
+
+def _write_candidates(
+ path: Path,
+ kind: str,
+ visits: Counter[str],
+ urls: dict[str, set[str]],
+ sources: dict[str, set[str]],
+) -> None:
+ with path.open("w", encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(
+ handle,
+ fieldnames=["candidate", "kind", "visits", "distinct_urls", "source_count", "sources", "status"],
+ )
+ writer.writeheader()
+ for candidate, count in visits.most_common():
+ writer.writerow(
+ {
+ "candidate": candidate,
+ "kind": kind,
+ "visits": count,
+ "distinct_urls": len(urls[candidate]),
+ "source_count": len(sources[candidate]),
+ "sources": " | ".join(sorted(sources[candidate])),
+ "status": "candidate",
+ }
+ )
+
+
+def _append_ranking(lines: list[str], title: str, values: Counter[str], limit: int = 30) -> None:
+ lines.extend([f"## {title}", "", "| 候选 | 访问次数 |", "| --- | ---: |"])
+ if values:
+ lines.extend(f"| {name.replace('|', '\\|')} | {count:,} |" for name, count in values.most_common(limit))
+ else:
+ lines.append("| 未提取到 | 0 |")
+ lines.append("")
+
+
+def write_manifest(path: Path, refresh_results: list[dict[str, object]], analysis: dict[str, object]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ payload = {
+ "updated_at": datetime.now(UTC).isoformat(),
+ "refresh": refresh_results,
+ "analysis": analysis,
+ }
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
diff --git a/tests/test_taste_history.py b/tests/test_taste_history.py
new file mode 100644
index 000000000..ddcff10bb
--- /dev/null
+++ b/tests/test_taste_history.py
@@ -0,0 +1,95 @@
+import csv
+import sqlite3
+import tempfile
+import unittest
+from contextlib import closing
+from pathlib import Path
+
+from peach.taste_history import HistorySource, analyze_history, discover_history_sources, refresh_history
+
+
+class TasteHistoryTests(unittest.TestCase):
+ def setUp(self):
+ self.temp_dir = tempfile.TemporaryDirectory()
+ self.root = Path(self.temp_dir.name)
+
+ def tearDown(self):
+ self.temp_dir.cleanup()
+
+ def _firefox_db(self, path: Path) -> None:
+ path.parent.mkdir(parents=True)
+ with closing(sqlite3.connect(path)) as db:
+ db.executescript(
+ "CREATE TABLE moz_places(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
+ "CREATE TABLE moz_historyvisits(id INTEGER PRIMARY KEY, place_id INTEGER, visit_date INTEGER);"
+ )
+ db.execute("INSERT INTO moz_places VALUES (1, ?, ?)", ("https://rule34.xxx/search?tags=feet+cosplay", "secret"))
+ db.execute("INSERT INTO moz_historyvisits VALUES (1, 1, 1700000000000000)")
+ db.commit()
+
+ def _chrome_db(self, path: Path) -> None:
+ path.parent.mkdir(parents=True)
+ with closing(sqlite3.connect(path)) as db:
+ db.executescript(
+ "CREATE TABLE urls(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
+ "CREATE TABLE visits(id INTEGER PRIMARY KEY, url INTEGER, visit_time INTEGER);"
+ )
+ db.execute("INSERT INTO urls VALUES (1, ?, ?)", ("https://onlyfans.com/creator_name", "private title"))
+ db.execute("INSERT INTO visits VALUES (2, 1, 13344473600000000)")
+ db.commit()
+
+ def _safari_db(self, path: Path) -> None:
+ path.parent.mkdir(parents=True)
+ with closing(sqlite3.connect(path)) as db:
+ db.executescript(
+ "CREATE TABLE history_items(id INTEGER PRIMARY KEY, url TEXT);"
+ "CREATE TABLE history_visits(id INTEGER PRIMARY KEY, history_item INTEGER, visit_time REAL, title TEXT);"
+ )
+ db.execute("INSERT INTO history_items VALUES (1, ?)", ("https://rule34video.com/models/alice/",))
+ db.execute("INSERT INTO history_visits VALUES (3, 1, 700000000, 'hidden')")
+ db.commit()
+
+ def test_discovers_windows_firefox_and_chrome_profiles(self):
+ roaming = self.root / "Roaming"
+ local = self.root / "Local"
+ self._firefox_db(roaming / "Mozilla" / "Firefox" / "Profiles" / "default" / "places.sqlite")
+ self._chrome_db(local / "Google" / "Chrome" / "User Data" / "Default" / "History")
+ sources = discover_history_sources(
+ home=self.root, appdata=roaming, localappdata=local, platform_name="windows"
+ )
+ self.assertEqual([source.browser for source in sources], ["chrome", "firefox"])
+
+ def test_refresh_is_incremental_and_report_omits_urls_and_titles(self):
+ firefox = self.root / "firefox" / "places.sqlite"
+ chrome = self.root / "chrome" / "History"
+ safari = self.root / "Safari" / "History.db"
+ self._firefox_db(firefox)
+ self._chrome_db(chrome)
+ self._safari_db(safari)
+ sources = [
+ HistorySource("firefox", "default", firefox),
+ HistorySource("chrome", "Default", chrome),
+ HistorySource("safari", "iCloud", safari),
+ ]
+ store = self.root / "sources" / "history.sqlite"
+ first = refresh_history(sources, store, host="test-host")
+ second = refresh_history(sources, store, host="test-host")
+ self.assertEqual(sum(item["added"] for item in first), 3)
+ self.assertEqual(sum(item["added"] for item in second), 0)
+
+ output = self.root / "review"
+ result = analyze_history(store, output)
+ report = Path(result["report"]).read_text(encoding="utf-8")
+ self.assertIn("足系", report)
+ self.assertIn("cosplay", report)
+ self.assertIn("alice", report)
+ self.assertNotIn("https://", report)
+ self.assertNotIn("secret", report)
+ self.assertNotIn("private title", report)
+ with Path(result["creators"]).open(encoding="utf-8-sig", newline="") as handle:
+ creators = {row["candidate"] for row in csv.DictReader(handle)}
+ self.assertEqual(creators, {"alice", "creator_name"})
+
+
+if __name__ == "__main__":
+ unittest.main()