Peach: Local-first video metadata scraper and media manager.
fix(media): 统一命令行抽帧的预览开关与指针边界
longmeidao1170c594066c
diff --git a/scripts/probe.py b/scripts/probe.pyindex e282c825e..ef3d3dafb 100644--- a/scripts/probe.py+++ b/scripts/probe.py@@ -130,7 +130,8 @@ def run(args: argparse.Namespace) -> int:if args.limit:sql += " LIMIT ?"parameters += (args.limit,)- tasks = connection.execute(sql, parameters).fetchall()+ from peach.strm import background_rows+ tasks = background_rows(connection.execute(sql, parameters).fetchall(), 1)connection.close()total = len(tasks)log(f"待处理 {total:,} 个视频 workers={args.workers} interval={args.interval}s 日志={log_path}")diff --git a/scripts/sheets.py b/scripts/sheets.pyindex 7b5296cf4..b8aab4273 100644--- a/scripts/sheets.py+++ b/scripts/sheets.py@@ -33,6 +33,8 @@ from peach.jobs import ()from peach.platform import system_volumefrom peach.media import resolve_case_insensitive+from peach.media_processing_policy import metadata_only+from peach.strm import background_rows, skip_background_readdef build_parser() -> argparse.ArgumentParser:@@ -93,12 +95,16 @@ def make_sheet(ffmpeg: str, path: str, duration: float, destination: Path,失败时返回可区分的原因,不能只返回「失败」:asset 12510 与 18349 都失败了一整天,一个是片源头损坏、一个是账本时长记错,光看计数分不出来,也就没法决定该修哪一边。"""+ if skip_background_read(path):+ return False, "unsupported_source"if not duration or duration < 2:return False, "no_duration"temporary = Path(tempfile.mkdtemp(prefix="sheet_"))try:captured: list[Path] = []for index in range(frames):+ if metadata_only():+ return False, "previews_disabled"timestamp = duration * (0.03 + 0.94 * (index + 0.5) / frames)frame = temporary / f"{index:02d}.jpg"ok, stderr = _capture_frame(ffmpeg, path, timestamp, frame, color_override=False)@@ -123,7 +129,23 @@ def make_sheet(ffmpeg: str, path: str, duration: float, destination: Path,shutil.rmtree(temporary, ignore_errors=True)+def _require_previews_enabled() -> None:+ if metadata_only():+ raise JobPolicyError("视频预览生成已关闭,请先在媒体库设置中开启")+++def _preview_active(stop, reasons) -> bool:+ if stop.is_set():+ return False+ if metadata_only():+ reasons.append("视频预览生成已关闭")+ stop.set()+ return False+ return True++def run(args: argparse.Namespace) -> int:+ _require_previews_enabled()if args.workers < 1 or args.frames < 2 or args.limit < 0:raise SystemExit("workers 必须大于 0,frames 至少为 2,limit 不能为负数")resolver = FFmpegResolver(FFMPEG_DIR)@@ -170,7 +192,7 @@ def run(args: argparse.Namespace) -> int:if args.limit:sql += " LIMIT ?"parameters += (args.limit,)- tasks = connection.execute(sql, parameters).fetchall()+ tasks = background_rows(connection.execute(sql, parameters).fetchall(), 2)connection.close()total = len(tasks)log(f"待处理 {total:,} 个视频 workers={args.workers} frames={args.frames} 日志={log_path}")@@ -191,7 +213,7 @@ def run(args: argparse.Namespace) -> int:stop_reason: list[str] = []def worker() -> None:- while not stop.is_set():+ while _preview_active(stop, stop_reason):try:asset_id, location, path, duration = pending.get_nowait()except queue.Empty:@@ -264,7 +286,7 @@ def run(args: argparse.Namespace) -> int:connection.close()if stop_reason:# 已完成的部分都已入库;磁盘闸门中止不能报成正常完成,否则续跑决策会被误导。- log(f"磁盘闸门中止:{stop_reason[0]}")+ log(f"任务中止:{stop_reason[0]}")return DiskSpaceDenied.exit_codereturn 0diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 8a6a37157..e1092502e 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -67,7 +67,8 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_mp4recover.py", "test_web_media_repair.py","test_previews.py", "test_preview_transport.py","test_providers.py", "test_segments.py", "test_streaming.py",- "test_subtitles.py", "test_transcodes.py"),+ "test_subtitles.py", "test_transcodes.py", "test_strm.py",+ "test_guangya_sources.py", "test_media_sources.py"),"sync": ("test_sync*.py", "test_platform.py", "test_mount.py", "test_tray*.py", "test_log_retention.py","test_mdns.py", "test_netwatch.py", "test_certs.py","test_review_mirror.py", "test_runtime_prepare.py"),diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex e9cfadd86..e05ca230a 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -1890,6 +1890,21 @@ class _LibraryCheckpoints:if _checkpoint_key(row) not in self.completed['completed_metadata'])+def _validate_processing_request(config, db_path, stage, asset_ids, retry_ids, database):+ """校验处理范围、选择与预览生成所需条件,返回规范的所选影片。"""+ _require_writer(config, db_path)+ if stage not in STAGES:+ raise ValueError('处理阶段无效')+ if stage == PREVIEWS_STAGE and metadata_only(config.directory('state')):+ raise ValueError('视频预览生成已关闭,请先在媒体库设置中开启')+ if asset_ids is not None and retry_ids is not None:+ raise ValueError('选择项目与失败重试不能同时使用')+ selected_ids = _asset_selection(db_path, asset_ids)+ if stage == PREVIEWS_STAGE and database is None:+ raise ValueError('生成预览图需要共享馆藏写入连接')+ return selected_ids++def process_library(config, db_path, candidate_root, cover_root, *, location='configured',report=lambda state: None, provider_factory=None, job_id=None,retry_ids=None, active=lambda: True, stage=ALL_STAGES,@@ -1911,16 +1926,7 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='co`metadata_routes.parse_route_overrides`;不给就用内建那张表。`state_file` 给后台定向任务保存独立进度,共享候选写入仍使用全库处理锁。"""- _require_writer(config, db_path)- if stage not in STAGES:- raise ValueError('处理阶段无效')- if stage == PREVIEWS_STAGE and metadata_only(config.directory('state')):- raise ValueError('视频预览生成已关闭,请先在媒体库设置中开启')- if asset_ids is not None and retry_ids is not None:- raise ValueError('选择项目与失败重试不能同时使用')- selected_ids = _asset_selection(db_path, asset_ids)- if stage == PREVIEWS_STAGE and database is None:- raise ValueError('生成预览图需要共享馆藏写入连接')+ selected_ids = _validate_processing_request(config, db_path, stage, asset_ids, retry_ids, database)routes = metadata_routes.parse_route_overrides(route_overrides)path = Path(state_file) if state_file is not None else state_path(config)path.parent.mkdir(parents=True, exist_ok=True)diff --git a/src/peach/strm.py b/src/peach/strm.pyindex d22c30210..50ee2675d 100644--- a/src/peach/strm.py+++ b/src/peach/strm.py@@ -17,6 +17,11 @@ def skip_background_read(path: str | Path) -> bool:return Path(path).suffix.lower() in DISC_SUFFIXES | {POINTER_SUFFIX}+def background_rows(rows, path_index: int):+ """批处理只领取可读取的视频文件,保留调用方的行形状。"""+ return [row for row in rows if not skip_background_read(row[path_index])]++def validate_url(url: str) -> str:try:parts = urlsplit(url)diff --git a/tests/test_complexity_ratchet.py b/tests/test_complexity_ratchet.pyindex 625afd360..73a32a186 100644--- a/tests/test_complexity_ratchet.py+++ b/tests/test_complexity_ratchet.py@@ -72,7 +72,7 @@ ACCEPTED: dict[str, tuple[int, str]] = {41, "应用工厂:按启动顺序构造账本、各项后台服务与路由并接成一个 app,每个可注入的""依赖各带一个缺省;挂载探测按配置状态启动。拆开会把同一条构造顺序分散到几处"),"src/peach/library_processing.py:process_library": (- 62, "顺序流水线:本地预览、读本地资料、联网采集、写候选、收尾共用一份进度状态"+ 58, "顺序流水线:本地预览、读本地资料、联网采集、写候选、收尾共用一份进度状态""与问题记录;来源扫描、资产查询与外部会话分别归 `_scan_sources`、""`_collection_rows`、`_RemoteSession`,剩下的是任务编排与逐项目资料处理"),"src/peach/jav_cover_fetch.py:run": (diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 87d9d2fde..6d518770b 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -1083,6 +1083,11 @@ class LibraryDirectoryTests(unittest.TestCase):class OperationalScriptTests(unittest.TestCase):+ def setUp(self):+ policy = mock.patch.object(self.sheets, "metadata_only", return_value=False)+ policy.start()+ self.addCleanup(policy.stop)+@classmethoddef setUpClass(cls):cls.clean_names = load_script("clean_names")@@ -2844,6 +2849,26 @@ class OperationalScriptTests(unittest.TestCase):self.assertEqual(rewritten[:1], b"y", "陈旧产物必须被真正覆盖")self.assertIsNone(snapshots[1], "没点名的待抽项不该被这一趟带走")+ def test_sheets_obeys_preview_mode_and_never_extracts_pointer_or_disc_frames(self):+ with mock.patch.object(self.sheets, "metadata_only", return_value=True), \+ mock.patch.object(self.sheets.FFmpegResolver, "ffmpeg") as resolver:+ with self.assertRaisesRegex(self.sheets.JobPolicyError, "视频预览生成已关闭"):+ self.sheets.run(self.sheets.build_parser().parse_args([]))+ resolver.assert_not_called()+ with mock.patch.object(self.sheets, "_capture_frame") as capture:+ for source in ("movie.strm", "movie.ISO"):+ self.assertEqual(self.sheets.make_sheet("ffmpeg", source, 60, Path("unused.jpg"), 9),+ (False, "unsupported_source"))+ capture.assert_not_called()++ def test_sheets_stops_extracting_frames_when_preview_mode_is_disabled(self):+ with tempfile.TemporaryDirectory() as temporary, \+ mock.patch.object(self.sheets, "metadata_only", side_effect=[False, True]), \+ mock.patch.object(self.sheets, "_capture_frame", return_value=(False, "")) as capture:+ result = self.sheets.make_sheet("ffmpeg", "movie.mp4", 60, Path(temporary) / "sheet.jpg", 9)+ self.assertEqual(result, (False, "previews_disabled"))+ self.assertEqual(capture.call_count, 1)+def test_sheets_leaves_the_recycle_bin_alone_unless_a_row_is_named(self):"""回收站里的行不领,点名的除外。