Skip to content

armgit / peach

Public Imported from GitHub
0

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

perf(api): 目录索引按目录前缀复用路径链,媒体工具探测按文件记住

longmeidaod2231eeff5c1
diff --git a/src/peach/ffmpeg.py b/src/peach/ffmpeg.py
index e32fe7e45..c459594ef 100644
--- a/src/peach/ffmpeg.py
+++ b/src/peach/ffmpeg.py
@@ -21,12 +21,33 @@ def bundled_tools_root() -> Path:
return executable.parent / "tools"
+#: 探测成功的结果按可执行文件的路径、修改时间与字节数记住。系统诊断页每开一次要起三个
+#: 子进程,合计三四百毫秒,而同一个文件的版本与解码器不会变;换了文件这三样至少变一样。
+_PROBED: dict[tuple, dict] = {}
+
+
def binary_diagnostics(choice: BinaryChoice | None, *, decoders=False) -> dict:
- """检查实际工具版本与 AV1 软件解码器;路径存在和可执行分别报告。"""
+ """检查实际工具版本与 AV1 软件解码器;路径存在和可执行分别报告。
+
+ 失败不记:超时、拒绝执行这类可能是一时的,下一次照样重探。"""
facts = {'available': choice is not None, 'source': choice.source if choice else None,
'path': str(choice.path) if choice else None, 'usable': False}
if choice is None:
return facts
+ try:
+ stat = choice.path.stat()
+ key = (str(choice.path), choice.source, stat.st_mtime_ns, stat.st_size, decoders)
+ except OSError:
+ key = None
+ if key in _PROBED:
+ return dict(_PROBED[key])
+ facts = _probe(choice, facts, decoders)
+ if key is not None and facts['usable']:
+ _PROBED[key] = dict(facts)
+ return facts
+
+
+def _probe(choice: BinaryChoice, facts: dict, decoders: bool) -> dict:
try:
for option in ('-version', '-decoders') if decoders else ('-version',):
result = subprocess.run([str(choice.path), '-hide_banner', option], capture_output=True,
diff --git a/src/peach/media_folders.py b/src/peach/media_folders.py
index 03a0b8b77..fc57de131 100644
--- a/src/peach/media_folders.py
+++ b/src/peach/media_folders.py
@@ -53,14 +53,11 @@ def directory_index(connection, config, *, locations: str = '', library: str = '
node = add(location, root, None, folder_id(location, root))
node.update(media_libraries.media_identity.ownership(config, root))
node['name'] = getattr(config, 'library_names', {}).get(root) or node['name']
- rows = connection.execute(
- "SELECT location,path,medium FROM asset WHERE path IS NOT NULL AND path<>'' "
- "AND COALESCE(disposal,'') NOT IN ('trash','vanished') ORDER BY id")
- for location, path, medium in rows:
+ def chain_for(location, path):
target = PureWindowsPath(path)
matches = [(loc, root) for loc, root in declared if loc == location and within(str(target), root)]
if not matches:
- continue
+ return None
_, root = max(matches, key=lambda item: len(PureWindowsPath(item[1]).parts))
root_key = folder_id(location, root)
tail = target.parent.relative_to(PureWindowsPath(root)).parts
@@ -70,6 +67,28 @@ def directory_index(connection, config, *, locations: str = '', library: str = '
current /= part
chain[-1]['has_children'] = True
chain.append(add(location, str(current), chain[-1]['id'], root_key))
+ return chain
+
+ # 同一目录下的文件走出来的是同一条链。七八万行逐行构造路径对象要好几秒,按目录前缀
+ # 记下第一条算出的链,其余文件只累加计数。末段为空或 `.`、没有分隔符、UNC 形态的
+ # 前缀不保证同前缀同父目录,逐行照算。
+ chains: dict[tuple[str, str], list | None] = {}
+ rows = connection.execute(
+ "SELECT location,path,medium FROM asset WHERE path IS NOT NULL AND path<>'' "
+ "AND COALESCE(disposal,'') NOT IN ('trash','vanished') ORDER BY id")
+ for location, path, medium in rows:
+ cut = max(path.rfind('\\'), path.rfind('/'))
+ prefix = path[:cut]
+ group = ((location, prefix) if cut > 0 and path[cut + 1:] not in ('', '.')
+ and prefix[:2].replace('/', '\\') != '\\\\' else None)
+ if group is None:
+ chain = chain_for(location, path)
+ elif group in chains:
+ chain = chains[group]
+ else:
+ chain = chains[group] = chain_for(location, path)
+ if chain is None:
+ continue
for node in chain:
node['files'] += 1
node['videos'] += medium == 'video'
diff --git a/tests/test_media.py b/tests/test_media.py
index e4b877329..8254d1a61 100644
--- a/tests/test_media.py
+++ b/tests/test_media.py
@@ -25,6 +25,24 @@ class MediaEngineTests(unittest.TestCase):
self.assertTrue(result['usable'])
self.assertEqual(result['av1_software'], available)
+ def test_tool_diagnostics_probe_each_binary_file_once_until_it_changes(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ binary = Path(tmp).resolve() / 'ffmpeg.exe'
+ binary.write_bytes(b'one')
+ choice = BinaryChoice(binary, 'test')
+ version = subprocess.CompletedProcess([], 0, b'ffmpeg version test\n', b'')
+ with patch('peach.ffmpeg.subprocess.run', return_value=version) as run:
+ self.assertTrue(binary_diagnostics(choice)['usable'])
+ self.assertTrue(binary_diagnostics(choice)['usable'])
+ self.assertEqual(run.call_count, 1)
+ binary.write_bytes(b'upgraded')
+ self.assertTrue(binary_diagnostics(choice)['usable'])
+ self.assertEqual(run.call_count, 2)
+ with patch('peach.ffmpeg.subprocess.run', side_effect=subprocess.TimeoutExpired('ffmpeg', 5)) as run:
+ self.assertFalse(binary_diagnostics(BinaryChoice(binary, 'other'))['usable'])
+ self.assertFalse(binary_diagnostics(BinaryChoice(binary, 'other'))['usable'])
+ self.assertEqual(run.call_count, 2)
+
def test_tool_diagnostics_reports_execution_failure(self):
with patch('peach.ffmpeg.subprocess.run', side_effect=subprocess.TimeoutExpired('ffmpeg', 5)):
result = binary_diagnostics(BinaryChoice(Path('ffmpeg'), 'test'), decoders=True)
diff --git a/tests/test_media_folders.py b/tests/test_media_folders.py
index e53607405..feab8f7b2 100644
--- a/tests/test_media_folders.py
+++ b/tests/test_media_folders.py
@@ -64,6 +64,18 @@ class MediaFolderTests(unittest.TestCase):
self.assertEqual(len(self.read(loc='115')['roots']), 1)
self.assertEqual(self.read(library='不存在')['roots'], [])
+ def test_counts_follow_the_parent_directory_whatever_the_path_spelling(self):
+ """同一目录的不同写法计到同一个节点;以分隔符结尾的路径计到上一层,不跟同前缀的文件走。"""
+ spellings = ['R:/Media/精选/作者甲/e.mp4', 'R:\\Media\\精选\\\\作者甲\\f.mp4',
+ 'r:\\media\\精选\\作者甲\\g.mp4', 'R:\\Media\\精选\\作者甲\\']
+ with self.contract.write_transaction() as connection:
+ connection.executemany("INSERT INTO asset(location,path,name,medium) VALUES('local',?,'x','video')",
+ [(path,) for path in spellings])
+ with self.contract.read_connection() as connection:
+ index = media_folders.directory_index(connection, self.config)
+ self.assertEqual(index[self.key()]['files'], 5)
+ self.assertEqual(index[self.key('R:\\Media\\精选')]['files'], 7)
+
def test_path_scope_is_case_insensitive_and_observes_component_boundary(self):
with self.contract.read_connection() as connection:
clause, args = media_folders.path_predicate('local', 'r:\\media\\精选\\作者甲')