Peach: Local-first video metadata scraper and media manager.
feat(library): 扫描与采集可以分开跑
longmeidaoe34bff12cac9
diff --git a/frontend/src/islands/library-processing.tsx b/frontend/src/islands/library-processing.tsxindex ae24cfe71..2f94df115 100644--- a/frontend/src/islands/library-processing.tsx+++ b/frontend/src/islands/library-processing.tsx@@ -106,14 +106,18 @@ export function LibraryProcessing({ data, error, toast, onComplete, mode, monito<section class="cleanupfieldset" data-geist-fieldset aria-labelledby="cleanupScrapingTitle"><div class="geist-fieldset-content library-processing"><div dangerouslySetInnerHTML={{ __html: fieldsetTitle('cleanupScrapingTitle', '扫描与采集') }} />- <p>扫描媒体文件夹,导入已有资料,采集缺失信息。</p>+ <p>扫描媒体文件夹,导入已有资料,采集缺失信息。两段也可以分开跑:新盘刚接上时先只扫描,几万个文件登记完就能用;采集被网络拖住时只重跑采集,不必再扫一遍磁盘。</p>{state.status === 'running' && <div aria-live="polite" dangerouslySetInnerHTML={{ __html:jobActivityHtml(state.total ? `${currentLine(state)} · ${state.checked || 0} / ${state.total} 个视频` : currentLine(state), state.checked, state.total) }} />}</div><footer class="geist-fieldset-footer" data-geist-fieldset-footer><LinkButton href="/scraping">采集来源</LinkButton>{!!state.candidates && <LinkButton href="/review">复核资料</LinkButton>}- {(state.status !== 'failed' || !retryable) && <button ref={button} type="button" class="geist-button primary" onClick={start}>扫描并补全资料</button>}+ {(state.status !== 'failed' || !retryable) && <div class="board-button-group" role="group" aria-label="扫描与采集">+ <button type="button" class="geist-button" onClick={()=>void submit({stage:'scan'})}>只扫描</button>+ <button type="button" class="geist-button" onClick={()=>void submit({stage:'collect'})}>只采集</button>+ <button ref={button} type="button" class="geist-button primary" onClick={start}>扫描并补全资料</button>+ </div>}</footer></section><div class="library-processing-outcome" aria-live="polite">diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex bcb34c096..ea1bed05e 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -33,6 +33,10 @@ LABELS = dict(title='标题', original_title='原标题', performers='演员', s#: 状态里最多保留这么多条问题;完整问题写在任务专属 JSONL 里,接口分页读取。ISSUE_PREVIEW_LIMIT = 20+#: 这条链能分开跑的两段,和一次跑完。名字进接口也进页面,改这里就是改契约。+SCAN_STAGE, COLLECT_STAGE, ALL_STAGES = 'scan', 'collect', 'all'+STAGES = (ALL_STAGES, SCAN_STAGE, COLLECT_STAGE)+#: 没有动作截止时间的阶段(本地读取)超过这么久没有心跳就在页面上预警。STALL_AFTER_SECONDS = 120.0@@ -194,11 +198,16 @@ def _fields(payload, genre_decisions=None):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):+ retry_ids=None, active=lambda: True, stage=ALL_STAGES):"""登记文件与确定的番号,外部资料保留为可复核候选。`retry_ids` 为 `None` 时处理整个馆藏;给定时只处理这些项目(上一任务记录的可重试失败),不重新扫描来源目录,已有候选与封面照常复用。++ `stage` 把这条链分两段跑:`scan` 只走一遍来源目录把文件登记进馆藏,`collect`+ 跳过那一遍、直接读本地资料并采集缺失的。新盘刚接上时要的是前者——几万个+ 文件登记完就能用,不必等采集;采集被网络拖住时要的是后者,重跑不必再扫一遍+ 磁盘。缺省两段都跑。"""def require_writer():if config.replication.enabled:@@ -285,10 +294,16 @@ def process_library(config, db_path, candidate_root, cover_root, *, location='coissue(None, f'{source} 来源离线', action='reading_local')continueonline_roots.append(translate_ledger_path(root).resolve())- if not retrying:+ if not retrying and stage != COLLECT_STAGE:result = scan_location(db_path, source, root, declared_roots=config.locations,mounts=mounts, report=lambda line: update(stage='扫描文件'))state['scanned'] += result.files+ if stage == SCAN_STAGE:+ update(status='failed' if state['issue_count'] else 'complete',+ stage='处理结束', completed_at=time.time(),+ error=f"{state['issue_count']} 项需要处理,请查看详情并重试。"+ if state['issue_count'] else '')+ return stateif retrying:placeholders = ','.join('?' * len(chosen_ids))query = (f"SELECT * FROM asset WHERE id IN ({placeholders}) AND medium='video' "diff --git a/src/peach/web_library_processing.py b/src/peach/web_library_processing.pyindex 8327b014a..d7caa56ff 100644--- a/src/peach/web_library_processing.py+++ b/src/peach/web_library_processing.py@@ -2,7 +2,8 @@import jsonfrom . import settings_file-from .library_processing import decorate, issues_path, process_library, snapshot+from .library_processing import (ALL_STAGES, COLLECT_STAGE, SCAN_STAGE, STAGES,+ decorate, issues_path, process_library, snapshot)def _current(contract):@@ -75,16 +76,23 @@ def w_library_processing(contract, body):if previous.get('status') == 'running':return previousretry_ids = _retry_ids(previous, body)+ stage = str((body or {}).get('stage') or ALL_STAGES)+ if stage not in STAGES:+ raise ValueError('处理阶段无效')if retry_ids is not None and not retry_ids:return previousdef work(job_id):try:result = process_library(config, contract.db_path, contract.candidate_root, contract.cover_root,- job_id=job_id, retry_ids=retry_ids,+ job_id=job_id, retry_ids=retry_ids, stage=stage,active=lambda: (contract.library_processing_job.snapshot() or {}).get('job_id') == job_id,report=lambda state: contract.library_processing_job.update(job_id, **{key: value for key, value in state.items() if key != 'job_id'}))contract.library_processing_job.update(job_id, **{key: value for key, value in result.items() if key != 'job_id'})finally:contract.cache_bust()- return contract.library_processing_job.start(work, restart=True, initial={'stage': '准备处理'})+ # 起步那行字按这一趟真正要做的事写:点了「只扫描」却看到「读取本地资料」,+ # 人会以为点错了。+ labels = {ALL_STAGES: '准备处理', SCAN_STAGE: '准备扫描文件', COLLECT_STAGE: '准备采集资料'}+ return contract.library_processing_job.start(+ work, restart=True, initial={'stage': labels[stage], 'requested_stage': stage})diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.pyindex a24aaf633..b5246689c 100644--- a/tests/test_metadata_library.py+++ b/tests/test_metadata_library.py@@ -6,6 +6,7 @@ import tempfileimport timeimport unittestfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import Mock, patchfrom contextlib import closing@@ -402,6 +403,81 @@ class LibraryWatchdogTests(unittest.TestCase):self.assertEqual(retried['checked'], 1)self.assertEqual(retried['status'], 'complete')+ def test_scanning_alone_registers_the_files_and_asks_no_source(self):+ """只扫描那一段登记完文件就收工,不读本地资料也不联网。++ 新盘刚接上时要的就是这个:几万个文件进了馆藏就能用,采集可以留到夜里。+ """+ media = self.root / 'media'+ media.mkdir()+ (media / 'ABW-203.mp4').write_bytes(b'video')+ db = fresh_ledger(self.root)+ provider = self._provider()+ state = process_library(self._config(media), db, self.root / 'generated',+ self.root / 'covers', stage='scan',+ provider_factory=lambda: provider)+ self.assertEqual(state['status'], 'complete')+ self.assertEqual(state['scanned'], 1)+ self.assertEqual(state['checked'], 0)+ self.assertEqual(state['candidates'], 0)+ provider.query.assert_not_called()+ with closing(sqlite3.connect(db)) as connection:+ self.assertEqual(connection.execute('SELECT count(*) FROM asset').fetchone()[0], 1,+ "文件要进馆藏,只是没往下走采集")++ def test_collecting_alone_walks_the_library_without_touching_the_disk_again(self):+ """只采集那一段不再扫一遍来源目录,处理的仍是整个馆藏。++ 采集被网络拖住时重跑的就是它:几万个文件的目录遍历没有必要再走一趟。+ """+ media = self.root / 'media'+ media.mkdir()+ (media / 'ABW-204.mp4').write_bytes(b'video')+ db = fresh_ledger(self.root)+ config = self._config(media)+ provider = self._provider()+ process_library(config, db, self.root / 'generated', self.root / 'covers',+ stage='scan', provider_factory=lambda: provider)+ with patch('peach.library_processing.scan_location') as scan:+ state = process_library(config, db, self.root / 'generated', self.root / 'covers',+ stage='collect', provider_factory=lambda: provider)+ scan.assert_not_called()+ self.assertEqual(state['status'], 'complete')+ self.assertEqual(state['total'], 1)+ self.assertEqual(state['checked'], 1)++ def test_the_stage_asked_for_is_the_stage_that_runs(self):+ """页面点哪一段就跑哪一段,不认识的段数拒绝掉。++ 段名要一路传到管线里。只拿它换一句提示文字的话,按钮看着分了工、跑起来+ 全是同一件事,而且页面上看不出区别。+ """+ from peach.web_library_processing import w_library_processing+ contract = SimpleNamespace(+ db_path=Path(self.root / 'database' / 'ledger.db'),+ candidate_root=self.root / 'generated', cover_root=self.root / 'covers',+ cache_bust=lambda: None,+ library_processing_job=SimpleNamespace(+ snapshot=lambda: None,+ start=lambda work, restart, initial: (work('job'), initial)[1],+ update=lambda job_id, **values: None))+ media = self.root / 'media'+ media.mkdir()+ (self.root / 'database').mkdir(exist_ok=True)+ fresh_ledger(self.root / 'database')+ config = self._config(media)+ with patch('peach.web_library_processing.settings_file.active', return_value=config), \+ patch('peach.web_library_processing.process_library') as run:+ run.return_value = {'job_id': 'job', 'status': 'complete'}+ initial = w_library_processing(contract, {'stage': 'collect'})+ self.assertEqual(run.call_args.kwargs['stage'], 'collect')+ self.assertEqual(initial['requested_stage'], 'collect')+ self.assertEqual(initial['stage'], '准备采集资料')+ w_library_processing(contract, {})+ self.assertEqual(run.call_args.kwargs['stage'], 'all')+ with self.assertRaises(ValueError):+ w_library_processing(contract, {'stage': 'thumbnails'})+def test_retry_request_accepts_only_the_previous_failure_set(self):from peach.web_library_processing import _retry_idsprevious = {'job_id': 'one', 'retryable_asset_ids': [130, 131]}diff --git a/web/dist/peach-ui.js b/web/dist/peach-ui.jsindex 4b2e8a136..6dc477208 100644--- a/web/dist/peach-ui.js+++ b/web/dist/peach-ui.js@@ -751,7 +751,7 @@ function bt({ data: e, error: t, toast: n, onComplete: r, mode: i, monitor: a, pclass: "geist-fieldset-content library-processing",children: [/* @__PURE__ */ q("div", { dangerouslySetInnerHTML: { __html: p("cleanupScrapingTitle", "扫描与采集") } }),- /* @__PURE__ */ q("p", { children: "扫描媒体文件夹,导入已有资料,采集缺失信息。" }),+ /* @__PURE__ */ q("p", { children: "扫描媒体文件夹,导入已有资料,采集缺失信息。两段也可以分开跑:新盘刚接上时先只扫描,几万个文件登记完就能用;采集被网络拖住时只重跑采集,不必再扫一遍磁盘。" }),s.status === "running" && /* @__PURE__ */ q("div", {"aria-live": "polite",dangerouslySetInnerHTML: { __html: ft(s.total ? `${yt(s)} · ${s.checked || 0} / ${s.total} 个视频` : yt(s), s.checked, s.total) }@@ -769,12 +769,31 @@ function bt({ data: e, error: t, toast: n, onComplete: r, mode: i, monitor: a, phref: "/review",children: "复核资料"}),- (s.status !== "failed" || !k) && /* @__PURE__ */ q("button", {- ref: S,- type: "button",- class: "geist-button primary",- onClick: E,- children: "扫描并补全资料"+ (s.status !== "failed" || !k) && /* @__PURE__ */ q("div", {+ class: "board-button-group",+ role: "group",+ "aria-label": "扫描与采集",+ children: [+ /* @__PURE__ */ q("button", {+ type: "button",+ class: "geist-button",+ onClick: () => void T({ stage: "scan" }),+ children: "只扫描"+ }),+ /* @__PURE__ */ q("button", {+ type: "button",+ class: "geist-button",+ onClick: () => void T({ stage: "collect" }),+ children: "只采集"+ }),+ /* @__PURE__ */ q("button", {+ ref: S,+ type: "button",+ class: "geist-button primary",+ onClick: E,+ children: "扫描并补全资料"+ })+ ]})]})]@@ -2509,10 +2528,10 @@ function Gn() {viewBox: "0 0 24 24","aria-hidden": "true",children: /* @__PURE__ */ q("use", { href: "#i-chevron-right" })- }), "CloudDrive 速度与缓存建议"] }),+ }), "CloudDrive 缓存建议"] }),/* @__PURE__ */ q("p", {class: "confighelp",- children: "看缓存放在哪块硬盘上,照那一行填。表里是起步值,先保证播放不卡,再拿同一个视频比较打开速度、拖动和流量;填得越大不一定越快。"+ children: "看缓存放在哪块硬盘上,照那一行填。这是起步值,填得越大不一定越快。"}),/* @__PURE__ */ q("div", {class: "cloudguide-tablewrap",@@ -2548,17 +2567,12 @@ function Gn() {}),/* @__PURE__ */ q("ul", {class: "cloudguide-notes",- children: [- /* @__PURE__ */ q("li", { children: "缓存上限和清理方式填在 CloudDrive「设置」里,清理方式选 LRU。上限不要填 0,系统盘至少留 40 GiB。" }),- /* @__PURE__ */ q("li", { children: "读取长度和下载线程填在每个网盘各自的下载设置里,线程都从 2 开始。看高码率视频还是缓冲就试 512 / 256 KB,打开速度、拖动和流量都没改善就调回去。" }),- /* @__PURE__ */ q("li", { children: "Buffer Cache 占内存,磁盘缓存和文件夹缓存占硬盘,三处是分开的设置,改一个管不住另外两个。" }),- /* @__PURE__ */ q("li", { children: "填完重新打开 CloudDrive 的设置页确认存住了,再看硬盘实际少了多少。播放期间先暂停批量抽帧、关掉不用的播放页。" })- ]+ children: [/* @__PURE__ */ q("li", { children: "缓存上限和清理方式填在 CloudDrive「设置」里,清理方式选 LRU。上限不要填 0,系统盘至少留 40 GiB;填完重开设置页确认存住了。" }), /* @__PURE__ */ q("li", { children: "读取长度和下载线程填在每个网盘各自的下载设置里,线程都从 2 开始。" })]}),/* @__PURE__ */ q("p", {class: "confighelp",children: [- "三处缓存分别管什么、码率和速度怎么换算、线程上限与直链代理怎么取舍,以及这些起步值的来源,都在",+ "三处缓存分别管什么、这几个值怎么往上调、码率和速度怎么换算、线程上限与直链代理怎么取舍,以及这些起步值的来源,都在",/* @__PURE__ */ q("a", {class: "externallink",href: "https://github.com/longmeidao/peach/blob/master/docs/CLOUDDRIVE.md",