Peach: Local-first video metadata scraper and media manager.
chore(scripts): 只读连接与写入参数收口到 peach.scripting
longmeidaof758f0e55024
diff --git a/scripts/audit_creator_attributions.py b/scripts/audit_creator_attributions.pyindex 93545cd6f..864e44f84 100644--- a/scripts/audit_creator_attributions.py+++ b/scripts/audit_creator_attributions.py@@ -6,7 +6,6 @@from __future__ import annotationsimport argparse-import sqlite3import sysfrom collections import Counterfrom pathlib import Path@@ -17,6 +16,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.review_csv import write_rows+from peach.scripting import open_readonlyfrom peach.config import DATABASE_PATH@@ -55,8 +55,7 @@ def classify(path: str, creator: str) -> tuple[str, str, str, str, str, str]:def rows(database: Path) -> list[dict[str, object]]:- connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)- connection.row_factory = sqlite3.Row+ connection = open_readonly(database)result: list[dict[str, object]] = []query = """SELECT a.id AS asset_id,a.medium,a.location,a.path,e.canonical_name AS creator,diff --git a/scripts/audit_fc2_similarity.py b/scripts/audit_fc2_similarity.pyindex 52617e1e3..7cb68c270 100644--- a/scripts/audit_fc2_similarity.py+++ b/scripts/audit_fc2_similarity.py@@ -11,7 +11,6 @@ from __future__ import annotationsimport argparseimport sqlite3import time-import urllib.parseimport sysfrom datetime import datetimefrom pathlib import Path@@ -22,6 +21,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.scripting import open_readonlyfrom peach.fc2_similarity import POLICY_VERSION, build_candidates, fc2_video_idfrom peach.review_csv import read_rows, write_rows@@ -90,9 +90,7 @@ def collection_ids(rows: list[dict]) -> set[str]:def load_assets(database: Path) -> list[dict]:- uri = "file:" + urllib.parse.quote(database.resolve().as_posix()) + "?mode=ro"- connection = sqlite3.connect(uri, uri=True)- connection.row_factory = sqlite3.Row+ connection = open_readonly(database)try:return [dict(row) for row in connection.execute("SELECT id,code,name,size,duration,width,height,hash FROM asset "diff --git a/scripts/audit_jav_display.py b/scripts/audit_jav_display.pyindex e5f21bff8..bd381e694 100644--- a/scripts/audit_jav_display.py+++ b/scripts/audit_jav_display.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport argparseimport re-import sqlite3import sysfrom pathlib import Path@@ -19,6 +18,7 @@ from peach.catalog_rules import (jav_display_metadata,)from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.scripting import open_readonlyfrom peach.review_csv import write_rows@@ -34,8 +34,7 @@ DOMAIN = re.compile(def audit(database: Path) -> list[dict[str, object]]:- connection = sqlite3.connect(f"file:{database}?mode=ro", uri=True)- connection.row_factory = sqlite3.Row+ connection = open_readonly(database)try:rows = connection.execute("SELECT a.id,a.name,a.code,a.studio,a.release_date,"diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.pyindex 648b37d7f..898dd3dcb 100644--- a/scripts/audit_performer_portraits.py+++ b/scripts/audit_performer_portraits.py@@ -61,7 +61,7 @@ from peach.catalog_rules import is_jav_codefrom peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.review_csv import read_rows, write_rows-from peach.scripting import USER_AGENT, HostLimiter+from peach.scripting import HostLimiter, USER_AGENT, open_readonlyGFRIENDS_RAW = "https://raw.githubusercontent.com/gfriends/gfriends/master/"# 目录名首字符即质量档位;0 最优,z(DMM 官方小图)最次。@@ -307,12 +307,6 @@ def normalized(value: str) -> str:# ---------------------------------------------------------------- ledger(只读)-def open_readonly(db_path: Path) -> sqlite3.Connection:- # mode=ro 让「绝不写库」成为数据库层的硬保证,而不只是约定。- uri = "file:" + urllib.parse.quote(db_path.resolve().as_posix()) + "?mode=ro"- return sqlite3.connect(uri, uri=True)--def load_performers(connection: sqlite3.Connection) -> list[dict]:"""全部 performer 及其名字链:canonical、alias(含已核实旧名)、本地化 jp。"""records: dict[int, dict] = {}diff --git a/scripts/audit_related_ranker.py b/scripts/audit_related_ranker.pyindex a706bf764..78577d855 100644--- a/scripts/audit_related_ranker.py+++ b/scripts/audit_related_ranker.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport argparseimport json-import sqlite3import timeimport sysfrom pathlib import Path@@ -15,11 +14,12 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH+from peach.scripting import open_readonlyfrom peach.web_contract import WebContract, q_relateddef seed_ids(database: Path, count: int) -> list[int]:- connection = sqlite3.connect(f"file:{database}?mode=ro", uri=True)+ connection = open_readonly(database)try:return [row[0] for row in connection.execute("SELECT a.id FROM asset a JOIN asset_entity ae ON ae.asset_id=a.id "diff --git a/scripts/audit_video_endcards.py b/scripts/audit_video_endcards.pyindex 198dda4b9..fdc61b0b2 100644--- a/scripts/audit_video_endcards.py+++ b/scripts/audit_video_endcards.py@@ -13,7 +13,6 @@ import osimport sqlite3import subprocessimport time-import urllib.parseimport sysfrom datetime import datetimefrom typing import Callable@@ -25,6 +24,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH, FFMPEG_DIR, GENERATED_DIR, STATE_DIR+from peach.scripting import open_readonlyfrom peach.endcard import POLICY_VERSION, detect_endcardfrom peach.ffmpeg import FFmpegResolverfrom peach.jobs import (@@ -109,13 +109,6 @@ def sample_points(return points-def open_readonly(database: Path) -> sqlite3.Connection:- uri = "file:" + urllib.parse.quote(database.resolve().as_posix()) + "?mode=ro"- connection = sqlite3.connect(uri, uri=True)- connection.row_factory = sqlite3.Row- return connection--def load_assets(args: argparse.Namespace) -> list[dict]:if not args.asset and args.limit <= 0:raise ValueError("必须点名 --asset,或给正数 --limit 才会启动")diff --git a/scripts/backfill_rule34_tag_types.py b/scripts/backfill_rule34_tag_types.pyindex 26e3216fc..80ec88015 100644--- a/scripts/backfill_rule34_tag_types.py+++ b/scripts/backfill_rule34_tag_types.py@@ -32,9 +32,11 @@ SRC_DIR = PROJECT_ROOT / "src"if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))-from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.config import GENERATED_DIRfrom peach.follow_sources import FollowSourceError, build_connector+from peach.migrations import sqlite_backupfrom peach.review_csv import write_rows+from peach.scripting import BACKUP_REQUIRED, add_ledger_write_args, open_readonlyFIELDS = ("item_id", "external_id", "url", "result", "tag_types", "note")@@ -51,13 +53,11 @@ COOLDOWN_SECONDS = 60.0def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description="补齐 rule34.xxx 追更条目的标签类型")- parser.add_argument("--db", type=Path, default=DATABASE_PATH)+ add_ledger_write_args(parser)parser.add_argument("--out", type=Path,default=GENERATED_DIR / "rule34-tag-type-backfill.csv")parser.add_argument("--limit", type=int, default=0, help="只处理前 N 条,0 为全部")parser.add_argument("--delay", type=float, default=DEFAULT_DELAY)- parser.add_argument("--apply", action="store_true", help="真正写入账本")- parser.add_argument("--backup", type=Path, help="写入前的账本备份路径;--apply 必须给")return parser@@ -87,19 +87,6 @@ def pending_rows(connection: sqlite3.Connection, limit: int) -> list[dict]:return rows-def backup_database(source: Path, target: Path) -> None:- """用 SQLite 自己的备份 API,不要 `shutil.copy2`。-- 账本是 WAL 模式:已提交但尚未 checkpoint 的事务在 `-wal` 里,只复制主库文件- 会得到一份**少了最近改动**的账本,而它看起来完全正常——恢复时才发现回退了- 一截。备份 API 会把 WAL 一并合进目标库。- """- target.parent.mkdir(parents=True, exist_ok=True)- with (sqlite3.connect(source.as_uri() + "?mode=ro", uri=True) as reader,- sqlite3.connect(target) as writer):- reader.backup(writer)--def merge_tag_types(metadata: dict, tag_types: dict[str, str]) -> str:merged = dict(metadata)merged["tag_types"] = dict(tag_types)@@ -108,11 +95,10 @@ def merge_tag_types(metadata: dict, tag_types: dict[str, str]) -> str:def run(args: argparse.Namespace) -> int:if args.apply and not args.backup:- print("--apply 必须同时给 --backup", file=sys.stderr)+ print(BACKUP_REQUIRED, file=sys.stderr)return 2database = args.db.resolve()- with sqlite3.connect(database.as_uri() + "?mode=ro", uri=True) as reader:- reader.row_factory = sqlite3.Row+ with open_readonly(database) as reader:rows = pending_rows(reader, args.limit)total = reader.execute("SELECT COUNT(*) FROM follow_item i JOIN follow_source s ON s.id=i.source_id"@@ -126,7 +112,7 @@ def run(args: argparse.Namespace) -> int:if args.apply:# 备份先做,批量写入才敢分批落。整轮跑完再一次性写,中断一次就等于白跑# 五十分钟——而这一趟本来就是可反复运行的。- backup_database(database, args.backup)+ sqlite_backup(database, args.backup)print(f"备份:{args.backup}", flush=True)writer = sqlite3.connect(database)before = writer.execute("SELECT COUNT(*) FROM follow_item").fetchone()[0]diff --git a/scripts/creator_boards.py b/scripts/creator_boards.pyindex 1b4bd7cff..2190f8464 100644--- a/scripts/creator_boards.py+++ b/scripts/creator_boards.py@@ -8,7 +8,6 @@ import concurrent.futures as futuresimport hashlibimport randomimport re-import sqlite3import subprocessimport threadingimport time@@ -21,6 +20,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH, FFMPEG_DIR, GENERATED_DIR, STATE_DIR+from peach.scripting import open_readonlyfrom peach.classification import is_probable_mainstream_release, is_structural_creatorfrom peach.ffmpeg import FFmpegResolverfrom peach.jobs import (@@ -146,10 +146,6 @@ def build_board(ffmpeg: str, ffprobe: str, paths: list[Path], destination: Path)return destination.is_file()-def _readonly(db_path: Path) -> sqlite3.Connection:- return sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)--def _existing_video_boards(output_dir: Path) -> set[str]:names = set()for path in output_dir.glob("v*_*.jpg"):@@ -166,7 +162,7 @@ def build_from_videos(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> in)frame_cache = args.output_dir / "_frames"frame_cache.mkdir(parents=True, exist_ok=True)- connection = _readonly(args.db)+ connection = open_readonly(args.db)rows = connection.execute("SELECT creator,path,name,duration FROM asset WHERE medium='video' ""AND creator IS NOT NULL AND creator<>'' "@@ -238,7 +234,7 @@ def build_from_videos(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> indef build_from_snapshots(args: argparse.Namespace, ffmpeg: str, ffprobe: str) -> int:- connection = _readonly(args.db)+ connection = open_readonly(args.db)rows = connection.execute("SELECT creator,name,path,snapshot_path FROM asset WHERE medium='video' ""AND creator IS NOT NULL AND creator<>'' AND snapshot_path IS NOT NULL "diff --git a/scripts/creator_tags.py b/scripts/creator_tags.pyindex f29a8bc4d..52e2416cf 100644--- a/scripts/creator_tags.py+++ b/scripts/creator_tags.py@@ -30,6 +30,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.scripting import open_readonlyfrom peach.classification import is_probable_mainstream_release, is_structural_creatorfrom peach.entities import upsert_asset_entityfrom peach.migrations import sqlite_backup@@ -77,10 +78,6 @@ SKIPPED = {"tuki_1154": "可用样张仅 5 张且过暗过糊,无法确证任何标签",}-def _readonly(path: Path) -> sqlite3.Connection:- return sqlite3.connect("file:" + path.resolve().as_posix() + "?mode=ro", uri=True)--def _safe_name(value: str) -> str:return re.sub(r"[^\w\u4e00-\u9fff-]", "_", value)[:40]@@ -91,7 +88,7 @@ def _board_identity(path: Path) -> tuple[str, int] | None:def export_review(db_path: Path, board_dir: Path, output: Path) -> tuple[int, int]:- connection = _readonly(db_path)+ connection = open_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<>''"@@ -207,7 +204,7 @@ def main(argv: list[str] | None = None) -> int:print(f"review queue: {total} boards, {pending} pending -> {args.review}")return 0if not args.backup:- raise SystemExit("--apply-review requires --backup")+ raise SystemExit("--apply-review 必须同时给 --backup")assets, rows = apply_review(args.db, args.review, args.backup)print(f"applied: {assets} assets, {rows} tag rows; backup={args.backup}")return 0diff --git a/scripts/fetch_fc2_metadata.py b/scripts/fetch_fc2_metadata.pyindex e1a7b95e6..522651dfc 100644--- a/scripts/fetch_fc2_metadata.py+++ b/scripts/fetch_fc2_metadata.py@@ -39,7 +39,6 @@ import hashlibimport http.cookiejarimport jsonimport re-import sqlite3import timeimport sysfrom pathlib import Path@@ -53,7 +52,7 @@ if str(SRC_DIR) not in sys.path:from peach.catalog_rules import normalise_code_keyfrom peach.review_csv import read_rows, write_rows-from peach.scripting import USER_AGENT+from peach.scripting import USER_AGENT, open_readonlyfrom peach.config import DATABASE_PATH, GENERATED_DIRARTICLE_URL = "https://fc2cmadb.com/articles/{video_id}"@@ -335,8 +334,7 @@ def translated_tags(raw: str) -> list[str]:def metadata_candidate_rows(rows: list[dict], database: Path, *, raw_snapshot: Path,fetched_at: str) -> list[dict]:"""Turn archived article facts into the normal review queue without writing ledger."""- connection = sqlite3.connect(f"file:{database}?mode=ro", uri=True)- connection.row_factory = sqlite3.Row+ connection = open_readonly(database)output = []try:for row in rows:@@ -403,7 +401,7 @@ def metadata_candidate_rows(rows: list[dict], database: Path, *, raw_snapshot: Pdef pending(database: Path, limit: int) -> list[tuple[str, str]]:"""库里的 FC2 资产,按 (code, video_id) 去重。"""- connection = sqlite3.connect(f"file:{database}?mode=ro", uri=True)+ connection = open_readonly(database)try:rows = connection.execute("SELECT DISTINCT code FROM asset "diff --git a/scripts/fetch_jav_covers.py b/scripts/fetch_jav_covers.pyindex b8960b3e6..0a839f759 100644--- a/scripts/fetch_jav_covers.py+++ b/scripts/fetch_jav_covers.py@@ -40,7 +40,6 @@ import argparseimport ioimport jsonimport re-import sqlite3import timeimport urllib.parseimport sys@@ -58,7 +57,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.review_csv import ENCODING, read_rows, write_rows-from peach.scripting import USER_AGENT+from peach.scripting import USER_AGENT, open_readonlyfrom peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.jobs import DiskGuard, JobPolicyError@@ -612,7 +611,7 @@ def restore_logged_successes(transport: HttpTransport, log: Path, root: Path,def pending(database: Path, root: Path, only_shaped: bool,location: str | None = None, *, existing: bool = False,max_width: int = 0, fc2_only: bool = False) -> list[str]:- connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)+ connection = open_readonly(database)try:location_sql = " AND location=?" if location else ""parameters: tuple[object, ...] = (location,) if location else ()@@ -657,7 +656,7 @@ def pending(database: Path, root: Path, only_shaped: bool,def audit_state(database: Path, root: Path, log: Path) -> dict[str, object]:"""只读盘点当前 JAV 封面;用于批次前后使用同一统计口径。"""- connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)+ connection = open_readonly(database)try:raw_codes = [str(row[0]) for row in connection.execute("SELECT DISTINCT code FROM asset WHERE medium='video' "diff --git a/scripts/find_ads.py b/scripts/find_ads.pyindex f8af91107..696db9731 100644--- a/scripts/find_ads.py+++ b/scripts/find_ads.py@@ -28,7 +28,6 @@ import collectionsimport argparseimport osimport re-import sqlite3import sysfrom pathlib import Path, PureWindowsPath@@ -38,6 +37,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.review_csv import write_rows+from peach.scripting import open_readonlyfrom peach.config import DATABASE_PATH, GENERATED_DIRDEFAULT_OUTPUT = GENERATED_DIR / "ad-candidates.csv"@@ -100,7 +100,7 @@ FIELDS = ["id", "location", "dir", "name", "size_mb", "duration",def find_candidates(db_path: Path | str, min_group: int = 3) -> tuple[list[dict], int]:"""只读 ledger 并返回复核候选;不写数据库或文件。"""db_path = Path(db_path)- conn = sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True)+ conn = open_readonly(db_path)rows = conn.execute("SELECT id, location, path, name, size, duration FROM asset ""WHERE medium='video'").fetchall()diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.pyindex 5f5f1ba16..86a0bd8bd 100644--- a/scripts/harvest_performer_links.py+++ b/scripts/harvest_performer_links.py@@ -30,7 +30,7 @@ from peach.entities import name_chain # noqa: E402,F401 测试从本模块取from peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.jobs import job_main # noqa: E402from peach.review_csv import write_rows # noqa: E402-from peach.scripting import USER_AGENT # noqa: E402+from peach.scripting import USER_AGENT, open_readonly # noqa: E402# 平台判据与选人规则和目录型采集器共用,定义在 peach.social_links;这里只保留 minnano-av 的解析。from peach.social_links import classify, load_performers, under # noqa: E402,F401@@ -102,7 +102,7 @@ def scan(http, name: str, timeout: float) -> tuple[list[dict], str, str, str]:def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--database", type=Path, required=True)+ parser.add_argument("--db", type=Path, required=True, help="账本路径")parser.add_argument("--output", type=Path, required=True)parser.add_argument("--min-assets", type=int, default=3)parser.add_argument("--limit", type=int, default=0)@@ -113,7 +113,7 @@ def build_parser() -> argparse.ArgumentParser:def run(args) -> int:- connection = sqlite3.connect(f"file:{args.database}?mode=ro", uri=True)+ connection = open_readonly(args.db)try:performers = load_performers(connection, args.min_assets)finally:diff --git a/scripts/harvest_social_avatars.py b/scripts/harvest_social_avatars.pyindex 7fc159e65..6e18b8cee 100644--- a/scripts/harvest_social_avatars.py+++ b/scripts/harvest_social_avatars.py@@ -60,7 +60,7 @@ from peach.config import DATABASE_PATH, GENERATED_DIR, STATE_DIR # noqa: E402from peach.http import HttpRequest, HttpTransport, HttpxTransport # noqa: E402from peach.review_csv import read_rows, write_rows # noqa: E402from peach.scripting import ( # noqa: E402- USER_AGENT, HostLimiter, host_under, hostname_of,+ USER_AGENT, HostLimiter, host_under, hostname_of, open_readonly,)from peach.social_links import twimg_tiers # noqa: E402@@ -577,7 +577,7 @@ def merge_prior_pending(db_path: Path, new_path: Path, rows: list[dict]) -> None"""decided: set[str] = set()try:- connection = sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True)+ connection = open_readonly(db_path)decided = {str(row[0]) for row in connection.execute("SELECT item_key FROM review_decision WHERE category='performer_avatars'")}connection.close()@@ -630,7 +630,7 @@ def run(args) -> int:"x.com": 2.0, "pbs.twimg.com": 0.3, "lit.link": 1.5,"babepedia.com": 3.0, "linktr.ee": 2.0,})- connection = sqlite3.connect(f"file:{args.db.as_posix()}?mode=ro", uri=True)+ connection = open_readonly(args.db)http = HttpxTransport()caches = {"social": AvatarCandidateCache(args.cache_root / "social"),diff --git a/scripts/harvest_studio_sites.py b/scripts/harvest_studio_sites.pyindex 3e6354563..403216923 100644--- a/scripts/harvest_studio_sites.py+++ b/scripts/harvest_studio_sites.py@@ -29,7 +29,7 @@ from peach.config import STATE_DIR # noqa: E402from peach.http import HttpRequest, HttpxTransport # noqa: E402from peach.jobs import job_main # noqa: E402from peach.review_csv import read_rows, write_rows # noqa: E402-from peach.scripting import USER_AGENT # noqa: E402+from peach.scripting import USER_AGENT, open_readonly # noqa: E402TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)# 抢注页与停放页的自述。它们同样会 200,也同样会在标题里回显域名,@@ -236,7 +236,7 @@ def probe(url: str, timeout: float) -> tuple[int, bytes, str]:def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--database", type=Path, required=True)+ parser.add_argument("--db", type=Path, required=True, help="账本路径")parser.add_argument("--output", type=Path, required=True)parser.add_argument("--seeds", type=Path, help="人工查到的 studio,site 表,优先于推导域名")parser.add_argument("--min-assets", type=int, default=3)@@ -253,7 +253,7 @@ def build_parser() -> argparse.ArgumentParser:def run(args) -> int:import hashlib- connection = sqlite3.connect(f"file:{args.database}?mode=ro", uri=True)+ connection = open_readonly(args.db)try:studios = load_studios(connection, args.min_assets)finally:diff --git a/scripts/install_entity_links.py b/scripts/install_entity_links.pyindex 6e7ca1e51..24e5827d5 100644--- a/scripts/install_entity_links.py+++ b/scripts/install_entity_links.py@@ -26,7 +26,13 @@ import httpxsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.review_csv import read_rows # noqa: E402-from peach.scripting import USER_AGENT # noqa: E402+from peach.scripting import ( # noqa: E402+ BACKUP_REQUIRED,+ USER_AGENT,+ add_ledger_write_args,+ open_for_write,+ verify_after_write,+)LINK_KINDS = {"official", "social", "catalog", "source_reference"}FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "evidence")@@ -205,16 +211,14 @@ def install(connection: sqlite3.Connection, planned: list[dict], source: str) ->def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--database", type=Path, required=True)+ add_ledger_write_args(parser)parser.add_argument("--input", type=Path,help=f"复核表,列:{','.join(FIELDS)}")parser.add_argument("--prune-dead", action="store_true",help="改为清理库里已经打不开的链接,不读 --input")- parser.add_argument("--apply", action="store_true", help="真正写入;必须同时给 --backup")parser.add_argument("--no-check", action="store_true",help="跳过「地址能不能打开」的检查。只在离线复核时用——""首批 703 条就是没验直接装的,事后发现 37%% 是死链")- parser.add_argument("--backup", type=Path, help="写入前的 SQLite 备份落点")return parser@@ -238,19 +242,11 @@ def prune(connection: sqlite3.Connection, args) -> int:print("dry-run;确认无误后加 --apply --backup <路径>")return 0- args.backup.parent.mkdir(parents=True, exist_ok=True)- destination = sqlite3.connect(args.backup)- with destination:- connection.backup(destination)- destination.close()- print(f"已备份:{args.backup}")-with connection:connection.executemany("DELETE FROM entity_link WHERE id=?",[(item["id"],) for item in dead])after = connection.execute("SELECT count(*) FROM entity_link").fetchone()[0]- integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]- orphans = len(connection.execute("PRAGMA foreign_key_check").fetchall())+ integrity, orphans = verify_after_write(connection)print({"删除前": before, "删除后": after, "差值": before - after,"integrity_check": integrity, "foreign_key_check": orphans})if before - after != len(dead) or integrity != "ok" or orphans:@@ -262,14 +258,18 @@ def prune(connection: sqlite3.Connection, args) -> int:def main(argv: list[str] | None = None) -> int:args = build_parser().parse_args(argv)if args.apply and not args.backup:- print("[stop] --apply 是真实账本写入,必须同时给 --backup")+ print(f"[stop] {BACKUP_REQUIRED}")return 2if not args.prune_dead and not args.input:print("[stop] 需要 --input(写入复核表)或 --prune-dead(清理死链)")return 2- connection = sqlite3.connect(args.database)+ # dry-run 拿到的是 `mode=ro` 连接,`--apply` 拿到的是「备份已经落好」的可写连接。+ # 备份先于任何写入完成,所以不必再推断「这份备份是写之前还是写之后的」。+ connection = open_for_write(args)+ if args.apply:+ print(f"已备份:{args.backup}")connection.execute("PRAGMA foreign_keys=ON")if args.prune_dead:try:@@ -296,18 +296,10 @@ def main(argv: list[str] | None = None) -> int:print("dry-run;确认无误后加 --apply --backup <路径>")return 0- args.backup.parent.mkdir(parents=True, exist_ok=True)- destination = sqlite3.connect(args.backup)- with destination:- connection.backup(destination)- destination.close()- print(f"已备份:{args.backup}")-with connection:written = install(connection, planned, source=args.input.name)after = connection.execute("SELECT count(*) FROM entity_link").fetchone()[0]- integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]- orphans = len(connection.execute("PRAGMA foreign_key_check").fetchall())+ integrity, orphans = verify_after_write(connection)print({"实际写入": written, "写入后 entity_link": after, "差值": after - before,"integrity_check": integrity, "foreign_key_check": orphans})if after - before != written or integrity != "ok" or orphans:diff --git a/scripts/match_babepedia_creators.py b/scripts/match_babepedia_creators.pyindex 694d0b40b..f9ce021b6 100644--- a/scripts/match_babepedia_creators.py+++ b/scripts/match_babepedia_creators.py@@ -36,7 +36,6 @@ from __future__ import annotationsimport argparseimport re-import sqlite3import timeimport urllib.parseimport sys@@ -50,7 +49,7 @@ if str(SRC_DIR) not in sys.path:from peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.review_csv import read_rows, write_rows-from peach.scripting import USER_AGENT+from peach.scripting import USER_AGENT, open_readonlyBASE = "https://www.babepedia.com/babe/"@@ -160,7 +159,7 @@ def resolve(transport: HttpTransport, name: str, delay: float,def candidates(database: Path) -> list[tuple[int, str, int]]:- connection = sqlite3.connect(f"file:{database.as_posix()}?mode=ro", uri=True)+ connection = open_readonly(database)try:rows = connection.execute("""SELECT e.id, e.canonical_name,diff --git a/scripts/normalize_studio_logos.py b/scripts/normalize_studio_logos.pyindex dd098967e..2bcb3cacd 100644--- a/scripts/normalize_studio_logos.py+++ b/scripts/normalize_studio_logos.py@@ -20,6 +20,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import GENERATED_DIR+from peach.scripting import BACKUP_REQUIREDfrom peach.images import MAX_ASPECT, measure_image_size, pad_to_squarefrom peach.review_csv import write_rows@@ -52,7 +53,7 @@ def normalize(root: Path, *, apply: bool = False,root = root.resolve()if apply:if backup_dir is None:- raise ValueError("--apply 必须同时提供 --backup-dir")+ raise ValueError(BACKUP_REQUIRED)backup_dir = backup_dir.resolve()if backup_dir == root or root in backup_dir.parents:raise ValueError("备份目录必须在 Logo 目录之外")@@ -107,7 +108,8 @@ def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description="把已安装的长条厂牌 Logo 补成方图")parser.add_argument("--root", type=Path, default=GENERATED_DIR / "logos")parser.add_argument("--apply", action="store_true")- parser.add_argument("--backup-dir", type=Path)+ parser.add_argument("--backup", type=Path,+ help="原图备份目录;--apply 必需")parser.add_argument("--report", type=Path)return parser@@ -115,7 +117,7 @@ def build_parser() -> argparse.ArgumentParser:def main(argv: list[str] | None = None) -> int:args = build_parser().parse_args(argv)try:- rows = normalize(args.root, apply=args.apply, backup_dir=args.backup_dir)+ rows = normalize(args.root, apply=args.apply, backup_dir=args.backup)except (OSError, ValueError) as error:print(str(error))return 2diff --git a/scripts/rediscover_entity_links.py b/scripts/rediscover_entity_links.pyindex ce5b701f7..a4375835e 100644--- a/scripts/rediscover_entity_links.py+++ b/scripts/rediscover_entity_links.py@@ -31,7 +31,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))from peach.entities import name_chain # noqa: E402from peach.review_csv import write_rows # noqa: E402-from peach.scripting import USER_AGENT # noqa: E402+from peach.scripting import USER_AGENT, RateLimiter, open_readonly # noqa: E402ANCHOR = re.compile(r'<a\s[^>]*href=["\']([^"\']+)["\']([^>]*)>(.*?)</a>', re.S | re.I)TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.S | re.I)@@ -124,6 +124,7 @@ def confirms(html: str, names: list[str]) -> str:def rediscover(record: dict, interval: float, timeout: float) -> dict:"""给一条死链找回它现在的地址。就地返回一行复核结果。"""+ limiter = RateLimiter(interval)names = record["chain"]row = {field: "" for field in FIELDS}row.update(entity_id=record["entity_id"], kind=record["kind"], name=record["name"],@@ -135,8 +136,8 @@ def rediscover(record: dict, interval: float, timeout: float) -> dict:seen: set[str] = set()for index in index_candidates(record["url"]):+ limiter.wait()status, html, final = fetch(index, timeout)- time.sleep(interval)if status != 200 or not html:continuefor target, matched in anchors_naming(html, final, names):@@ -149,8 +150,8 @@ def rediscover(record: dict, interval: float, timeout: float) -> dict:if not same_site(target, record["url"]):continueseen.add(target)+ limiter.wait()hit_status, hit_html, hit_final = fetch(target, timeout)- time.sleep(interval)if hit_status != 200:continuetitle = confirms(hit_html, names)@@ -183,7 +184,7 @@ def load_dead(connection: sqlite3.Connection) -> list[dict]:def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--database", type=Path, required=True)+ parser.add_argument("--db", type=Path, required=True, help="账本路径")parser.add_argument("--output", type=Path, required=True)parser.add_argument("--dead-list", type=Path, required=True,help="entity-link-check CSV,只处理其中 status 为 404/410 的行")@@ -199,7 +200,7 @@ def main(argv: list[str] | None = None) -> int:args = build_parser().parse_args(argv)gone = {row["url"] for row in read_rows(args.dead_list)if str(row.get("status") or "") in {"404", "410"}}- connection = sqlite3.connect(f"file:{args.database}?mode=ro", uri=True)+ connection = open_readonly(args.db)try:targets = [record for record in load_dead(connection)if record["url"] in gone]diff --git a/scripts/rehome_unknown_jav.py b/scripts/rehome_unknown_jav.pyindex af35bbbed..5aebe65b7 100644--- a/scripts/rehome_unknown_jav.py+++ b/scripts/rehome_unknown_jav.py@@ -23,6 +23,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.config import DATABASE_PATH, GENERATED_DIR+from peach.scripting import open_readonlyfrom peach.entities import upsert_asset_entityfrom peach.migrations import sqlite_backupfrom peach.review_csv import ENCODING, write_rows@@ -262,7 +263,7 @@ def apply_plan(_check_database(connection)before_assets = connection.execute("SELECT count(*) FROM asset").fetchone()[0]sqlite_backup(Path(connection.execute("PRAGMA database_list").fetchone()[2]), backup)- saved = sqlite3.connect(f"file:{backup}?mode=ro", uri=True)+ saved = open_readonly(backup)try:_check_database(saved)if saved.execute("SELECT count(*) FROM asset").fetchone()[0] != before_assets:diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.pyindex 7b97c4e6c..d759c8069 100644--- a/scripts/scrape_codes.py+++ b/scripts/scrape_codes.py@@ -26,6 +26,7 @@ if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))from peach.catalog_rules import normalise_code_key+from peach.scripting import open_readonlyfrom peach.config import DATABASE_PATH, GENERATED_DIR, LOG_DIR, SOURCES_DIR, STATE_DIRfrom peach.jobs import DiskGuard, JobPolicyErrorfrom peach.metadata import (@@ -406,7 +407,7 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | Nonehealth = _health_rows(policy)adapter = provider or JavinizerGoProvider.create(args.binary, args.config)- connection = sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True)+ connection = open_readonly(args.db)codes = [(str(row[0]).strip(), float(row[1]), int(row[2]))for row in connection.execute(diff --git a/tests/test_entity_link_install.py b/tests/test_entity_link_install.pyindex 987a881a5..6273ec1a9 100644--- a/tests/test_entity_link_install.py+++ b/tests/test_entity_link_install.py@@ -127,7 +127,7 @@ class InstallTests(unittest.TestCase):def test_apply_without_backup_refuses_and_writes_nothing(self):"""真实账本写入必须带备份;缺备份要在读输入之前就停。"""- code = self.module.main(["--database", str(self.db), "--input", str(self.tmp / "x.csv"),+ code = self.module.main(["--db", str(self.db), "--input", str(self.tmp / "x.csv"),"--apply"])self.assertEqual(code, 2)self.assertEqual(@@ -141,7 +141,7 @@ class InstallTests(unittest.TestCase):encoding="utf-8-sig")# `--no-check` 不只是提速:测试不许发网络请求,否则一次断网就变成红灯。self.assertEqual(self.module.main(- ["--database", str(self.db), "--input", str(source), "--no-check"]), 0)+ ["--db", str(self.db), "--input", str(source), "--no-check"]), 0)self.assertEqual(self.connection.execute("SELECT count(*) FROM entity_link").fetchone()[0], 0)diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 2c429f887..e403fc241 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -13,7 +13,7 @@ from types import SimpleNamespacefrom unittest import mockfrom peach import catalog_rules, scripting-from peach.migrations import upgrade+from peach.migrations import sqlite_backup, upgradefrom peach.classification import is_probable_mainstream_release, is_structural_creator@@ -43,6 +43,31 @@ class OperationalScriptTests(unittest.TestCase):cls.creator_attributions = load_script("audit_creator_attributions")cls.rehome_unknown = load_script("rehome_unknown_jav")+ def tmp_ledger(self) -> Path:+ """一份只含 rule34xxx 追更条目的临时账本:一条已有类型、一条还没有。++ 临时目录先 `.resolve()`:CI runner 的临时目录都是别名(macOS `/var` 软链到+ `/private/var`,Windows `RUNNER~1` 展开成 `runneradmin`),不 resolve 的路径+ 喂给被测代码只会在 CI 上红。+ """+ root = Path(tempfile.mkdtemp()).resolve()+ database = root / "ledger.db"+ connection = sqlite3.connect(database)+ connection.executescript(+ "CREATE TABLE follow_source(id INTEGER PRIMARY KEY, provider TEXT);"+ "CREATE TABLE follow_item(id INTEGER PRIMARY KEY, source_id INTEGER,"+ " external_id TEXT, url TEXT, metadata_json TEXT);")+ connection.execute("INSERT INTO follow_source VALUES(1,'rule34xxx')")+ connection.executemany(+ "INSERT INTO follow_item VALUES(?,1,?,?,?)",+ [(1, "18622796", "https://rule34.xxx/index.php?id=18622796",+ json.dumps({"tag_types": {"nier": "copyright"}})),+ (2, "18622794", "https://rule34.xxx/index.php?id=18622794",+ json.dumps({"tag_types": {}}))])+ connection.commit()+ connection.close()+ return database+def test_import_has_no_filesystem_or_log_side_effect(self):self.assertIsNone(self.clean_names._logf)self.assertIsNone(self.scrape_codes._logf)@@ -122,17 +147,31 @@ class OperationalScriptTests(unittest.TestCase):常规检查只看第一页,补不到历史条目。抓取判据不重写,直接复用连接器的`_detail_tag_types`;备份先做、分批提交,中断一次不至于白跑五十分钟。"""- source = (ROOT / "scripts" / "backfill_rule34_tag_types.py").read_text(encoding="utf-8")- self.assertIn("connector._detail_tag_types(post_id)", source)- self.assertIn('if args.apply and not args.backup:', source)- # WAL 库不能用 `shutil.copy2` 备份:已提交但未 checkpoint 的事务在 `-wal` 里,- # 只复制主库会得到一份少了最近改动、却看起来完全正常的账本。- self.assertIn("reader.backup(writer)", source)- self.assertNotIn("shutil.copy2(database", source)- self.assertIn("writer.commit()", source)- # 取不到不等于这条没有类型:不写空字典冒充已补,下一轮还要再问。- self.assertIn('if not tag_types:', source)- self.assertIn('return 0 if before == after else 1', source)+ backfill = load_script("backfill_rule34_tag_types")+ # 备份走共享的 `sqlite_backup`,WAL 正确性由 `scripting` 那条回归测试守住;+ # 这里只钉「用的是那一份」。以前这条断言读的是源码里有没有+ # `reader.backup(writer)` 这串字符,脚本改成调用共享实现就红了——而行为+ # 恰恰是变好了。+ self.assertIs(backfill.sqlite_backup, sqlite_backup)+ self.assertIs(backfill.open_readonly, scripting.open_readonly)+ self.assertEqual(backfill.BACKUP_REQUIRED, scripting.BACKUP_REQUIRED)++ # 缺 `--backup` 的 `--apply` 在读输入之前就停,返回 2 且一行都不写。+ database = self.tmp_ledger()+ args = backfill.build_parser().parse_args(+ ["--db", str(database), "--apply"])+ self.assertEqual(backfill.run(args), 2)++ # `--limit` 之外的两条判据也用真实数据钉住:已经有 tag_types 的条目不再排队,+ # 取不到的条目不写空字典冒充已补(下一轮还要再问)。+ connection = sqlite3.connect(database)+ self.addCleanup(connection.close)+ connection.row_factory = sqlite3.Row+ pending = backfill.pending_rows(connection, 0)+ self.assertEqual([row["external_id"] for row in pending], ["18622794"])+ self.assertEqual(+ json.loads(backfill.merge_tag_types({"tags": "a b"}, {"a": "artist"})),+ {"tags": "a b", "tag_types": {"a": "artist"}})def test_test_entrypoint_enforces_worktree_source_and_unittest(self):windows = (ROOT / "scripts" / "test.ps1").read_text(encoding="utf-8")