Peach: Local-first video metadata scraper and media manager.
fix: bound media classification and blocking work
longmeidaoa2f663c37f16
diff --git a/src/peach/api.py b/src/peach/api.pyindex 3155ce5b4..6847ada91 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -378,7 +378,7 @@ def create_app(if stream_sessions.is_cancelled(session):return Response(status_code=410, headers={"Cache-Control": "no-store"})try:- resolved = _hls_plan(id)+ resolved = await asyncio.to_thread(_hls_plan, id)if resolved is None:return JSONResponse({"error": "hls unavailable"}, status_code=404)_, source, plan = resolveddiff --git a/src/peach/media.py b/src/peach/media.pyindex db733c96e..d2c9b4747 100644--- a/src/peach/media.py+++ b/src/peach/media.py@@ -5,6 +5,7 @@ import osfrom dataclasses import dataclassfrom functools import lru_cachefrom pathlib import Path, PureWindowsPath+from time import monotonicfrom typing import Protocol, Sequencefrom .platform import (@@ -31,8 +32,13 @@ def normalized_path(path: Path | str) -> Path:return Path(os.path.abspath(os.fspath(candidate)))+CASE_MATCH_TTL_SECONDS = 5.0++@lru_cache(maxsize=512)-def _case_insensitive_match(parent_key: str, name_key: str) -> str | None:+def _cached_case_insensitive_match(+ parent_key: str, name_key: str, _ttl_bucket: int,+) -> str | None:"""同目录大小写不敏感匹配;只为大小写敏感的挂载层(CloudDrive/APFS)兜底。NTFS 上 `Path.is_file()` 已不区分大小写,正常情况不会走到这里。@@ -49,6 +55,12 @@ def _case_insensitive_match(parent_key: str, name_key: str) -> str | None:return None+def _case_insensitive_match(parent_key: str, name_key: str) -> str | None:+ """Cache scans briefly without pinning misses or stale names forever."""+ bucket = int(monotonic() // CASE_MATCH_TTL_SECONDS)+ return _cached_case_insensitive_match(parent_key, name_key, bucket)++def resolve_case_insensitive(path: Path | str) -> str:"""返回可直接打开的实际路径:原路径不存在时按大小写不敏感匹配同目录文件。"""# 批处理脚本直接调用本函数,不经过 FilesystemBackend;因此这里也必须先把账本的diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex 59d97286d..50483508d 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -1511,9 +1511,6 @@ def q_facets("GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT 60", scope_params)]# 标签要分层 —— 原来一锅端,结果「演员:一个ren」和「1080P」「足交」混在一起。# 三类分开:技术规格(画质/时长/画幅,筛选价值低)、内容维度(真正有用的)、演员(另立一栏)。- TECH = ("1080P", "720P", "4K", "2160P", "480P", "低画质", "高帧率",- "横屏", "竖屏",- "真人", "混合集", "身份待确认", "R-18")rows = [dict(r) for r in c.execute("SELECT e.canonical_name AS k, count(DISTINCT ae.asset_id) AS n ""FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "@@ -1522,8 +1519,8 @@ def q_facets("AND performer.normalized_name=e.normalized_name) ""GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT 400", scope_params)]out["tags"] = [dict(r, cat=tag_cat(r["k"])) for r in rows- if r["k"] not in TECH and r["k"] not in LENGTH_TAGS][:44]- out["tech"] = [r for r in rows if r["k"] in TECH][:14]+ if r["k"] not in TECH_TAGS and r["k"] not in LENGTH_TAGS][:44]+ out["tech"] = [r for r in rows if r["k"] in TECH_TAGS][:16]out["tagperformers"] = [dict(r) for r in c.execute("SELECT e.canonical_name AS k,count(DISTINCT ae.asset_id) AS n ""FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex dd4019f4c..558c6bf97 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -1,3 +1,4 @@+import asyncioimport csvimport importlib.utilimport json@@ -582,10 +583,13 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual((asset_id, index, session), (1, 1, "hls-test"))return segment+ real_to_thread = asyncio.to_threadwith patch.object(self.app.state.hls_service, "generate", new=generate):- response = await self.client.get(- "/stream/hls/1/1.ts?session=hls-test&t=secret",- )+ with patch("peach.api.asyncio.to_thread", wraps=real_to_thread) as offload:+ response = await self.client.get(+ "/stream/hls/1/1.ts?session=hls-test&t=secret",+ )+ offload.assert_awaited_once()self.assertEqual(response.status_code, 200)self.assertEqual(response.content, b"one segment")self.assertEqual(response.headers["content-type"], "video/mp2t")diff --git a/tests/test_media.py b/tests/test_media.pyindex 5e06d2b98..a3a260b48 100644--- a/tests/test_media.py+++ b/tests/test_media.py@@ -4,6 +4,7 @@ import unittestfrom pathlib import Pathfrom unittest.mock import patch+import peach.media as media_modulefrom peach.ffmpeg import FFmpegResolverfrom peach.media import (FilesystemBackend, MediaEngine, StashAdapter, normalized_path, remap_managed_path,@@ -145,6 +146,21 @@ class MediaEngineTests(unittest.TestCase):self.assertTrue(opened.is_file())self.assertTrue(opened.parent.samefile(root))+ def test_case_insensitive_miss_expires_after_the_short_ttl(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ with patch("peach.media.monotonic", return_value=0):+ self.assertIsNone(+ media_module._case_insensitive_match(str(root), "abw-118.mp4")+ )+ real = root / "ABW-118.MP4"+ real.write_bytes(b"test")+ with patch("peach.media.monotonic", return_value=6):+ self.assertEqual(+ media_module._case_insensitive_match(str(root), "abw-118.mp4"),+ real.name,+ )+def test_remote_mp4_defaults_to_range_and_only_segments_on_request(self):"""默认 HLS 会让 HEVC 静默黑屏:`-c copy` 把 HEVC 装进 MPEG-TS,而 Chromium 的MSE 不支持 TS 里的 HEVC(实测 `video/mp2t; codecs="hvc1…"` 为 false),数据进得了diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 21d7070af..bb92c0d5f 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -249,6 +249,27 @@ class WebDataTests(unittest.TestCase):self.assertTrue(first_page["has_more"])self.assertNotEqual(first_page["items"][0]["k"], second_page["items"][0]["k"])+ def test_every_technical_tag_uses_the_same_facets_classification(self):+ connection = sqlite3.connect(self.db_path)+ for entity_id, tag in enumerate(("2K", "有码", "无码"), start=201):+ connection.execute(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name) VALUES(?, 'tag', ?, ?)",+ (entity_id, tag, tag.lower()),+ )+ connection.execute(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "+ "VALUES(1,?,'tag','test',1.0)",+ (entity_id,),+ )+ connection.commit()+ connection.close()++ facets = rm_web.q_facets(self.contract)+ tech = {row["k"] for row in facets["tech"]}+ content = {row["k"] for row in facets["tags"]}+ self.assertTrue({"2K", "有码", "无码"} <= tech)+ self.assertTrue({"2K", "有码", "无码"}.isdisjoint(content))+def test_activity_accumulates_real_play_time_and_max_position(self):first = rm_web.w_activity(self.contract, {"id": 1, "position": 50, "duration": 100, "delta": 12, "seeks": 2,