Peach: Local-first video metadata scraper and media manager.
feat: import canonical performer identity metadata
Peach local maintenance59c1ef2ed31c
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 98e21b941..34793cb04 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -41,6 +41,7 @@ This is durable operating knowledge, not a per-session transcript.- Item/detail/filter/search/facets/index/stats/top lists/related ranking use canonical relations. Flattened creator/studio fields remain only as response compatibility projections; do not use them for identity or matching.- Performer/studio/creator/series names navigate to entity pages; only content tags are direct homepage filters. `entity_link.source_reference` is private provenance and must not become a clickable download link. “稍后看” writes `watch_queue`, never feedback.- Entity portraits resolve `generated/avatars/<kind>-<entity_id>.img` first and carry content-type/provenance sidecars. Do not accept Stash's default SVG silhouette or search-result thumbnails as portraits; representative asset crops are fallback only.+- `scripts/import_stash_entities.py` is the transitional performer identity importer. It uses `StashClient`, exact canonical-name matches, stable external refs, dry-run by default and a required backup on apply. Only localhost Stash image URLs are accepted; placeholders and images below a 512 px short side are rejected. Only aliases explicitly marked `X:`/`Twitter:` become social links; plain `@handle` remains a search term because its network is ambiguous.- Reviewed studio merging runs through `scripts/canonicalize_studios.py` (dry-run by default, backup required for apply). `PREMIUM` is a distinct studio; only Prestige Premium and Japanese Prestige spellings alias to `Prestige`.- Keep FastAPI and the front end logically separate but deploy as a monolith.- External sources and AI are supported only through explicit adapters and declared data boundaries.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 6289cbbac..066fbaeca 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -40,7 +40,8 @@ Runtime PIDs are observations, not configuration; always re-check them.- Immersive-mode actions now use optically centered 60 px controls with visible `不喜欢` / `看过` / `高潮` labels; the orgasm count is a corner badge and the watched state changes to `已看`.- Long-card hover now enlarges the card and exposes ±10-second preview seeking; short cards expose a profile-backed “稍后看” action. Item details show linked performers/studio/creator/series, and top performer/studio entries navigate to entity pages instead of mutating filters.- Migration `0003` added entity summaries, typed links/search terms and `watch_queue`. Thirteen reviewed studio duplicate groups were merged with 15 aliases; Prestige has 248 video assets after Japanese/Prestige Premium normalization, while distinct `PREMIUM` remains separate.-- FC2's 16×16 favicon was replaced by the official 102×43 asset and the user-provided Prestige logo was cached locally, both with provenance sidecars. Performer-image routing prefers a provenance-backed entity cache; the tested Stash performer endpoint returned its default SVG silhouette and was rejected as an HD source.+- FC2's 16×16 favicon was replaced by the official 102×43 asset and the user-provided Prestige logo was cached locally, both with provenance sidecars. Performer-image routing prefers a provenance-backed entity cache; Stash's default SVG silhouette is rejected rather than mislabeled as an HD portrait.+- `scripts/import_stash_entities.py` reconciled the Stash public performer contract into Peach without making Stash authoritative: 383 exact stable refs, 52 aliases/search terms and two explicitly declared X links were imported. Of 42 non-placeholder Stash images, 14 passed the 512 px short-side gate and were cached with provenance; 28 smaller images were rejected. Top entries including 一个ren、高桥千凛 and 小桃 now use 720 px-class cached portraits.- Static/unit/API production checks passed after restart: home/entity routes, FC2/Prestige logos, canonical aliases and a local-media 1 KiB `206 Partial Content` response. No browser instance was connected, so desktop and 390×844 visual verification remain pending.- CloudDrive `A:`/`B:` mounts are currently absent from the console session and asset 4289 returns unavailable. CloudDrive is doing roughly 5.7–6.2 MB/s I/O, so it was deliberately not restarted; local `R:` media playback is verified and cloud playback remains a runtime blocker until active CloudDrive work finishes.- The original Peach process could not see CloudDrive `A:`/`B:` even though CloudDrive was running. After confirming zero copy tasks and no I/O, CloudDrive and Peach were restarted in the same execution context. Asset 4289 (`669.mp4`) then passed `video/mp4`, 1 KiB `206 Range`, thumbnail and generated-poster API checks. Drive-letter visibility differs by Windows token, so the HTTP stream check is the authoritative service test.diff --git a/scripts/import_stash_entities.py b/scripts/import_stash_entities.pynew file mode 100644index 000000000..ae3c0d77d--- /dev/null+++ b/scripts/import_stash_entities.py@@ -0,0 +1,236 @@+"""Import Stash performer identity metadata into Peach's canonical model.++This is a transitional adapter, not a second truth source. It imports stable IDs,+aliases, descriptions and declared URLs; placeholder images are deliberately ignored.+Dry-run is the default and applying requires a SQLite backup.+"""+from __future__ import annotations++import argparse+import json+import re+import sqlite3+import struct+import urllib.request+from datetime import datetime, timezone+from pathlib import Path+from urllib.parse import urlsplit++from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.migrations import sqlite_backup+from peach.stash import StashClient+++QUERY = """query PeachPerformerIdentity {+ allPerformers { id name urls alias_list details birthdate country height_cm measurements image_path }+}"""+++def normalized(value: str) -> str:+ return " ".join(value.casefold().split())+++def link_kind(url: str) -> str:+ host = (urlsplit(url).hostname or "").casefold()+ if host.endswith(("x.com", "twitter.com", "instagram.com", "youtube.com", "tiktok.com")):+ return "social"+ return "catalog"+++def collect(connection: sqlite3.Connection, performers: list[dict]) -> list[dict]:+ entities = {normalized(name): (entity_id, name) for entity_id, name in connection.execute(+ "SELECT id,canonical_name FROM entity WHERE kind='performer'"+ )}+ result = []+ for performer in performers:+ match = entities.get(normalized(performer.get("name") or ""))+ if not match:+ continue+ aliases = sorted({a.strip() for a in performer.get("alias_list") or [] if a.strip()},+ key=str.casefold)+ urls = {u.strip() for u in performer.get("urls") or []+ if u.strip().startswith(("https://", "http://"))}+ for alias in aliases:+ social = re.fullmatch(r"(?:X|Twitter):\s*@?([A-Za-z0-9_]{1,15})", alias, re.I)+ if social:+ urls.add("https://x.com/" + social.group(1))+ urls = sorted(urls)+ result.append({+ "entity_id": match[0], "canonical_name": match[1], "stash_id": str(performer["id"]),+ "aliases": aliases, "urls": urls, "details": (performer.get("details") or "").strip(),+ "bio": {k: performer.get(k) for k in ("birthdate", "country", "height_cm", "measurements")+ if performer.get(k) not in (None, "")},+ "has_real_image": bool(performer.get("image_path") and+ "default=true" not in performer["image_path"]),+ "image_url": performer.get("image_path") or "",+ })+ return result+++def apply(connection: sqlite3.Connection, rows: list[dict]) -> dict:+ stamp = datetime.now(timezone.utc).isoformat()+ counts = {"external_refs": 0, "aliases": 0, "links": 0, "summaries": 0, "search_terms": 0}+ connection.execute("PRAGMA foreign_keys=ON")+ connection.execute("BEGIN IMMEDIATE")+ try:+ for row in rows:+ entity_id = row["entity_id"]+ existing = connection.execute(+ "SELECT external_id FROM entity_external_ref WHERE entity_id=? "+ "AND provider='stash' AND external_kind='performer'", (entity_id,),+ ).fetchone()+ if existing and existing[0] != row["stash_id"]:+ raise RuntimeError(f"Stash performer ID conflict for {row['canonical_name']}")+ connection.execute(+ "INSERT OR IGNORE INTO entity_external_ref(entity_id,provider,external_kind,external_id,"+ "metadata_json,last_synced_at) VALUES(?,'stash','performer',?,'{}',?)",+ (entity_id, row["stash_id"], stamp),+ )+ counts["external_refs"] += connection.execute("SELECT changes()").fetchone()[0]+ for alias in row["aliases"]:+ connection.execute(+ "INSERT OR IGNORE INTO entity_alias(entity_id,alias,normalized_alias,source,confidence) "+ "VALUES(?,?,?,'stash:performer',0.9)", (entity_id, alias, normalized(alias)),+ )+ counts["aliases"] += connection.execute("SELECT changes()").fetchone()[0]+ connection.execute(+ "INSERT OR IGNORE INTO entity_search_term(entity_id,term,purpose,source,created_at) "+ "VALUES(?,?,'discovery','stash:performer',?)", (entity_id, alias, stamp),+ )+ counts["search_terms"] += connection.execute("SELECT changes()").fetchone()[0]+ for url in row["urls"]:+ host = urlsplit(url).hostname or ""+ connection.execute(+ "INSERT OR IGNORE INTO entity_link(entity_id,link_kind,label,url,hostname,is_sensitive,"+ "metadata_json,created_at,updated_at) VALUES(?,?,?,?,?,0,'{}',?,?)",+ (entity_id, link_kind(url), host or "Stash URL", url, host, stamp, stamp),+ )+ counts["links"] += connection.execute("SELECT changes()").fetchone()[0]+ current = connection.execute(+ "SELECT metadata_json FROM entity WHERE id=?", (entity_id,),+ ).fetchone()[0]+ try:+ metadata = json.loads(current or "{}")+ except ValueError:+ metadata = {}+ changed = False+ if row["details"] and not metadata.get("summary"):+ metadata["summary"] = row["details"]+ changed = True+ for key, value in row["bio"].items():+ if key not in metadata:+ metadata[key] = value+ changed = True+ if changed:+ connection.execute(+ "UPDATE entity SET metadata_json=?,updated_at=? WHERE id=?",+ (json.dumps(metadata, ensure_ascii=False, separators=(",", ":")), stamp, entity_id),+ )+ counts["summaries"] += 1+ connection.commit()+ except Exception:+ connection.rollback()+ raise+ return counts+++def image_size(data: bytes) -> tuple[int, int] | None:+ if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:+ return struct.unpack(">II", data[16:24])+ if data.startswith(b"\xff\xd8"):+ offset = 2+ while offset + 9 < len(data):+ if data[offset] != 0xFF:+ offset += 1+ continue+ marker = data[offset + 1]+ offset += 2+ if marker in {0xD8, 0xD9}:+ continue+ if offset + 2 > len(data):+ break+ length = int.from_bytes(data[offset:offset + 2], "big")+ if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7,+ 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} and offset + 7 <= len(data):+ return (int.from_bytes(data[offset + 5:offset + 7], "big"),+ int.from_bytes(data[offset + 3:offset + 5], "big"))+ offset += max(length, 2)+ return None+++def cache_images(rows: list[dict], destination: Path, minimum_short_side: int = 512) -> dict:+ destination.mkdir(parents=True, exist_ok=True)+ result = {"cached": 0, "too_small": 0, "placeholder_or_invalid": 0, "failed": 0}+ for row in rows:+ if not row["has_real_image"]:+ continue+ url = row["image_url"]+ parsed = urlsplit(url)+ if parsed.hostname not in {"127.0.0.1", "localhost", "::1"}:+ result["failed"] += 1+ continue+ try:+ with urllib.request.urlopen(url, timeout=20) as response:+ content_type = response.headers.get_content_type()+ data = response.read(10 * 1024 * 1024 + 1)+ size = image_size(data)+ if content_type not in {"image/jpeg", "image/png"} or not size or len(data) > 10 * 1024 * 1024:+ result["placeholder_or_invalid"] += 1+ continue+ if min(size) < minimum_short_side:+ result["too_small"] += 1+ continue+ target = destination / f"performer-{row['entity_id']}.img"+ temporary = target.with_suffix(".tmp")+ temporary.write_bytes(data)+ temporary.replace(target)+ Path(str(target) + ".ct").write_text(content_type + "\n", encoding="utf-8", newline="\n")+ Path(str(target) + ".provenance.json").write_text(json.dumps({+ "source": "Stash public performer adapter",+ "stash_performer_id": row["stash_id"],+ "cached_at": datetime.now(timezone.utc).isoformat(),+ "width": size[0], "height": size[1],+ "upstream_url": "local-stash-performer-endpoint",+ }, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n")+ result["cached"] += 1+ except (OSError, ValueError):+ result["failed"] += 1+ return result+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ parser.add_argument("--graphql", default="http://127.0.0.1:9999/graphql")+ parser.add_argument("--apply", action="store_true")+ parser.add_argument("--backup", type=Path)+ parser.add_argument("--cache-images", action="store_true")+ args = parser.parse_args()+ performers = StashClient(args.graphql, timeout=60).graphql(QUERY).get("allPerformers") or []+ connection = sqlite3.connect(args.db)+ try:+ rows = collect(connection, performers)+ summary = {"stash_performers": len(performers), "exact_matches": len(rows),+ "with_aliases": sum(bool(r["aliases"]) for r in rows),+ "with_urls": sum(bool(r["urls"]) for r in rows),+ "with_details": sum(bool(r["details"] or r["bio"]) for r in rows),+ "with_real_image": sum(r["has_real_image"] for r in rows)}+ print({"mode": "apply" if args.apply else "dry-run", **summary})+ if not args.apply:+ return+ if not args.backup:+ raise SystemExit("--apply requires --backup")+ connection.close()+ sqlite_backup(args.db, args.backup)+ connection = sqlite3.connect(args.db)+ applied = apply(connection, rows)+ images = cache_images(rows, GENERATED_DIR / "avatars") if args.cache_images else None+ print({"applied": applied, "images": images, "backup": str(args.backup),+ "integrity": connection.execute("PRAGMA integrity_check").fetchone()[0],+ "foreign_key_errors": len(connection.execute("PRAGMA foreign_key_check").fetchall())})+ finally:+ connection.close()+++if __name__ == "__main__":+ main()diff --git a/tests/test_stash_entity_import.py b/tests/test_stash_entity_import.pynew file mode 100644index 000000000..29453713e--- /dev/null+++ b/tests/test_stash_entity_import.py@@ -0,0 +1,72 @@+import importlib.util+import sqlite3+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[1]+SPEC = importlib.util.spec_from_file_location(+ "import_stash_entities", ROOT / "scripts" / "import_stash_entities.py",+)+MODULE = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(MODULE)+++class StashEntityImportTests(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.db = Path(self.tmp.name) / "ledger.db"+ self.connection = sqlite3.connect(self.db)+ self.connection.executescript("""+ CREATE TABLE entity(id INTEGER PRIMARY KEY,kind TEXT,canonical_name TEXT,+ metadata_json TEXT DEFAULT '{}',updated_at TEXT);+ CREATE TABLE entity_alias(entity_id INTEGER,alias TEXT,normalized_alias TEXT,+ source TEXT,confidence REAL,PRIMARY KEY(entity_id,normalized_alias,source));+ CREATE TABLE entity_external_ref(entity_id INTEGER,provider TEXT,external_kind TEXT,+ external_id TEXT,metadata_json TEXT,last_synced_at TEXT,+ PRIMARY KEY(provider,external_kind,external_id),UNIQUE(entity_id,provider,external_kind));+ CREATE TABLE entity_search_term(entity_id INTEGER,term TEXT,purpose TEXT,source TEXT,+ created_at TEXT,PRIMARY KEY(entity_id,term,purpose));+ CREATE TABLE entity_link(id INTEGER PRIMARY KEY,entity_id INTEGER,link_kind TEXT,label TEXT,+ url TEXT,hostname TEXT,is_sensitive INTEGER,metadata_json TEXT,created_at TEXT,updated_at TEXT,+ UNIQUE(entity_id,url));+ INSERT INTO entity(id,kind,canonical_name,metadata_json) VALUES(1,'performer','Alice','{}');+ """)++ def tearDown(self):+ self.connection.close()+ self.tmp.cleanup()++ def test_imports_identity_data_and_rejects_default_portrait(self):+ rows = MODULE.collect(self.connection, [{+ "id": "42", "name": "Alice", "alias_list": ["@alice", "Alice A", "X:@alice"],+ "urls": [], "details": "Performer summary",+ "birthdate": "2000-01-01", "country": "JP", "height_cm": 165,+ "measurements": "B80 W55 H82",+ "image_path": "http://127.0.0.1/performer/42/image?default=true",+ }])+ self.assertEqual(len(rows), 1)+ self.assertFalse(rows[0]["has_real_image"])+ counts = MODULE.apply(self.connection, rows)+ self.assertEqual(counts["external_refs"], 1)+ self.assertEqual(counts["aliases"], 3)+ self.assertEqual(counts["links"], 1)+ self.assertEqual(self.connection.execute(+ "SELECT link_kind FROM entity_link"+ ).fetchone()[0], "social")+ metadata = self.connection.execute(+ "SELECT metadata_json FROM entity WHERE id=1"+ ).fetchone()[0]+ self.assertIn("Performer summary", metadata)++ def test_reads_png_and_jpeg_dimensions(self):+ png = b"\x89PNG\r\n\x1a\n" + b"\x00" * 8 + (600).to_bytes(4, "big") + (800).to_bytes(4, "big")+ jpeg = (b"\xff\xd8\xff\xc0\x00\x11\x08" + (700).to_bytes(2, "big")+ + (500).to_bytes(2, "big") + b"\x03" + b"\x00" * 20)+ self.assertEqual(MODULE.image_size(png), (600, 800))+ self.assertEqual(MODULE.image_size(jpeg), (500, 700))+++if __name__ == "__main__":+ unittest.main()