Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 导入 Google Takeout 口味历史

Peach local maintenancee7f93310b08b
diff --git a/README.md b/README.md
index c9ae369fd..dea04d7be 100644
--- a/README.md
+++ b/README.md
@@ -120,6 +120,14 @@ creator/tag candidate,不写 ledger,不自动批准。
python scripts/taste_history.py refresh
```
+Chrome 历史已清理但 Google Takeout 仍在时,显式增加 ZIP。脚本读取 `Chrome/History.json`,
+以及 My Activity 中的 Chrome、Search、Image Search、Video Search,解除 Google 跳转包装,
+并按「同 URL、同秒的最大出现次数」与所有既有来源跨源去重;不会把 ZIP 解压到磁盘:
+
+```powershell
+python scripts/taste_history.py refresh --takeout ~/Downloads/takeout-YYYYMMDD-001.zip
+```
+
只用已有源库重新分析,或限制到某个时间点以后:
```powershell
diff --git a/scripts/taste_history.py b/scripts/taste_history.py
index 328723c7a..47c7ae3ea 100644
--- a/scripts/taste_history.py
+++ b/scripts/taste_history.py
@@ -10,6 +10,7 @@ from peach.taste_history import (
analyze_history,
discover_history_sources,
refresh_history,
+ refresh_takeout_history,
write_manifest,
)
@@ -21,6 +22,14 @@ def _parser() -> argparse.ArgumentParser:
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(
+ "--takeout",
+ action="append",
+ default=[],
+ type=Path,
+ metavar="ZIP",
+ help="显式导入 Google Takeout ZIP;可重复指定",
+ )
parser.add_argument(
"--source",
action="append",
@@ -46,6 +55,10 @@ def _explicit_sources(values: list[str]) -> list[HistorySource]:
def main() -> int:
args = _parser().parse_args()
+ takeouts = [path.expanduser() for path in args.takeout]
+ missing_takeouts = [path for path in takeouts if not path.is_file()]
+ if missing_takeouts:
+ raise SystemExit(f"Takeout 不存在:{missing_takeouts[0]}")
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())
@@ -57,9 +70,12 @@ def main() -> int:
return 0
refresh_results: list[dict[str, object]] = []
if args.action == "refresh":
- if not sources:
+ if not sources and not takeouts:
raise SystemExit("未发现浏览器历史数据库")
- refresh_results = refresh_history(sources, args.store)
+ if sources:
+ refresh_results = refresh_history(sources, args.store)
+ if takeouts:
+ refresh_results.extend(refresh_takeout_history(takeouts, args.store))
if not args.store.is_file():
raise SystemExit(f"历史库不存在:{args.store}")
analysis = analyze_history(args.store, args.output, since=args.since)
diff --git a/src/peach/taste_history.py b/src/peach/taste_history.py
index 3a12726fa..27e773851 100644
--- a/src/peach/taste_history.py
+++ b/src/peach/taste_history.py
@@ -7,12 +7,15 @@ import re
import socket
import sqlite3
import tempfile
+import zipfile
from collections import Counter, defaultdict
from contextlib import closing
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
+from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
+from zoneinfo import ZoneInfo
@dataclass(frozen=True)
@@ -61,6 +64,17 @@ CATEGORY_TERMS: dict[str, set[str]] = {
"游戏同人": {"game", "gamecg", "hgame", "游戏", "同人"},
"反差/泄密/探花": {"leak", "leaked", "private", "反差", "探花", "泄密", "流出"},
}
+TAKEOUT_HISTORY_MEMBER = "Takeout/Chrome/History.json"
+TAKEOUT_ACTIVITY_MEMBERS = (
+ ("chrome", "Google My Activity - Chrome", "Takeout/My Activity/Chrome/MyActivity.html"),
+ ("google_activity", "Google My Activity - Search", "Takeout/My Activity/Search/MyActivity.html"),
+ ("google_activity", "Google My Activity - Image Search", "Takeout/My Activity/Image Search/MyActivity.html"),
+ ("google_activity", "Google My Activity - Video Search", "Takeout/My Activity/Video Search/MyActivity.html"),
+)
+TAKEOUT_ACTIVITY_ACTIONS = {"Visited", "Searched for", "Viewed", "Watched"}
+TAKEOUT_DATE_RE = re.compile(
+ r"^(?P<date>[A-Z][a-z]{2} \d{1,2}, \d{4}, \d{1,2}:\d{2}:\d{2}\s+[AP]M) (?P<zone>HKT|UTC|GMT)$"
+)
def discover_history_sources(
@@ -226,6 +240,210 @@ def refresh_history(
return results
+def _normalize_takeout_url(value: str) -> str:
+ parsed = urlparse(value)
+ if parsed.hostname in {"google.com", "www.google.com"} and parsed.path == "/url":
+ query = parse_qs(parsed.query)
+ for key in ("q", "url"):
+ if query.get(key):
+ return query[key][0]
+ return value
+
+
+def _parse_takeout_date(value: str) -> datetime:
+ match = TAKEOUT_DATE_RE.fullmatch(value.replace("\u202f", " "))
+ if not match:
+ raise ValueError("Google My Activity 时间格式无法识别")
+ naive = datetime.strptime(match.group("date"), "%b %d, %Y, %I:%M:%S %p")
+ timezone = ZoneInfo("Asia/Hong_Kong") if match.group("zone") == "HKT" else UTC
+ return naive.replace(tzinfo=timezone).astimezone(UTC)
+
+
+class _TakeoutActivityParser(HTMLParser):
+ def __init__(self, *, visit_prefix: str) -> None:
+ super().__init__()
+ self.visit_prefix = visit_prefix
+ self.depth = 0
+ self.card_number = 0
+ self.pending_visit = False
+ self.in_target = False
+ self.href: str | None = None
+ self.title_parts: list[str] = []
+ self.date_text: str | None = None
+ self.visits: list[HistoryVisit] = []
+ self.errors = 0
+ self.matched_action = False
+ self.skipped = 0
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ values = dict(attrs)
+ if tag == "div" and self.depth == 0 and "outer-cell" in (values.get("class") or "").split():
+ self.depth = 1
+ self.pending_visit = False
+ self.in_target = False
+ self.href = None
+ self.title_parts = []
+ self.date_text = None
+ self.matched_action = False
+ return
+ if not self.depth:
+ return
+ if tag == "div":
+ self.depth += 1
+ elif tag == "a" and self.pending_visit and self.href is None:
+ self.in_target = True
+ self.href = values.get("href")
+
+ def handle_endtag(self, tag: str) -> None:
+ if self.depth and tag == "a" and self.in_target:
+ self.in_target = False
+ self.pending_visit = False
+ if not self.depth or tag != "div":
+ return
+ self.depth -= 1
+ if self.depth:
+ return
+ self.card_number += 1
+ if self.href is None or self.date_text is None:
+ if self.matched_action:
+ self.skipped += 1
+ return
+ try:
+ visited = _parse_takeout_date(self.date_text)
+ except ValueError:
+ self.errors += 1
+ return
+ url = _normalize_takeout_url(self.href)
+ if urlparse(url).scheme not in {"http", "https"}:
+ self.errors += 1
+ return
+ digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16]
+ self.visits.append(
+ HistoryVisit(
+ f"{self.visit_prefix}:{self.card_number}:{int(visited.timestamp())}:{digest}",
+ visited.isoformat(),
+ url,
+ " ".join(self.title_parts).strip(),
+ )
+ )
+
+ def handle_data(self, data: str) -> None:
+ if not self.depth:
+ return
+ value = data.strip()
+ if value in TAKEOUT_ACTIVITY_ACTIONS:
+ self.matched_action = True
+ self.pending_visit = True
+ elif self.in_target and value:
+ self.title_parts.append(value)
+ elif value.endswith((" HKT", " UTC", " GMT")) and len(value) >= 20:
+ self.date_text = value
+
+
+def _read_takeout_archive(path: Path) -> list[tuple[str, str, list[HistoryVisit], int]]:
+ with zipfile.ZipFile(path) as archive:
+ members = set(archive.namelist())
+ if TAKEOUT_HISTORY_MEMBER not in members and not any(
+ member in members for _browser, _profile, member in TAKEOUT_ACTIVITY_MEMBERS
+ ):
+ raise ValueError("Takeout 未包含可识别的浏览或搜索活动")
+ history_visits: list[HistoryVisit] = []
+ if TAKEOUT_HISTORY_MEMBER in members:
+ history_payload = json.loads(archive.read(TAKEOUT_HISTORY_MEMBER))
+ history_rows = history_payload.get("Browser History")
+ if not isinstance(history_rows, list):
+ raise ValueError("Takeout Chrome History 缺少 Browser History 列表")
+ for index, row in enumerate(history_rows, 1):
+ if not isinstance(row, dict) or not row.get("url") or row.get("time_usec") is None:
+ raise ValueError("Takeout Chrome History 含无效记录")
+ url = str(row["url"])
+ time_usec = int(row["time_usec"])
+ digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:16]
+ history_visits.append(
+ HistoryVisit(
+ f"history:{index}:{time_usec}:{digest}",
+ _iso_from_unix_microseconds(time_usec),
+ url,
+ str(row.get("title") or ""),
+ )
+ )
+ sources: list[tuple[str, str, list[HistoryVisit], int]] = []
+ if history_visits:
+ sources.append(("chrome", "Takeout Browser History", history_visits, 0))
+ for browser, profile, member in TAKEOUT_ACTIVITY_MEMBERS:
+ if member not in members:
+ continue
+ activity = _TakeoutActivityParser(visit_prefix=hashlib.sha256(member.encode()).hexdigest()[:10])
+ activity.feed(archive.read(member).decode("utf-8"))
+ activity.close()
+ if activity.errors:
+ raise ValueError(f"{profile} 含无法解析的活动记录:{activity.errors}")
+ sources.append((browser, profile, activity.visits, activity.skipped))
+ return sources
+
+
+def _event_fingerprint(url: str, visited_at: str) -> tuple[str, int]:
+ return url, int(datetime.fromisoformat(visited_at).timestamp())
+
+
+def refresh_takeout_history(
+ archives: list[Path],
+ 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)
+ existing = Counter(
+ _event_fingerprint(url, visited_at)
+ for visited_at, url in store.execute(
+ "SELECT v.visited_at, v.url FROM history_visit v "
+ "JOIN history_source s ON s.source_key = v.source_key"
+ )
+ )
+ for archive_path in archives:
+ for browser, profile, visits, skipped in _read_takeout_archive(archive_path):
+ source = HistorySource(browser, profile, archive_path)
+ source_key = _source_key(source, host)
+ path_hash = hashlib.sha256(str(archive_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),
+ )
+ source_seen: Counter[tuple[str, int]] = Counter()
+ additions: list[HistoryVisit] = []
+ for visit in visits:
+ fingerprint = _event_fingerprint(visit.url, visit.visited_at)
+ source_seen[fingerprint] += 1
+ if source_seen[fingerprint] > existing[fingerprint]:
+ additions.append(visit)
+ 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 additions),
+ )
+ added = store.total_changes - before
+ for fingerprint, count in source_seen.items():
+ existing[fingerprint] = max(existing[fingerprint], count)
+ results.append(
+ {
+ "browser": browser,
+ "profile": profile,
+ "visits": len(visits),
+ "added": added,
+ "skipped": skipped,
+ }
+ )
+ 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)
diff --git a/tests/test_taste_history.py b/tests/test_taste_history.py
index ddcff10bb..09b1b859f 100644
--- a/tests/test_taste_history.py
+++ b/tests/test_taste_history.py
@@ -1,11 +1,22 @@
import csv
+import json
import sqlite3
import tempfile
import unittest
+import zipfile
from contextlib import closing
+from datetime import UTC, datetime
from pathlib import Path
+from urllib.parse import quote
+from zoneinfo import ZoneInfo
-from peach.taste_history import HistorySource, analyze_history, discover_history_sources, refresh_history
+from peach.taste_history import (
+ HistorySource,
+ analyze_history,
+ discover_history_sources,
+ refresh_history,
+ refresh_takeout_history,
+)
class TasteHistoryTests(unittest.TestCase):
@@ -49,6 +60,41 @@ class TasteHistoryTests(unittest.TestCase):
db.execute("INSERT INTO history_visits VALUES (3, 1, 700000000, 'hidden')")
db.commit()
+ def _takeout_zip(self, path: Path) -> None:
+ overlap_url = "https://onlyfans.com/takeout_creator"
+ unique_url = "https://rule34.xxx/index.php?page=post&s=list&tags=feet"
+ history = {
+ "Browser History": [
+ {"url": overlap_url, "title": "private takeout title", "time_usec": 1700000000123456},
+ {"url": unique_url, "title": "another private title", "time_usec": 1700000100000000},
+ ]
+ }
+ activity_rows = [
+ (overlap_url, 1700000000, "private activity title"),
+ ("https://fansly.com/activity_only", 1700000200, "activity only title"),
+ ]
+ cards: list[str] = []
+ for url, timestamp, title in activity_rows:
+ local = datetime.fromtimestamp(timestamp, UTC).astimezone(ZoneInfo("Asia/Hong_Kong"))
+ hour = (local.hour - 1) % 12 + 1
+ date = f"{local:%b} {local.day}, {local.year}, {hour}:{local:%M:%S} {local:%p} HKT"
+ wrapped = f"https://www.google.com/url?q={quote(url, safe='')}"
+ cards.append(
+ '<div class="outer-cell"><div><div>Visited&nbsp;'
+ f'<a href="{wrapped}">{title}</a><br>{date}<br>Products:<br>Chrome'
+ "</div></div></div>"
+ )
+ with zipfile.ZipFile(path, "w") as archive:
+ archive.writestr("Takeout/Chrome/History.json", json.dumps(history))
+ archive.writestr("Takeout/My Activity/Chrome/MyActivity.html", "<html>" + "".join(cards) + "</html>")
+ archive.writestr(
+ "Takeout/My Activity/Search/MyActivity.html",
+ '<html><div class="outer-cell"><div><div>Searched for&nbsp;'
+ '<a href="https://www.google.com/search?q=test">private search</a><br>'
+ "Nov 15, 2023, 9:18:20 PM HKT<br>Products:<br>Search"
+ "</div></div></div></html>",
+ )
+
def test_discovers_windows_firefox_and_chrome_profiles(self):
roaming = self.root / "Roaming"
local = self.root / "Local"
@@ -90,6 +136,34 @@ class TasteHistoryTests(unittest.TestCase):
creators = {row["candidate"] for row in csv.DictReader(handle)}
self.assertEqual(creators, {"alice", "creator_name"})
+ def test_takeout_import_recovers_activity_and_deduplicates_sources(self):
+ archive = self.root / "takeout.zip"
+ self._takeout_zip(archive)
+ store = self.root / "sources" / "history.sqlite"
+
+ first = refresh_takeout_history([archive], store, host="test-host")
+ second = refresh_takeout_history([archive], store, host="test-host")
+
+ self.assertEqual(
+ [(item["profile"], item["visits"], item["added"]) for item in first],
+ [
+ ("Takeout Browser History", 2, 2),
+ ("Google My Activity - Chrome", 2, 1),
+ ("Google My Activity - Search", 1, 1),
+ ],
+ )
+ self.assertEqual(sum(item["added"] for item in second), 0)
+ with closing(sqlite3.connect(store)) as db:
+ rows = db.execute("SELECT url, title FROM history_visit ORDER BY visited_at").fetchall()
+ self.assertEqual(len(rows), 4)
+ self.assertTrue(all("google.com/url" not in url for url, _title in rows))
+ self.assertIn(("https://fansly.com/activity_only", "activity only title"), rows)
+
+ result = analyze_history(store, self.root / "review")
+ report = Path(result["report"]).read_text(encoding="utf-8")
+ self.assertNotIn("https://", report)
+ self.assertNotIn("private takeout title", report)
+
if __name__ == "__main__":
unittest.main()