Peach: Local-first video metadata scraper and media manager.
refactor(scan): 扫描搬进 peach.scan,脚本只做薄委托
longmeidao6cdba2f7446a
diff --git a/scripts/ledger.py b/scripts/ledger.pyindex 093ff02da..c0793bfaa 100644--- a/scripts/ledger.py+++ b/scripts/ledger.py@@ -27,15 +27,13 @@ if str(SRC_DIR) not in sys.path:from peach.stash import StashClient, StashErrorfrom peach.entities import canonicalize_entity_name, upsert_asset_entityfrom peach.config import DATABASE_PATH-from peach.platform import declared_root, location_of, location_roots+from peach.platform import location_mounts, location_roots+from peach.scan import ScanTargetError, ledger_root_for, scan_location+from peach.scan import check_scan_target as _check_scan_target# 账本位置只有 `peach.config` 一处判据,这里不写死 `R:\peach-data\...` 之类的盘上# 路径:数据根搬走时写死的路径不会报「配置过时」,它只会安静地建一个空库。DB = str(DATABASE_PATH)-VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg", ".m2ts"}-IMAGE = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}-AUDIO = {".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus"}-ARCHIVE = {".zip", ".rar", ".7z", ".tar", ".gz"}SCHEMA = """CREATE TABLE IF NOT EXISTS source(@@ -136,15 +134,6 @@ def conn():return c-def medium_of(name):- e = os.path.splitext(name)[1].lower()- if e in VIDEO: return "video"- if e in IMAGE: return "image"- if e in AUDIO: return "audio"- if e in ARCHIVE: return "archive"- return "other"--def ctx_from(size, w=None, h=None, dur=None):orient = quality = length = Noneif w and h:@@ -162,59 +151,24 @@ def cmd_init():def check_scan_target(location, root):- """扫描根必须落在这个来源的声明根内,否则拒绝。-- `asset.location` 是挂载点 ID,`[media.locations]` 给出它在账本里的声明根。- 这两者对不上时写进去的行既翻译不出本机路径、也通不过授权根,而且要等到有人- 点开那个资产才会发现。ADR-0023 第 2 阶段把这一条从口头约定变成写入侧门槛。- """- declared = declared_root(location)- if declared is None:- known = "、".join(sorted(location_roots())) or "(设置文件里一个都没有)"- sys.exit(f"✗ 未声明的来源 {location!r};[media.locations] 里已知:{known}")- actual = location_of(root)- if actual != location:- sys.exit(- f"✗ 扫描根与来源对不上:{location} 的声明根是 {declared},"- f"但要扫的是 {root}"- + (f"(那是 {actual} 的地盘)" if actual else "(不在任何声明根下)")- )+ """扫描根必须落在这个来源的声明根内,否则拒绝。判据在 `peach.scan`,这里只转成退出码。"""+ try:+ _check_scan_target(location, root, declared_roots=location_roots())+ except ScanTargetError as exc:+ sys.exit(str(exc))def cmd_scan(location, root):+ """薄委托:声明根与挂载表取当前设置文件,扫描本体在 `peach.scan.scan_location`。"""+ roots, mounts = location_roots(), location_mounts()+ try:+ root = ledger_root_for(location, root, declared_roots=roots, mounts=mounts)+ except ScanTargetError as exc:+ sys.exit(str(exc))check_scan_target(location, root)- c = conn(); c.executescript(SCHEMA)- now = time.strftime("%Y-%m-%d %H:%M:%S")- t0 = time.time(); n = 0; tot = 0- batch = []- for dp, dn, fns in os.walk(root, onerror=lambda e: None):- for f in fns:- p = os.path.join(dp, f)- try:- st = os.stat(p)- sz, mt = st.st_size, time.strftime("%Y-%m-%d", time.localtime(st.st_mtime))- except OSError:- continue- batch.append((location, p, f, medium_of(f), sz, mt, now, now))- n += 1; tot += sz- if len(batch) >= 2000:- c.executemany("""INSERT INTO asset(location,path,name,medium,size,mtime,first_seen,last_seen)- VALUES(?,?,?,?,?,?,?,?)- ON CONFLICT(location,path) DO UPDATE SET- size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen""", batch)- c.commit(); batch.clear()- print(f" {time.time()-t0:5.0f}s {n:,} 文件 {tot/1024**4:.2f} TB", flush=True)- if batch:- c.executemany("""INSERT INTO asset(location,path,name,medium,size,mtime,first_seen,last_seen)- VALUES(?,?,?,?,?,?,?,?)- ON CONFLICT(location,path) DO UPDATE SET- size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen""", batch)- # 标记本次没扫到的(= 已删除)- c.execute("UPDATE asset SET last_seen=last_seen WHERE location=?", (location,))- c.commit()- gone = c.execute("SELECT COUNT(*) FROM asset WHERE location=? AND last_seen<?", (location, now)).fetchone()[0]- print(f"✓ {location}: {n:,} 文件 / {tot/1024**4:.2f} TB / 耗时 {time.time()-t0:.0f}s;清单中已消失 {gone:,} 个")- c.close()+ c = conn(); c.executescript(SCHEMA); c.commit(); c.close()+ scan_location(DB, location, root, declared_roots=roots, mounts=mounts,+ report=lambda line: print(line, flush=True))def cmd_stash(client=None):diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 404c746bf..dfd8a948e 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -51,6 +51,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_javdb_cn_names.py","test_link_rediscovery.py", "test_link_label_owner.py"),"tooling": ("test_scripts.py", "test_cli.py", "test_script_policy.py",+ "test_scan.py", "test_onboarding.py","test_agent_worktree.py", "test_dependency_policy.py","test_restart_windows_tray.py","test_versioning.py",diff --git a/src/peach/platform.py b/src/peach/platform.pyindex df47a86aa..4d9b01b64 100644--- a/src/peach/platform.py+++ b/src/peach/platform.py@@ -15,6 +15,7 @@ from __future__ import annotationsimport loggingimport os+from collections.abc import Mappingfrom functools import lru_cachefrom pathlib import Path, PureWindowsPath@@ -64,20 +65,26 @@ def declared_root(location: str) -> str | None:return location_roots().get(location)-def resolve_location(raw: str | os.PathLike[str]) -> tuple[str | None, tuple[str, ...]]:+def resolve_location(+ raw: str | os.PathLike[str], roots: Mapping[str, str] | None = None,+) -> tuple[str | None, tuple[str, ...]]:"""账本路径属于哪个来源,以及它在声明根之后的层级。翻译和写入侧门槛共用这一段判定,所以它只碰 `PureWindowsPath` 和字符串,在两个平台上行为一致、也都能测。声明根重叠时取最长的那个(`R:\\` 与`R:\\media` 同时声明时,`R:\\media\\x` 归后者)。大小写不敏感由`PureWindowsPath` 负责:账本里写 `R:\\Media`、声明根写 `R:\\media` 是同一处。++ `roots` 缺省取当前生效的 `[media.locations]`。`peach init` 刚写完设置文件时进程里+ 那份缓存还是旧的,这种调用方把要用的声明根显式传进来。"""text = os.fspath(raw)if not is_windows_path(text):return None, ()candidate = PureWindowsPath(text)best: tuple[int, str] | None = None- for location, root in location_roots().items():+ declared_roots = location_roots() if roots is None else roots+ for location, root in declared_roots.items():declared = PureWindowsPath(root)if candidate == declared or candidate.is_relative_to(declared):depth = len(declared.parts)@@ -88,12 +95,14 @@ def resolve_location(raw: str | os.PathLike[str]) -> tuple[str | None, tuple[strreturn best[1], candidate.parts[best[0]:]-def location_of(raw: str | os.PathLike[str]) -> str | None:+def location_of(+ raw: str | os.PathLike[str], roots: Mapping[str, str] | None = None,+) -> str | None:"""账本路径属于哪个来源;不在任何声明根下则返回 None。- 写入侧用它拦截「location 和 root 对不上」的导入(`scripts/ledger.py scan`)。+ 写入侧用它拦截「location 和 root 对不上」的导入(`peach.scan.check_scan_target`)。"""- return resolve_location(raw)[0]+ return resolve_location(raw, roots)[0]def root_online(root: Path) -> bool:diff --git a/src/peach/scan.py b/src/peach/scan.pynew file mode 100644index 000000000..2b011cf54--- /dev/null+++ b/src/peach/scan.py@@ -0,0 +1,193 @@+"""扫描一个来源的目录,把文件元数据写进账本。++这是摄取入口,不是复核写入:它新增行、刷新 `size`/`mtime`/`last_seen`,不改任何+真相字段,也不删行——本次没扫到的文件只会在 `last_seen` 上落后,由资源同步对账决定去留。++两条不变量都在这里守:++- `asset.location` 是来源 ID,`asset.path` 一律是 Windows 形态的账本路径。扫描根必须+ 落在该来源 `[media.locations]` 声明根之内(`check_scan_target`),否则写进去的行既+ 翻译不出本机路径、也通不过授权根,而且要等到有人点开那个资产才会发现。+- 目录在本机哪里,由 `[media.mounts]` 决定。Windows 上盘符本身就是挂载点,声明根原样+ 就是要遍历的目录;macOS 上遍历的是挂载点,写进账本的仍是 `声明根\\相对路径`,这样+ 读取侧的 `platform.translate_ledger_path` 才翻得回同一个文件。++`peach init` 的首次扫描、`peach scan` 与 `scripts/ledger.py scan` 都调这里,+声明根和挂载表由调用方传入而不是读进程缓存:`init` 刚写完设置文件时缓存还是旧的。+"""+from __future__ import annotations++import os+import sqlite3+import time+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from pathlib import Path, PureWindowsPath++from .platform import is_windows_path, resolve_location++VIDEO = {".mp4", ".m4v", ".mkv", ".avi", ".wmv", ".mov", ".ts", ".flv", ".rmvb", ".mpg",+ ".m2ts"}+IMAGE = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}+AUDIO = {".mp3", ".flac", ".wav", ".m4a", ".ogg", ".opus"}+ARCHIVE = {".zip", ".rar", ".7z", ".tar", ".gz"}++#: 每攒够这么多行落一次盘,并报一行进度。+BATCH_SIZE = 2000++_UPSERT = """INSERT INTO asset(location,path,name,medium,size,mtime,first_seen,last_seen)+ VALUES(?,?,?,?,?,?,?,?)+ ON CONFLICT(location,path) DO UPDATE SET+ size=excluded.size, mtime=excluded.mtime, last_seen=excluded.last_seen"""+++class ScanTargetError(ValueError):+ """来源与扫描根对不上,或者来源在本机没有落点。消息可以直接给人看。"""+++def medium_of(name: str) -> str:+ suffix = os.path.splitext(name)[1].lower()+ if suffix in VIDEO:+ return "video"+ if suffix in IMAGE:+ return "image"+ if suffix in AUDIO:+ return "audio"+ if suffix in ARCHIVE:+ return "archive"+ return "other"+++def check_scan_target(+ location: str, root: str, *, declared_roots: Mapping[str, str],+) -> None:+ """扫描根必须落在这个来源的声明根内,否则拒绝(ADR-0023 第 2 阶段的写入侧门槛)。"""+ declared = declared_roots.get(location)+ if declared is None:+ known = "、".join(sorted(declared_roots)) or "(设置文件里一个都没有)"+ raise ScanTargetError(f"✗ 未声明的来源 {location!r};[media.locations] 里已知:{known}")+ actual = resolve_location(root, declared_roots)[0]+ if actual != location:+ raise ScanTargetError(+ f"✗ 扫描根与来源对不上:{location} 的声明根是 {declared},"+ f"但要扫的是 {root}"+ + (f"(那是 {actual} 的地盘)" if actual else "(不在任何声明根下)")+ )+++def ledger_root_for(+ location: str, root: str | os.PathLike[str], *,+ declared_roots: Mapping[str, str], mounts: Mapping[str, str | Path],+ windows: bool | None = None,+) -> str:+ """把用户给的目录换成账本口径的扫描根。++ Windows 上任何绝对路径本来就是账本形态,相对路径先按当前目录补全。其他平台上+ 给的是本机目录(挂载点下的某一层),换成 `声明根\\相对路径`;没有挂载点或不在+ 挂载点下都拒绝——那种目录扫出来的行谁也翻译不回去。+ """+ windows = os.name == "nt" if windows is None else windows+ text = os.fspath(root)+ if windows:+ return text if is_windows_path(text) else str(Path(text).resolve())+ declared = declared_roots.get(location)+ mount = mounts.get(location)+ if mount and declared is not None:+ try:+ tail = Path(text).resolve().relative_to(Path(mount).resolve()).parts+ except ValueError:+ pass+ else:+ return str(PureWindowsPath(declared, *tail))+ if is_windows_path(text):+ return text+ if not mount:+ raise ScanTargetError(+ f"✗ 来源 {location!r} 在本机没有挂载点,无法把 {text} 换成账本路径;"+ f"先在 [media.mounts] 里声明它的落点")+ raise ScanTargetError(f"✗ {text} 不在来源 {location!r} 的挂载点 {mount} 之下")+++def walk_root_for(+ location: str, root: str, *, declared_roots: Mapping[str, str],+ mounts: Mapping[str, str | Path], windows: bool | None = None,+) -> Path:+ """账本口径的扫描根在本机要遍历哪个目录。调用前先过 `check_scan_target`。"""+ windows = os.name == "nt" if windows is None else windows+ if windows:+ return Path(root)+ mount = mounts.get(location)+ if not mount:+ raise ScanTargetError(+ f"✗ 来源 {location!r} 在本机没有挂载点;先在 [media.mounts] 里声明它的落点")+ return Path(mount).joinpath(*resolve_location(root, declared_roots)[1])+++@dataclass(frozen=True)+class ScanResult:+ location: str+ root: str+ files: int+ total_bytes: int+ seconds: float+ #: 该来源里本次没扫到的行数(`last_seen` 落后于本次)。+ gone: int++ def summary(self) -> str:+ return (f"✓ {self.location}: {self.files:,} 文件 / "+ f"{self.total_bytes / 1024 ** 4:.2f} TB / 耗时 {self.seconds:.0f}s;"+ f"清单中已消失 {self.gone:,} 个")+++def scan_location(+ db_path: str | os.PathLike[str], location: str, root: str, *,+ declared_roots: Mapping[str, str], mounts: Mapping[str, str | Path] | None = None,+ report: Callable[[str], None] = print, windows: bool | None = None,+) -> ScanResult:+ """遍历 `root`(账本口径)对应的本机目录,把文件元数据 upsert 进 `asset`。++ 读不了的目录和文件直接跳过,不中断整轮:网盘挂载里零星几个条目读失败很常见,+ 一个坏条目不该让几万个好条目白扫。+ """+ check_scan_target(location, root, declared_roots=declared_roots)+ walk_root = walk_root_for(+ location, root, declared_roots=declared_roots, mounts=mounts or {}, windows=windows)+ ledger_root = PureWindowsPath(root)+ now = time.strftime("%Y-%m-%d %H:%M:%S")+ started = time.time()+ files = 0+ total = 0+ batch: list[tuple] = []+ connection = sqlite3.connect(db_path)+ try:+ connection.execute("PRAGMA journal_mode=WAL")+ for directory, _subdirs, names in os.walk(walk_root, onerror=lambda _error: None):+ relative = Path(directory).relative_to(walk_root).parts+ for name in names:+ try:+ stat = os.stat(os.path.join(directory, name))+ except OSError:+ continue+ ledger_path = str(ledger_root.joinpath(*relative, name))+ mtime = time.strftime("%Y-%m-%d", time.localtime(stat.st_mtime))+ batch.append((location, ledger_path, name, medium_of(name),+ stat.st_size, mtime, now, now))+ files += 1+ total += stat.st_size+ if len(batch) >= BATCH_SIZE:+ connection.executemany(_UPSERT, batch)+ connection.commit()+ batch.clear()+ report(f" {time.time() - started:5.0f}s {files:,} 文件 "+ f"{total / 1024 ** 4:.2f} TB")+ if batch:+ connection.executemany(_UPSERT, batch)+ connection.commit()+ gone = connection.execute(+ "SELECT COUNT(*) FROM asset WHERE location=? AND last_seen<?",+ (location, now)).fetchone()[0]+ finally:+ connection.close()+ result = ScanResult(location, root, files, total, time.time() - started, gone)+ report(result.summary())+ return resultdiff --git a/tests/test_scan.py b/tests/test_scan.pynew file mode 100644index 000000000..f6aed995d--- /dev/null+++ b/tests/test_scan.py@@ -0,0 +1,163 @@+"""`peach.scan`:扫描写进账本的行必须能被读取侧翻译回同一个文件。++两种设置文件写法各一条:Windows 上 `[media.locations] local = <真实目录>`、挂载表为空;+macOS 上声明根仍是 `R:\\media`,`[media.mounts] local = <真实目录>`。两条都在临时目录里跑,+平台用 `windows=` 参数注入,不看测试机自己是什么系统。+"""+from __future__ import annotations++import io+import sqlite3+import tempfile+import unittest+from contextlib import redirect_stdout+from pathlib import Path, PureWindowsPath++from peach import scan+from peach.migrations import upgrade++ROOT = Path(__file__).resolve().parents[1]+MIGRATIONS = ROOT / "migrations"+++class _ScanCase(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.root = Path(self.tmp.name).resolve()+ self.db = self.root / "ledger.db"+ upgrade(self.db, MIGRATIONS)+ self.media = self.root / "media"+ (self.media / "创作者" / "sub").mkdir(parents=True)+ (self.media / "创作者" / "sub" / "a.mp4").write_bytes(b"0" * 10)+ (self.media / "cover.jpg").write_bytes(b"1" * 3)+ (self.media / "notes.txt").write_bytes(b"2")++ def _paths(self):+ connection = sqlite3.connect(self.db)+ try:+ return dict(connection.execute(+ "SELECT path,medium FROM asset WHERE location='local'").fetchall())+ finally:+ connection.close()++ def _scan(self, root, **kwargs):+ output = io.StringIO()+ with redirect_stdout(output):+ result = scan.scan_location(self.db, "local", root, **kwargs)+ return result, output.getvalue()+++class WindowsShapeTests(_ScanCase):+ """Windows:声明根就是真实目录,路径原样进账本。"""++ def test_rows_are_written_under_the_declared_root(self):+ declared = {"local": str(self.media)}+ result, output = self._scan(str(self.media), declared_roots=declared, windows=True)+ self.assertEqual(result.files, 3)+ self.assertEqual(result.total_bytes, 14)+ self.assertEqual(result.gone, 0)+ self.assertIn("✓ local: 3 文件", output)+ rows = self._paths()+ self.assertEqual(rows[str(self.media / "创作者" / "sub" / "a.mp4")], "video")+ self.assertEqual(rows[str(self.media / "cover.jpg")], "image")+ self.assertEqual(rows[str(self.media / "notes.txt")], "other")+ # 读取侧:Windows 上账本路径就是本机路径,每一行都指向真实存在的文件。+ for path in rows:+ self.assertTrue(Path(path).is_file(), path)++ def test_a_subdirectory_of_the_declared_root_is_accepted(self):+ declared = {"local": str(self.media)}+ result, _ = self._scan(str(self.media / "创作者"), declared_roots=declared, windows=True)+ self.assertEqual(result.files, 1)++ def test_rescanning_refreshes_instead_of_duplicating_and_counts_the_gone(self):+ declared = {"local": str(self.media)}+ self._scan(str(self.media), declared_roots=declared, windows=True)+ (self.media / "notes.txt").unlink()+ (self.media / "cover.jpg").write_bytes(b"1" * 8)+ result, _ = self._scan(str(self.media), declared_roots=declared, windows=True)+ self.assertEqual(result.files, 2)+ self.assertEqual(len(self._paths()), 3, "没扫到的行留着,由资源同步对账处理")+ connection = sqlite3.connect(self.db)+ size = connection.execute("SELECT size FROM asset WHERE path=?",+ (str(self.media / "cover.jpg"),)).fetchone()[0]+ connection.close()+ self.assertEqual(size, 8)+++class PosixShapeTests(_ScanCase):+ """macOS:账本里写 `R:\\media\\...`,遍历的是挂载点,读取侧按挂载表翻回去。"""++ DECLARED = {"local": r"R:\media"}++ def test_rows_keep_the_ledger_shape_and_translate_back_to_real_files(self):+ mounts = {"local": self.media}+ result, _ = self._scan(r"R:\media", declared_roots=self.DECLARED, mounts=mounts,+ windows=False)+ self.assertEqual(result.files, 3)+ rows = self._paths()+ self.assertEqual(set(rows), {r"R:\media\创作者\sub\a.mp4", r"R:\media\cover.jpg",+ r"R:\media\notes.txt"})+ # 与 `platform.translate_ledger_path` 同一套算法:声明根后的层级接到挂载点上。+ for path in rows:+ tail = PureWindowsPath(path).relative_to(PureWindowsPath(r"R:\media")).parts+ self.assertTrue(self.media.joinpath(*tail).is_file(), path)++ def test_a_local_directory_is_converted_to_the_ledger_shape(self):+ mounts = {"local": str(self.media)}+ root = scan.ledger_root_for("local", self.media / "创作者",+ declared_roots=self.DECLARED, mounts=mounts, windows=False)+ self.assertEqual(root, r"R:\media\创作者")+ result, _ = self._scan(root, declared_roots=self.DECLARED, mounts=mounts, windows=False)+ self.assertEqual(set(self._paths()), {r"R:\media\创作者\sub\a.mp4"})++ def test_a_source_without_a_mount_is_refused_before_touching_the_ledger(self):+ with self.assertRaises(scan.ScanTargetError) as caught:+ self._scan(r"R:\media", declared_roots=self.DECLARED, mounts={}, windows=False)+ self.assertIn("media.mounts", str(caught.exception))+ self.assertEqual(self._paths(), {})++ def test_a_directory_outside_the_mount_is_refused(self):+ with self.assertRaises(scan.ScanTargetError) as caught:+ scan.ledger_root_for("local", "/somewhere/else", declared_roots=self.DECLARED,+ mounts={"local": str(self.media)}, windows=False)+ self.assertIn("挂载点", str(caught.exception))+++class ScanTargetTests(unittest.TestCase):+ """写入侧门槛:`location` 与扫描根必须对得上(ADR-0023 第 2 阶段),口径与脚本时期一致。"""++ DECLARED = {"local": r"R:\media", "115": "B:/"}++ def test_the_declared_root_and_its_subdirectories_are_accepted(self):+ for location, root in (("local", r"R:\media"), ("local", r"R:\media\创作者"),+ ("115", "B:/x")):+ self.assertIsNone(scan.check_scan_target(location, root,+ declared_roots=self.DECLARED))++ def test_a_root_belonging_to_another_source_is_refused(self):+ with self.assertRaises(scan.ScanTargetError) as caught:+ scan.check_scan_target("115", r"R:\media\创作者", declared_roots=self.DECLARED)+ self.assertIn("115", str(caught.exception))+ self.assertIn("local", str(caught.exception))++ def test_a_root_outside_every_declared_root_is_refused(self):+ with self.assertRaises(scan.ScanTargetError) as caught:+ scan.check_scan_target("local", r"R:\Resources\Intake", declared_roots=self.DECLARED)+ self.assertIn(r"R:\media", str(caught.exception))++ def test_an_undeclared_source_is_refused_and_lists_the_known_ones(self):+ with self.assertRaises(scan.ScanTargetError) as caught:+ scan.check_scan_target("nas", "N:/", declared_roots=self.DECLARED)+ self.assertIn("nas", str(caught.exception))+ self.assertIn("local", str(caught.exception))++ def test_medium_is_decided_by_extension(self):+ self.assertEqual([scan.medium_of(name) for name in+ ("a.MP4", "b.webp", "c.flac", "d.7z", "e.nfo")],+ ["video", "image", "audio", "archive", "other"])+++if __name__ == "__main__":+ unittest.main()