Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: add review gate for parallel tagging

Peach local maintenance8b4f49a74f11
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index 01cbf4018..9867e1b44 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -12,6 +12,15 @@ This is durable operating knowledge, not a per-session transcript.
- The user is not the message bus. Do not ask the user to copy technical conclusions to another agent; update the shared documents in the same change.
- If the worktree is dirty, inspect and preserve every existing diff. One agent owns a file while actively changing it; work on non-overlapping files or wait for that write to finish, then integrate the diff instead of recreating it.
+## Parallel agent execution
+
+- Codex is the coordinator for architecture, code ownership, review, migrations, real-ledger writes, service restarts and final verification. Claude is a parallel worker for bounded mechanical batches such as board reading, metadata candidate scraping and CSV reconciliation; handoff is not the goal.
+- Parallel workers receive explicit input/output paths, network and cost policy, write boundary and acceptance criteria. They write `candidate` review artifacts only; they do not mark their own output `approved`, run `--apply`, alter migrations/ADR, or restart services.
+- Use separate Git worktrees for concurrent code changes. Data-only batches may share the main checkout only when their sole writable artifact is outside Git and named in the task. Never let two agents edit the same file.
+- Worker results return to the coordinating agent for vocabulary/provenance checks, deduplication, isolated tests and approval. The user does not relay reports between agents.
+- `scripts/scrape_codes.py` and `scripts/creator_tags.py` are the standard review boundaries. Creator-board work exports `generated/creator-tags-review.csv`; workers may change `pending` to `candidate` or `skip`, while `approved` and the required backup remain coordinator actions.
+- Claude Code 2.1.232 refused explicit sexual-act classification from board images. Do not assign that visual-content category to Claude again unless its supported-use boundary is reverified; use human review or a separately approved vision provider. Claude remains suitable for code, public metadata adapters, deduplication and non-visual CSV validation.
+
## Reuse before restore
- Read `docs/REUSE.md` before introducing a library, protocol implementation or restored legacy script.
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 47bc4f490..9d91c4d42 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -31,7 +31,7 @@ Runtime PIDs are observations, not configuration; always re-check them.
- Creator/studio top lists and related-item creator/tag/studio matching now read canonical entity relations. Real-ledger timings were 0.055 s for 28 top entries and 0.055 s for 24 related items.
- Creator/studio filters, canonical-name search, creator index, facets and attribution stats now also read entity relations. Real-ledger timings were 0.040 s for a 1,545-item creator filter, 0.043 s for the first 60 creators, 0.132 s for facets and 0.394 s for stats.
- Snapshot availability checks use the same strict legacy-prefix resolver as `/thumb`, so the front end requests migrated previews instead of displaying false “无预览” cards.
-- 60 isolated tests, Python static compilation, dependency validation and JavaScript parse validation passed under Python 3.14/Node.
+- 61 isolated tests, Python static compilation, dependency validation and JavaScript parse validation passed under Python 3.14/Node.
- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check` before later metadata writes.
- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.
- Restarted production port 80 passed health, home, public OpenCode Go model discovery (26 models at verification time), canonical filtered-list/item reads, thumbnail `200` and 1 KiB `206 Partial Content` Range smoke checks.
@@ -50,7 +50,9 @@ Runtime PIDs are observations, not configuration; always re-check them.
## Batch jobs
- The creator-board sampler completed before its implementation was changed; it left 86 boards and 598 cached frames. No `creator_boards.py` process was active at the final observation. The command now uses the shared source-access policy, disk guard, PID lock and Peach-managed FFmpeg resolver while preserving its prior arguments and output layout.
-- `RM-TrafficWatch` is running from the project venv with the refactored watcher. It stops only matching Peach task trees and no longer terminates machine-wide FFmpeg/ffprobe processes.
+- Creator tagging is now review-first: `scripts/creator_tags.py --export-review` produced `R:\peach-data\generated\creator-tags-review.csv` with 86 boards, 30 prior decisions and 56 pending rows. A parallel worker may write only `candidate`/`skip`; applying accepts only coordinator-reviewed `approved` rows, requires a SQLite backup, and dual-writes compatibility plus canonical tag relations.
+- A Claude Code 2.1.232 batch was asked to inspect those 56 boards but refused explicit sexual-act visual classification after 24 seconds; it made no CSV changes. The queue remains 27 applied, 3 skipped and 56 pending. Claude should be used for non-visual scraping/code/data reconciliation, not this visual category.
+- The visible terminal mistaken for a slow batch was the permanent `RM-TrafficWatch` heartbeat. Its scheduled action was changed from `python.exe` to `pythonw.exe` at 22:36, the task restarted successfully, and the new hidden process continued writing `trafficwatch-20260814-223642.log` every 30 seconds. It stops only matching Peach task trees and no longer terminates machine-wide FFmpeg/ffprobe processes.
- `scripts/scrape_codes.py` — code scraping via r18 → avsox → javbus cascade, resumable from
`R:\peach-data\generated\code-scrape.csv`. All 1,104 non-FC2 codes were processed; 715 rows carry
diff --git a/scripts/creator_tags.py b/scripts/creator_tags.py
index 8e24179dc..bcc28f89a 100644
--- a/scripts/creator_tags.py
+++ b/scripts/creator_tags.py
@@ -12,17 +12,28 @@ r"""
标签一律取自 ledger 现有词表,不新造词。
用法:
- python scripts/creator_tags.py [--apply]
+ python scripts/creator_tags.py --export-review
+ # Claude/人工先写 candidate;审核后才把行改为 approved。
+ python scripts/creator_tags.py --apply-review --backup <backup.db>
"""
from __future__ import annotations
-import os
+import argparse
+import csv
+import re
import sqlite3
-import sys
+from pathlib import Path
-DB = r"R:\peach-data\database\ledger.db"
+from peach.config import DATABASE_PATH, GENERATED_DIR
+from peach.entities import upsert_asset_entity
+from peach.migrations import sqlite_backup
+
+DB = DATABASE_PATH
+BOARD_DIR = GENERATED_DIR / "boards"
+REVIEW_CSV = GENERATED_DIR / "creator-tags-review.csv"
SOURCE = "vision_creator"
CONFIDENCE = 0.6
+REVIEW_FIELDS = ["board", "creator", "video_count", "status", "tags", "reason"]
# 创作者 -> 标签。读风格板得出,只记反复出现的稳定特征。
BOARDS: dict[str, list[str]] = {
@@ -63,42 +74,139 @@ SKIPPED = {
"tuki_1154": "可用样张仅 5 张且过暗过糊,无法确证任何标签",
}
-APPLY = "--apply" in sys.argv[1:]
+def _readonly(path: Path) -> sqlite3.Connection:
+ return sqlite3.connect("file:" + path.resolve().as_posix() + "?mode=ro", uri=True)
-def main() -> int:
- conn = sqlite3.connect(DB, timeout=60)
- conn.execute("PRAGMA busy_timeout=60000")
+def _safe_name(value: str) -> str:
+ return re.sub(r"[^\w\u4e00-\u9fff-]", "_", value)[:40]
- known = {r[0] for r in conn.execute(
- "SELECT DISTINCT tag FROM asset_tag WHERE source IN ('name','r18','vision')")}
- unknown = {t for tags in BOARDS.values() for t in tags} - known
- if unknown:
- print("以下标签不在现有词表,先确认再写:", sorted(unknown))
- return 1
- total_assets = total_rows = 0
- for creator, tags in BOARDS.items():
- ids = [r[0] for r in conn.execute(
- "SELECT id FROM asset WHERE medium='video' AND creator=? "
- "AND id NOT IN (SELECT asset_id FROM asset_tag)", (creator,))]
- if not ids:
- print(f" {creator[:24]:<24} 无待打标视频,跳过")
+def _board_identity(path: Path) -> tuple[str, int] | None:
+ match = re.match(r"^(?:v)?\d+_(.+)_(\d+)$", path.stem)
+ return (match.group(1), int(match.group(2))) if match else None
+
+
+def export_review(db_path: Path, board_dir: Path, output: Path) -> tuple[int, int]:
+ connection = _readonly(db_path)
+ creators = [row[0] for row in connection.execute(
+ "SELECT DISTINCT creator FROM asset WHERE medium='video' "
+ "AND creator IS NOT NULL AND creator<>''"
+ )]
+ connection.close()
+ by_safe_name: dict[str, str] = {}
+ for creator in creators:
+ key = _safe_name(creator)
+ if key in by_safe_name and by_safe_name[key] != creator:
+ raise RuntimeError(f"board filename collision: {creator} / {by_safe_name[key]}")
+ by_safe_name[key] = creator
+
+ previous: dict[str, dict] = {}
+ if output.is_file():
+ with output.open(encoding="utf-8-sig", newline="") as handle:
+ previous = {row["board"]: row for row in csv.DictReader(handle)}
+
+ rows: list[dict] = []
+ pending = 0
+ for board in sorted(board_dir.glob("*.jpg")):
+ identity = _board_identity(board)
+ if identity is None:
continue
- print(f" {creator[:24]:<24} {len(ids):>4} 条 x {len(tags)} 标签 {' '.join(tags)}")
- total_assets += len(ids)
- total_rows += len(ids) * len(tags)
- if APPLY:
- conn.executemany(
+ safe_creator, count = identity
+ creator = by_safe_name.get(safe_creator)
+ if not creator:
+ raise RuntimeError(f"creator not found for board: {board.name}")
+ old = previous.get(board.name)
+ if old:
+ row = {field: old.get(field, "") for field in REVIEW_FIELDS}
+ row.update({"board": board.name, "creator": creator, "video_count": count})
+ elif creator in BOARDS:
+ row = {"board": board.name, "creator": creator, "video_count": count,
+ "status": "applied", "tags": "|".join(BOARDS[creator]), "reason": ""}
+ elif creator in SKIPPED:
+ row = {"board": board.name, "creator": creator, "video_count": count,
+ "status": "skip", "tags": "", "reason": SKIPPED[creator]}
+ else:
+ row = {"board": board.name, "creator": creator, "video_count": count,
+ "status": "pending", "tags": "", "reason": ""}
+ pending += row["status"] == "pending"
+ rows.append(row)
+
+ output.parent.mkdir(parents=True, exist_ok=True)
+ temporary = output.with_suffix(output.suffix + ".tmp")
+ with temporary.open("w", encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=REVIEW_FIELDS)
+ writer.writeheader()
+ writer.writerows(rows)
+ temporary.replace(output)
+ return len(rows), pending
+
+
+def apply_review(db_path: Path, review_path: Path, backup: Path) -> tuple[int, int]:
+ with review_path.open(encoding="utf-8-sig", newline="") as handle:
+ approved = [row for row in csv.DictReader(handle) if row.get("status") == "approved"]
+ sqlite_backup(db_path, backup)
+ connection = sqlite3.connect(db_path, timeout=60)
+ connection.execute("PRAGMA busy_timeout=60000")
+ known = {row[0] for row in connection.execute(
+ "SELECT DISTINCT tag FROM asset_tag WHERE source IN ('name','r18','vision')"
+ )}
+ total_assets = total_rows = 0
+ connection.execute("BEGIN IMMEDIATE")
+ try:
+ for row in approved:
+ tags = list(dict.fromkeys(tag.strip() for tag in row["tags"].split("|") if tag.strip()))
+ unknown = set(tags) - known
+ if unknown:
+ raise ValueError(f"{row['creator']} has unknown tags: {sorted(unknown)}")
+ ids = [result[0] for result in connection.execute(
+ "SELECT id FROM asset WHERE medium='video' AND creator=? "
+ "AND id NOT IN (SELECT asset_id FROM asset_tag)", (row["creator"],)
+ )]
+ connection.executemany(
"INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) VALUES(?,?,?,?)",
- [(aid, tag, CONFIDENCE, SOURCE) for aid in ids for tag in tags])
-
- if APPLY:
- conn.commit()
- print(f"\n已写入:{total_assets} 条视频,约 {total_rows} 条标签")
- else:
- print(f"\n预演:将覆盖 {total_assets} 条视频,约 {total_rows} 条标签。加 --apply 落库。")
- conn.close()
+ [(asset_id, tag, CONFIDENCE, SOURCE) for asset_id in ids for tag in tags],
+ )
+ for asset_id in ids:
+ for tag in tags:
+ upsert_asset_entity(
+ connection, kind="tag", name=tag, asset_id=asset_id, role="tag",
+ source=SOURCE, confidence=CONFIDENCE,
+ metadata={"evidence_board": row["board"]},
+ )
+ total_assets += len(ids)
+ total_rows += len(ids) * len(tags)
+ connection.commit()
+ except Exception:
+ connection.rollback()
+ raise
+ finally:
+ connection.close()
+ return total_assets, total_rows
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="review-first creator board tagging")
+ parser.add_argument("--db", type=Path, default=DB)
+ parser.add_argument("--board-dir", type=Path, default=BOARD_DIR)
+ parser.add_argument("--review", type=Path, default=REVIEW_CSV)
+ action = parser.add_mutually_exclusive_group(required=True)
+ action.add_argument("--export-review", action="store_true")
+ action.add_argument("--apply-review", action="store_true")
+ parser.add_argument("--backup", type=Path)
+ return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ if args.export_review:
+ total, pending = export_review(args.db, args.board_dir, args.review)
+ print(f"review queue: {total} boards, {pending} pending -> {args.review}")
+ return 0
+ if not args.backup:
+ raise SystemExit("--apply-review requires --backup")
+ assets, rows = apply_review(args.db, args.review, args.backup)
+ print(f"applied: {assets} assets, {rows} tag rows; backup={args.backup}")
return 0
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index a9ca9d263..96382ddf1 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -32,6 +32,7 @@ class OperationalScriptTests(unittest.TestCase):
cls.sheets = load_script("sheets")
cls.traffic_watch = load_script("traffic_watch")
cls.creator_boards = load_script("creator_boards")
+ cls.creator_tags = load_script("creator_tags")
def test_import_has_no_filesystem_or_log_side_effect(self):
self.assertIsNone(self.clean_names._logf)
@@ -173,6 +174,56 @@ class OperationalScriptTests(unittest.TestCase):
("tag", "肛交", "tag", "r18"),
} <= relations)
+ def test_creator_tag_review_queue_requires_approval_and_backup(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ db = root / "ledger.db"
+ sqlite3.connect(db).close()
+ upgrade(db, MIGRATIONS)
+ connection = sqlite3.connect(db)
+ connection.execute(
+ "INSERT INTO asset(id,location,path,name,medium,creator) "
+ "VALUES(1,'local','one.mp4','one.mp4','video','Alice')"
+ )
+ connection.execute(
+ "INSERT INTO asset(id,location,path,name,medium,creator) "
+ "VALUES(2,'local','vocab.mp4','vocab.mp4','video','Vocabulary')"
+ )
+ connection.execute(
+ "INSERT INTO asset_tag(asset_id,tag,confidence,source) "
+ "VALUES(2,'素人',0.9,'vision')"
+ )
+ connection.commit()
+ connection.close()
+ boards = root / "boards"
+ boards.mkdir()
+ (boards / "01_Alice_1.jpg").write_bytes(b"review-only fixture")
+ review = root / "review.csv"
+
+ total, pending = self.creator_tags.export_review(db, boards, review)
+ self.assertEqual((total, pending), (1, 1))
+ with review.open(encoding="utf-8-sig", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ rows[0].update({"status": "approved", "tags": "素人", "reason": "reviewed"})
+ with review.open("w", encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=self.creator_tags.REVIEW_FIELDS)
+ writer.writeheader()
+ writer.writerows(rows)
+
+ backup = root / "backup.db"
+ assets, tag_rows = self.creator_tags.apply_review(db, review, backup)
+ self.assertEqual((assets, tag_rows), (1, 1))
+ self.assertTrue(backup.is_file())
+ connection = sqlite3.connect(db)
+ self.assertEqual(connection.execute(
+ "SELECT source,confidence FROM asset_tag WHERE asset_id=1 AND tag='素人'"
+ ).fetchone(), ("vision_creator", 0.6))
+ self.assertEqual(connection.execute(
+ "SELECT ae.source FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
+ "WHERE ae.asset_id=1 AND e.kind='tag' AND e.canonical_name='素人'"
+ ).fetchone()[0], "vision_creator")
+ connection.close()
+
if __name__ == "__main__":
unittest.main()