Skip to content

armgit / peach

Public Imported from GitHub
0

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

refactor(codes): 番号归一化三份实现合并到 catalog_rules

longmeidao053aed52ca0d
diff --git a/scripts/fetch_jav_covers.py b/scripts/fetch_jav_covers.py
index 180390060..0a3589fb0 100644
--- a/scripts/fetch_jav_covers.py
+++ b/scripts/fetch_jav_covers.py
@@ -56,7 +56,7 @@ from peach.config import COVER_DIR, DATABASE_PATH, GENERATED_DIR, SOURCES_DIR
from peach.http import HttpRequest, HttpTransport, HttpxTransport
from peach.jobs import DiskGuard, JobPolicyError
from peach.platform import system_volume
-from peach.web_contract import is_jav_code
+from peach.catalog_rules import is_jav_code, normalise_code_key
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")
@@ -180,22 +180,9 @@ def _fetch(transport: HttpTransport, url: str, *, referer: str,
return response.body
-def normalise_code(code: str) -> str:
- """`abw232` / `ABW-0232` 一律归一成 `ABW-232`,与 scrape_codes 同口径。"""
- value = (code or "").upper().replace("_", "-").replace(" ", "-").strip()
- if value.startswith("FC2"):
- digits = re.search(r"(\d{5,})", value)
- return f"FC2-PPV-{digits.group(1)}" if digits else value
- shape = re.match(r"^(\d{3})?([A-Z]+)-?(\d+)$", value)
- if not shape:
- return value
- prefix = shape.group(1) or ""
- return f"{prefix}{shape.group(2)}-{int(shape.group(3)):03d}"
-
-
def code_variants(code: str) -> list[str]:
"""素人系番号带三位厂牌前缀,去掉才查得到:`278GYAN-017` -> `GYAN-017`。"""
- value = normalise_code(code)
+ value = normalise_code_key(code)
out = [value]
stripped = re.sub(r"^\d{3}(?=[A-Z])", "", value)
if stripped != value:
@@ -312,7 +299,7 @@ def logged_success_evidence(
) -> tuple[Candidate, tuple[int, int]] | None:
"""复用历史精确 URL 与已量尺寸;DUGA 等无需重复探同一张图。"""
for row in reversed(rows):
- if (normalise_code(str(row.get("code") or "")) == code
+ if (normalise_code_key(str(row.get("code") or "")) == code
and row.get("result") == "取得"
and isinstance(row.get("url"), str)
and IMAGE_URL.fullmatch(str(row["url"]))):
@@ -417,11 +404,11 @@ def prestige_images(transport: HttpTransport, code: str) -> list[Candidate]:
source = hit.get("_source") if isinstance(hit, dict) else None
if not isinstance(source, dict):
continue
- item_id = normalise_code(str(source.get("deliveryItemId") or ""))
+ item_id = normalise_code_key(str(source.get("deliveryItemId") or ""))
uuid = str(source.get("productUuid") or "").strip()
if not uuid:
continue
- if item_id == normalise_code(code):
+ if item_id == normalise_code_key(code):
exact.append(uuid)
elif str(source.get("deliveryItemId") or "").upper().endswith(code.upper()):
fallback.append(uuid)
@@ -568,7 +555,7 @@ def restore_logged_successes(transport: HttpTransport, log: Path, root: Path,
for index, row in enumerate(successes, 1):
if guard is not None:
guard.check()
- code = normalise_code(str(row["code"]))
+ code = normalise_code_key(str(row["code"]))
target = root / f"{code}.jpg"
if target.is_file():
skipped += 1
@@ -618,7 +605,7 @@ def pending(database: Path, root: Path, only_shaped: bool,
connection.close()
result = []
for code, _count in rows:
- # 判形态必须看原值。`normalise_code` 会补上分隔符,把 `RAIKUN325`
+ # 判形态必须看原值。`normalise_code_key` 会补上分隔符,把 `RAIKUN325`
# (myfans 账号名,241 个文件)改写成 `RAIKUN-325` 并通过形态检查,
# 于是队列里全是查不到的账号名。判据与 web_contract 共用一份实现。
if only_shaped and not is_jav_code(str(code)):
@@ -627,7 +614,7 @@ def pending(database: Path, root: Path, only_shaped: bool,
# 同一批来源。默认跳过 400 个必然落空的请求;`--all-codes` 仍可强制尝试。
if only_shaped and str(code).upper().startswith("FC2"):
continue
- key = normalise_code(str(code))
+ key = normalise_code_key(str(code))
target = root / f"{key}.jpg"
if existing:
if not target.is_file():
@@ -656,7 +643,7 @@ def audit_state(database: Path, root: Path, log: Path) -> dict[str, object]:
finally:
connection.close()
codes = {
- normalise_code(code) for code in raw_codes
+ normalise_code_key(code) for code in raw_codes
if is_jav_code(code) and not code.upper().startswith("FC2")
}
dimensions: dict[str, tuple[int, int]] = {}
diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.py
index 9ad7fcbbc..3a5d29c6b 100644
--- a/scripts/scrape_codes.py
+++ b/scripts/scrape_codes.py
@@ -19,6 +19,7 @@ import time
from datetime import datetime, timezone
from pathlib import Path
+from peach.catalog_rules import normalise_code_key
from peach.config import DATABASE_PATH, GENERATED_DIR, LOG_DIR, SOURCES_DIR, STATE_DIR
from peach.jobs import DiskGuard, JobPolicyError
from peach.metadata import (
@@ -102,19 +103,6 @@ def close_log() -> None:
_logf = None
-def normalise(code: str) -> str:
- """Normalize only the movie-code spellings Peach explicitly accepts."""
- value = str(code or "").upper().replace("_", "-").replace(" ", "-").strip()
- if value.startswith("FC2"):
- digits = re.search(r"(\d{5,})", value)
- return f"FC2-PPV-{digits.group(1)}" if digits else value
- shape = re.match(r"^(\d{3})?([A-Z]+)-?(\d+)$", value)
- if not shape:
- return value
- digits = str(int(shape.group(3))).zfill(3)
- return f"{shape.group(1) or ''}{shape.group(2)}-{digits}"
-
-
def _is_explicit_code(code: str) -> bool:
value = str(code or "").upper().strip()
if value.startswith("FC2"):
@@ -250,7 +238,7 @@ def _requested_codes(path: Path) -> list[str]:
value = raw.split("#", 1)[0].strip()
if not value:
continue
- query = normalise(value)
+ query = normalise_code_key(value)
if query not in seen:
seen.add(query)
requested.append(query)
@@ -263,7 +251,7 @@ def _select_requested_codes(
requested = _requested_codes(path)
available: dict[str, tuple[str, float, int]] = {}
for code, size_gb, videos in codes:
- query = normalise(code)
+ query = normalise_code_key(code)
previous = available.get(query)
if previous is None:
available[query] = (code, size_gb, videos)
@@ -376,7 +364,7 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None
stopped = error
log(f"[stop] {error}")
break
- query = normalise(code)
+ query = normalise_code_key(code)
by_field: dict[str, list[dict]] = {}
fetched_at = datetime.now(timezone.utc).isoformat()
for source in sources:
diff --git a/tests/test_jav_covers.py b/tests/test_jav_covers.py
index 0a784c22e..a409546f0 100644
--- a/tests/test_jav_covers.py
+++ b/tests/test_jav_covers.py
@@ -128,11 +128,13 @@ class CodeShapeTests(unittest.TestCase):
self.assertEqual(covers.code_variants("ABW-232"), ["ABW-232"])
def test_codes_are_normalised_to_three_digits(self):
- self.assertEqual(covers.normalise_code("abw232"), "ABW-232")
- self.assertEqual(covers.normalise_code("ABW-0232"), "ABW-232")
+ # 归一化本体收进了 catalog_rules,脚本 import 它;这里验的是脚本用的
+ # 确实是那一份,而不是又抄了一个同名函数。
+ self.assertEqual(covers.normalise_code_key("abw232"), "ABW-232")
+ self.assertEqual(covers.normalise_code_key("ABW-0232"), "ABW-232")
def test_amateur_prefix_survives_normalisation(self):
- self.assertEqual(covers.normalise_code("278gyan17"), "278GYAN-017")
+ self.assertEqual(covers.normalise_code_key("278gyan17"), "278GYAN-017")
class ContentIdTests(unittest.TestCase):
diff --git a/tests/test_module_layering.py b/tests/test_module_layering.py
index 41d507c6e..deaf1aac5 100644
--- a/tests/test_module_layering.py
+++ b/tests/test_module_layering.py
@@ -37,6 +37,59 @@ def _local_imports(path: pathlib.Path) -> set[str]:
return names
+#: 项目根:`src/peach` 的上两级。脚本和源码要一起扫。
+PROJECT_ROOT = SOURCE_ROOT.parent.parent
+
+
+def _python_sources() -> list[pathlib.Path]:
+ return sorted(SOURCE_ROOT.glob("*.py")) + sorted((PROJECT_ROOT / "scripts").glob("*.py"))
+
+
+class SharedRuleTests(unittest.TestCase):
+ """领域规则只许有一份实现。
+
+ 番号归一化曾经有三份:`catalog_rules.normalise_code_key`、
+ `scripts/fetch_jav_covers.normalise_code`、`scripts/scrape_codes.normalise`。
+ 三份逐字相同,靠一句「与 scrape_codes 同口径」的注释维持一致——注释不是门槛。
+
+ 番号既是身份判定也是封面缓存键:三份一旦漂移,同一部片会解析出两个键,
+ 封面缓存静默失配,而两边的数都「对」,只是口径不同。
+ """
+
+ #: 归一化实现的指纹。`FC2-PPV-` 的拼装和番号形态的正则,凑齐就是又抄了一份。
+ FINGERPRINTS = ('f"FC2-PPV-', r'([A-Z]+)-?(\d+)$')
+
+ def test_release_code_normalisation_exists_once(self):
+ offenders = []
+ for path in _python_sources():
+ if path.name == "catalog_rules.py":
+ continue
+ text = path.read_text(encoding="utf-8")
+ if all(mark in text for mark in self.FINGERPRINTS):
+ offenders.append(path.name)
+ self.assertEqual(
+ offenders, [],
+ "番号归一化又被抄了一份,请改 import catalog_rules.normalise_code_key",
+ )
+
+ def test_pure_rules_are_imported_from_the_policy_module_not_through_web(self):
+ """纯规则要直接从 `catalog_rules` 取,不要借道 web 层的再导出。
+
+ `web_contract` 把 `is_jav_code` 再导出了一遍,于是脚本写成
+ `from peach.web_contract import is_jav_code`——为一条纯规则拉起整个 web 层,
+ 读代码的人还会以为这条规则属于 web。
+ """
+ offenders = []
+ for path in sorted((PROJECT_ROOT / "scripts").glob("*.py")):
+ text = path.read_text(encoding="utf-8")
+ for rule in ("is_jav_code", "normalise_code_key", "LENGTH_TAGS"):
+ if f"from peach.web_contract import" in text and rule in text.split(
+ "from peach.web_contract import", 1)[1].split("\n", 1)[0]:
+ offenders.append(f"{path.name} → web_contract.{rule}")
+ self.assertEqual(offenders, [],
+ "纯规则请直接从 peach.catalog_rules 取")
+
+
class LayeringTests(unittest.TestCase):
def test_only_web_modules_and_the_composition_root_import_the_web_layer(self):
offenders = []
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 9cc968c9c..df28d2e8a 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -764,7 +764,9 @@ class OperationalScriptTests(unittest.TestCase):
)
def test_code_normalization(self):
- normalise = self.scrape_codes.normalise
+ # 归一化本体已收进 catalog_rules;脚本只是 import 它,这里验的是脚本用的
+ # 确实是那一份,而不是自己又抄了一个同名函数。
+ normalise = self.scrape_codes.normalise_code_key
self.assertEqual(normalise("fc2ppv-1234567"), "FC2-PPV-1234567")
self.assertEqual(normalise("abw123"), "ABW-123")
self.assertEqual(normalise("ipvr00296"), "IPVR-296")