spencernorton commited on
Commit
41cb0db
·
verified ·
1 Parent(s): c3bb71f

Release Armiger Ultra v3.12.0 (v3.0-gold-r13.13, DHT seq=15 / seq=3015)

Browse files
armiger-zero-cue-db-v3.11.0.torrent → 21b92f658b7b6f58cb2ac330988f4e188302ba17.torrent RENAMED
Binary files a/armiger-zero-cue-db-v3.11.0.torrent and b/21b92f658b7b6f58cb2ac330988f4e188302ba17.torrent differ
 
4a8a48e2436e5fe77029a360860cb41747a88b3c.torrent → 4adb9ffb83706dbc329d1f4384e53cb028449646.torrent RENAMED
Binary files a/4a8a48e2436e5fe77029a360860cb41747a88b3c.torrent and b/4adb9ffb83706dbc329d1f4384e53cb028449646.torrent differ
 
54b45957d34d06556ad4a2b12c6ecfa8c0bd9500.torrent DELETED
Binary file (12.1 kB)
 
585c4be6b1c20213567c504fa35de6e69ac09583.torrent ADDED
Binary file (12.1 kB). View file
 
README.md CHANGED
@@ -32,24 +32,24 @@ tags:
32
 
33
  **ONNX files:** 33,260,312 bytes (33.3 MB) FP32 and 17,606,362 bytes (17.6 MB) INT8.
34
  **Architecture:** approximately 8 million parameters, byte-level RoPE transformer.
35
- **License:** Apache-2.0. [Model release](https://github.com/spencernorton/armiger/releases/tag/v3.11.0).
36
 
37
  Armiger Ultra combines neural metadata predictions with optional title-catalogue
38
  matching, metadata-language rules, calibration and swarm-availability estimates.
39
  Its classifier reads names, file lists and supplied counters. It runs on a CPU;
40
  no GPU or paid inference API is required.
41
 
42
- **Model bundle 3.11.0.** [Armiger Standalone](https://huggingface.co/NorviTech/armiger) provides the focused INT8 ONNX classifier. See the [Armiger software and setup](https://github.com/spencernorton/armiger) or [NorviTech model overview](https://norvitech.com/ai-models/#armiger).
43
 
44
  ## Comparison charts
45
 
46
  **Latest published figures — provenance under review.** These archived charts retain their original model labels and scores. Their displayed values and vector-based source records still need reconciliation; they do not establish verified current-release performance. These Ultra hybrid comparisons do not measure standalone INT8 accuracy or payload safety. [Evaluation scope and source records](https://github.com/spencernorton/armiger/blob/main/docs/evaluation.md).
47
 
48
- ![Latest published Armiger Ultra comparison with cloud teacher models; provenance under review](https://huggingface.co/NorviTech/armiger-ultra/resolve/efd514648bd86c964e7ec837a2689c682c5d56bd/assets/armiger_vs_llms_overall_and_6dims.png)
49
 
50
  Cloud teacher comparisons use separate common-support and swarm cohorts; panel-specific sample counts and metrics must remain separate.
51
 
52
- ![Latest published Armiger Ultra comparison with open-source torrent classifiers and parsers; provenance under review](https://huggingface.co/NorviTech/armiger-ultra/resolve/efd514648bd86c964e7ec837a2689c682c5d56bd/assets/armiger_vs_torrent_classifiers_6dims.png)
53
 
54
  Classifier and parser comparisons cover separate category, catalogue, language, metadata-screening and swarm tasks. Original PNGs and recorded results are unchanged.
55
 
@@ -60,7 +60,7 @@ Ultra package and full SDK snapshot with extra authority/policy assets are
60
  different runtime paths. The GitHub package's INT8 Ultra option retains the
61
  Ultra components; it is not the standalone API.
62
 
63
- One CPU service using the complete R13.11 SDK with request-cache cleanup was
64
  observed near 2.1 GiB whole-container memory during a 628.8-second live workload,
65
  under a configured 4 GiB limit. This is one deployment observation, not a minimum
66
  requirement or a measurement of every public API. See
@@ -72,13 +72,13 @@ No current-release end-to-end CPU/GPU throughput or latency guarantee is made.
72
 
73
  ## Docker and Python
74
 
75
- The quickstart uses software 3.12.2 with model bundle 3.11.0.
76
  Choose the model-update channel explicitly; `off` keeps the bundled model pinned.
77
 
78
  ```bash
79
  docker run -d --name armiger-ultra -p 127.0.0.1:8096:8096 \
80
  -e ARMIGER_UPDATE_CHANNEL=off \
81
- ghcr.io/spencernorton/armiger-ultra:3.12.2
82
  ```
83
 
84
  For Bitmagnet or Rats Search, use the
@@ -87,7 +87,7 @@ For Python, follow the [installation guide](https://github.com/spencernorton/arm
87
  including CPU-only PyTorch on Linux when using the Ultra extra:
88
 
89
  ```bash
90
- python -m pip install "armiger[ultra] @ git+https://github.com/spencernorton/armiger.git@v3.12.2"
91
  python -m armiger download --directory ./models
92
  export ARMIGER_UPDATE_CHANNEL=off
93
  ```
@@ -120,7 +120,7 @@ guarantee a safe or available download. Optional post-import `ffprobe` checks in
120
  a connector are a separate operation.
121
 
122
  Published comparison graphics are under provenance review: the displayed
123
- 3.11.0 / 2,484-item overview and its 3.0.0 / 2,835-item data receipt do not
124
  describe the same results. The latest published comparison charts are restored
125
  above as archival figures with that provenance limit. Detailed charts also
126
  combine newer aggregate values with older vector-based statistical panels.
 
32
 
33
  **ONNX files:** 33,260,312 bytes (33.3 MB) FP32 and 17,606,362 bytes (17.6 MB) INT8.
34
  **Architecture:** approximately 8 million parameters, byte-level RoPE transformer.
35
+ **License:** Apache-2.0. [Model release](https://github.com/spencernorton/armiger/releases/tag/v3.12.0).
36
 
37
  Armiger Ultra combines neural metadata predictions with optional title-catalogue
38
  matching, metadata-language rules, calibration and swarm-availability estimates.
39
  Its classifier reads names, file lists and supplied counters. It runs on a CPU;
40
  no GPU or paid inference API is required.
41
 
42
+ **Model bundle 3.12.0.** [Armiger Standalone](https://huggingface.co/NorviTech/armiger) provides the focused INT8 ONNX classifier. See the [Armiger software and setup](https://github.com/spencernorton/armiger) or [NorviTech model overview](https://norvitech.com/ai-models/#armiger).
43
 
44
  ## Comparison charts
45
 
46
  **Latest published figures — provenance under review.** These archived charts retain their original model labels and scores. Their displayed values and vector-based source records still need reconciliation; they do not establish verified current-release performance. These Ultra hybrid comparisons do not measure standalone INT8 accuracy or payload safety. [Evaluation scope and source records](https://github.com/spencernorton/armiger/blob/main/docs/evaluation.md).
47
 
48
+ ![Latest published Armiger Ultra comparison with cloud teacher models; provenance under review](https://huggingface.co/NorviTech/armiger-ultra/resolve/main/assets/armiger_vs_llms_overall_and_6dims.png)
49
 
50
  Cloud teacher comparisons use separate common-support and swarm cohorts; panel-specific sample counts and metrics must remain separate.
51
 
52
+ ![Latest published Armiger Ultra comparison with open-source torrent classifiers and parsers; provenance under review](https://huggingface.co/NorviTech/armiger-ultra/resolve/main/assets/armiger_vs_torrent_classifiers_6dims.png)
53
 
54
  Classifier and parser comparisons cover separate category, catalogue, language, metadata-screening and swarm tasks. Original PNGs and recorded results are unchanged.
55
 
 
60
  different runtime paths. The GitHub package's INT8 Ultra option retains the
61
  Ultra components; it is not the standalone API.
62
 
63
+ One CPU service using the complete R13.13 SDK with request-cache cleanup was
64
  observed near 2.1 GiB whole-container memory during a 628.8-second live workload,
65
  under a configured 4 GiB limit. This is one deployment observation, not a minimum
66
  requirement or a measurement of every public API. See
 
72
 
73
  ## Docker and Python
74
 
75
+ The quickstart uses software 3.12.3 with model bundle 3.12.0.
76
  Choose the model-update channel explicitly; `off` keeps the bundled model pinned.
77
 
78
  ```bash
79
  docker run -d --name armiger-ultra -p 127.0.0.1:8096:8096 \
80
  -e ARMIGER_UPDATE_CHANNEL=off \
81
+ ghcr.io/spencernorton/armiger-ultra:3.12.3
82
  ```
83
 
84
  For Bitmagnet or Rats Search, use the
 
87
  including CPU-only PyTorch on Linux when using the Ultra extra:
88
 
89
  ```bash
90
+ python -m pip install "armiger[ultra] @ git+https://github.com/spencernorton/armiger.git@v3.12.3"
91
  python -m armiger download --directory ./models
92
  export ARMIGER_UPDATE_CHANNEL=off
93
  ```
 
120
  a connector are a separate operation.
121
 
122
  Published comparison graphics are under provenance review: the displayed
123
+ 3.12.0 / 2,484-item overview and its 3.0.0 / 2,835-item data receipt do not
124
  describe the same results. The latest published comparison charts are restored
125
  above as archival figures with that provenance limit. Detailed charts also
126
  combine newer aggregate values with older vector-based statistical panels.
_r12_features_base.py CHANGED
@@ -8,7 +8,7 @@ and `onnxruntime`.
8
  All release-group and publisher token tables are stored as 8-byte BLAKE2b-64 hex digests
9
  so zero copyrighted or scene group strings appear in plaintext.
10
 
11
- R12 Session 2: derivative-group file-tree features
12
  (`U_deriv_groups`, `E_episode_keys`, `P_multipart_idx`, `s_max`) are computed by
13
  `compute_derivative_group_features` and appended to the side vector at
14
  `side[24..27]`; negated subtitle clauses are stripped before the `side[13]`
@@ -26,7 +26,11 @@ import math
26
  import os
27
  from pathlib import Path
28
  import re
29
- from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
 
 
 
 
30
  import zlib
31
 
32
  try:
@@ -81,9 +85,9 @@ _PREP_KIND_EXTS = {
81
  0: frozenset("mkv mp4 avi ts m2ts mts vob wmv mpg mpeg mov flv rmvb rm m4v divx webm 3gp asf f4v ogv mxf m2v bik".split()),
82
  1: frozenset("mp3 flac m4a m4b aac ogg opus wav wma ape alac aif aiff aifc ac3 dts mka mpc wv shn mid midi dff dsf".split()),
83
  2: frozenset("zip rar 7z gz tgz bz2 xz zst lz lzma tar cab iso img dmg mdf mds nrg wim par par2 z".split()),
84
- 3: frozenset("exe msi apk ipa dll bat cmd sh vbs ps1 com scr jar deb rpm appimage run lnk".split()),
85
  4: frozenset("jpg jpeg png gif webp bmp tif tiff avif jxl heic heif psd ai svg ico tga cr2 nef arw dng raw eps".split()),
86
- 5: frozenset("pdf epub mobi azw azw3 djvu djv fb2 txt rtf doc docx odt xls xlsx ppt pptx csv chm cbz cbr cb7 html htm mht mhtml md tex lit".split()),
87
  6: frozenset("srt ass ssa sub idx vtt sup smi sbv ttml dfxp usf scc stl mks".split()),
88
  }
89
  _PREP_EXT_TO_KIND = {e: k for k, es in _PREP_KIND_EXTS.items() for e in es}
@@ -105,21 +109,18 @@ _SIDE_ANIME_KW_RE = re.compile(
105
  r"(?i)\b(?:anime|ova|ona|donghua|aeni|bdrip[ ._-]*1080p[ ._-]*flac|dual[ ._-]*audio[ ._-]*\[?(?:jpn|jap))\b"
106
  )
107
  _SIDE_VID_CLAIM_RE = re.compile(
108
- r"(?i)\b(?:1080p|720p|2160p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|hdrip|camrip|hdcam|telesync|x264|x265|hevc|avc|h264|h265|s\d{1,2}e\d{1,3}|season[ ._-]*\d+|fc2-?ppv)\b|高清首发|更新至第"
109
  )
110
  _SIDE_DECEPTIVE_SUB_STRIP_RE = re.compile(
111
  r"(?i)\b(?:eng(?:lish)?|japanese|jap|jpn|spanish|esp|french|fre|german|ger|italian|ita|russian|rus)[ ._-]+(?:hard|soft)?sub(?:s|bed|titled|titles)?\b|"
112
  r"\b(?:hard|soft)?sub(?:s|bed|titled|titles)?[ ._-]+(?:eng|english|esp|ja|jpn|fr|de|it|ru)\b|"
113
- r"\b(?:m[ ._-]?subs?|multi[ ._-]?subs?|esubs?|vostfr|hardsubs?)\b"
114
  )
115
  _SIDE_ANIME_DUB_KW_RE = re.compile(
116
- r"(?i)\b(?:dual[ ._-]?audio|dubbed|eng(?:lish)?[ ._-]?dub(?:bed)?|multi[ ._-]?audio)\b"
117
  )
118
  _SIDE_SW_APP_TITLE_RE = re.compile(
119
- r"(?i)\b(?:v?\d+\.\d+\.\d+|repack|portable|cracked|keygen|patch|patcher|activat(?:ed|or)|"
120
- r"multilingual|win(?:32|64)|x64|x86|macos|macosx|android|apk|pc[ ._-]?game|nintendo[ ._-]?switch|ps4|ps5|"
121
- r"emulator|driver|firmware|setup|installer|downloader|studio|vst3?|"
122
- r"pro[ ._-]+v?\d|ce[ ._-]+v?\d)\b"
123
  )
124
  _SIDE_COURSE_RE = re.compile(
125
  r"(?i)\b(?:complete[ ._-]+course|video[ ._-]+course|masterclass|bootcamp|tutorial[ ._-]+series|certification[ ._-]+course|hands-on[ ._-]+training)\b"
@@ -132,10 +133,7 @@ _SIDE_VPN_TRAP_RE = re.compile(
132
  )
133
  _SIDE_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
134
  _SIDE_EP_ZIP_RE = re.compile(
135
- r"(?i)(?:^\[[^\[\]]{2,30}\].*?(?:\s-\s*\d{1,3}\b|\bS\d{1,2}E\d{1,3}\b).*?\b(?:1080p|720p|2160p|480p)\b|"
136
- r"\bS\d{1,2}E\d{1,3}\b.*?\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\b|"
137
- r"\b(?:1080p|720p|2160p|480p|576p|4k)\b.*?\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip|x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX)\b|"
138
- r"\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip)\b(?:.*?\b(?:x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX))?)"
139
  )
140
  _SIDE_BENIGN_ZIP_RE = re.compile(
141
  r"(?i)\b(?:batch|complete|season[ ._-]*\d+|s\d{1,2}[ ._-]*complete|e?\d{1,3}[ ._-]*[~-][ ._-]*e?\d{1,3}|시즌\s*\d+|완결|全集|合集|"
@@ -193,29 +191,76 @@ _MEDIA_SUMMARY_EXTS = frozenset(
193
  _DERIV_LOG_NORM: float = math.log1p(64.0)
194
 
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  def _normalize_file_entries(files: Any) -> List[Tuple[str, int]]:
 
 
 
 
197
  """Normalize torrent `files` (dicts / (path, size) tuples / strings) to `(path, size)` pairs."""
198
  out: List[Tuple[str, int]] = []
199
  for f in files or []:
200
- if isinstance(f, Mapping):
201
  p = str(f.get("path") or f.get("p") or f.get("name") or "")
202
  try:
203
  sz = int(f.get("size") or f.get("s") or 0)
204
- except (TypeError, ValueError, OverflowError):
205
  sz = 0
206
  elif isinstance(f, (tuple, list)) and len(f) >= 1:
207
  p = str(f[0] or "")
208
  try:
209
  sz = int(f[1]) if len(f) > 1 else 0
210
- except (TypeError, ValueError, OverflowError):
211
  sz = 0
212
  else:
213
  p, sz = str(f or ""), 0
214
- if p and "/.____padding_file/" not in p and not p.startswith(".____padding_file"):
215
- out.append((p, max(sz, 0)))
 
 
216
  return out
217
 
218
 
 
 
 
 
219
  def _deriv_stem_key(parent: str, stem: str) -> Tuple[str, str]:
220
  """Collapse transcode renditions of one work to a single derivative-group key."""
221
  s = stem
@@ -224,12 +269,13 @@ def _deriv_stem_key(parent: str, stem: str) -> Tuple[str, str]:
224
  if stripped == s:
225
  break
226
  s = stripped
227
- norm_s = re.sub(r"[\W_]+", " ", s.lower(), flags=re.UNICODE).strip() or s.lower().strip()
228
- norm_p = re.sub(r"[\W_]+", " ", parent.lower(), flags=re.UNICODE).strip()
 
229
  return norm_p, norm_s
230
 
231
 
232
- def _episode_keys_from_text(text: str, default_season: Optional[int] = None) -> set:
233
  """Distinct episode keys in one path/name string (multipart CD/Part tokens never count)."""
234
  keys: set = set()
235
  if not text:
@@ -238,11 +284,7 @@ def _episode_keys_from_text(text: str, default_season: Optional[int] = None) ->
238
  int(g) for m in _SEASON_HINT_RE.finditer(text)
239
  for g in m.groups() if g is not None
240
  }
241
- for m_sxe in _EP_SXE_RE.finditer(text):
242
- seasons.add(int(m_sxe.group(1)))
243
- for m_nxn in _EP_NXN_RE.finditer(text):
244
- seasons.add(int(m_nxn.group(1)))
245
- season = seasons.pop() if len(seasons) == 1 else (default_season if not seasons else None)
246
 
247
  def add_bare(num: int) -> None:
248
  keys.add(f"s{season:02d}e{num:03d}" if season is not None else f"ep{num:04d}")
@@ -269,6 +311,14 @@ def _episode_keys_from_text(text: str, default_season: Optional[int] = None) ->
269
  def compute_derivative_group_features(
270
  files: Any,
271
  raw_name: str = "",
 
 
 
 
 
 
 
 
272
  ) -> Tuple[float, float, float, float]:
273
  """Compute `(U_deriv_groups, E_episode_keys, P_multipart_idx, s_max)` for a torrent file tree.
274
 
@@ -310,15 +360,10 @@ def compute_derivative_group_features(
310
  has_video_ts = False
311
  tv_marker = bool(_EP_SXE_RE.search(raw_name or "") or _PILOT_RE.search(raw_name or "")
312
  or _SEASON_HINT_RE.search(raw_name or ""))
313
- title_seasons = {
314
- int(g) for m in _SEASON_HINT_RE.finditer(raw_name or "")
315
- for g in m.groups() if g is not None
316
- } | {int(m.group(1)) for m in _EP_SXE_RE.finditer(raw_name or "")} | {int(m.group(1)) for m in _EP_NXN_RE.finditer(raw_name or "")}
317
- title_default_season = next(iter(title_seasons)) if len(title_seasons) == 1 else None
318
- ep_keys.update(_episode_keys_from_text(raw_name or "", default_season=title_default_season))
319
 
320
  for p_norm, parent, stem, sz in videos:
321
- ep_keys.update(_episode_keys_from_text(p_norm, default_season=title_default_season))
322
  part_indices.update(int(m.group(1)) for m in _MULTIPART_TOKEN_RE.finditer(p_norm))
323
  if _EP_SXE_RE.search(p_norm) or _PILOT_RE.search(p_norm) or _SEASON_HINT_RE.search(p_norm):
324
  tv_marker = True
@@ -357,27 +402,185 @@ def primary_media_file_summary(files: Any, top_n: int = 3) -> str:
357
  return " ; ".join(p for p, _ in media[:top_n])
358
 
359
 
360
- def build_enriched_name_text(name: str, files: Any, max_bytes: int = 256) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  """Append |FILES: <top-3 media basenames> when name is opaque or hides multi-episode files."""
 
 
 
 
362
  summary = primary_media_file_summary(files, top_n=3)
363
  if not summary:
364
- return name
365
- _, e_count, _, _ = compute_derivative_group_features(files, name)
366
  name_has_ep = bool(_episode_keys_from_text(name))
367
  is_opaque_slug = not bool(re.search(r"[A-Za-z]{3,}", name))
368
  hidden_ep_pack = (e_count >= 2 and not name_has_ep)
369
  if not (is_opaque_slug or hidden_ep_pack):
370
- return name
371
  basenames = " ; ".join(
372
  p.rsplit("/", 1)[-1] for p in summary.split(" ; ")
373
  )
374
- return f"{name} |FILES: {basenames}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
 
376
 
377
  def _h64(s: str) -> str:
378
  return hashlib.blake2b(s.strip().lower().encode("utf-8"), digest_size=8).hexdigest()
379
 
380
 
 
381
  def _extract_token_hashes(text: str) -> frozenset[str]:
382
  toks = [m.group(0).lower() for m in _TOKEN_SCAN_RE.finditer(text)]
383
  out = {_h64(t) for t in toks}
@@ -386,31 +589,16 @@ def _extract_token_hashes(text: str) -> frozenset[str]:
386
  return frozenset(out)
387
 
388
 
389
- _VOCAB_CACHE_BY_PATH: Dict[str, Dict[str, int]] = {}
390
-
391
-
392
  def _get_vocab_ext_map(vocab_path: Optional[Path] = None) -> Dict[str, int]:
393
  global _VOCAB_EXT_MAP
394
- if vocab_path is not None:
395
- vp = Path(vocab_path)
396
- if vp.exists():
397
- key = str(vp.resolve())
398
- if key not in _VOCAB_CACHE_BY_PATH:
399
- data = json.loads(vp.read_text(encoding="utf-8"))
400
- _VOCAB_CACHE_BY_PATH[key] = {e: i + 1 for i, e in enumerate(data.get("exts", []))}
401
- _VOCAB_EXT_MAP = _VOCAB_CACHE_BY_PATH[key]
402
- return _VOCAB_EXT_MAP
403
- if vocab_path is None and _VOCAB_EXT_MAP is not None and len(_VOCAB_EXT_MAP) > 64:
404
  return _VOCAB_EXT_MAP
405
- vpath = Path(__file__).resolve().with_name("vocab.json")
406
  if not vpath.exists() and os.environ.get("ARMIGER_MODEL_DIR"):
407
  vpath = Path(os.environ["ARMIGER_MODEL_DIR"]) / "vocab.json"
408
  if vpath.exists():
409
- key = str(vpath.resolve())
410
- if key not in _VOCAB_CACHE_BY_PATH:
411
- data = json.loads(vpath.read_text(encoding="utf-8"))
412
- _VOCAB_CACHE_BY_PATH[key] = {e: i + 1 for i, e in enumerate(data.get("exts", []))}
413
- _VOCAB_EXT_MAP = _VOCAB_CACHE_BY_PATH[key]
414
  else:
415
  _VOCAB_EXT_MAP = {
416
  "mp3": 2, "mp4": 3, "mkv": 4, "avi": 7, "srt": 10, "zip": 12,
@@ -458,33 +646,80 @@ def _prep_path_words(parent: str, stem: str) -> List[int]:
458
  return res[:4]
459
 
460
 
461
- def encode_torrent_features(
462
  row: Mapping[str, Any],
463
  max_name_len: int = 256,
464
  max_files: int = 64,
 
465
  ) -> Dict[str, Any]:
466
  """Encode a torrent metadata dictionary into the exact ONNX tensor inputs for Armiger v2.1."""
467
  name = str(row.get("name") or row.get("title") or "")
468
 
469
  raw_files = row.get("files") or []
470
- try:
471
- total_size = max(0, int(row.get("size") or 0))
472
- except (TypeError, ValueError, OverflowError):
473
- total_size = 0
474
- all_items: List[Tuple[str, int]] = _normalize_file_entries(raw_files)
 
 
 
 
 
 
 
 
 
 
 
475
  all_items.sort(key=lambda x: -x[1])
476
- items: List[Tuple[str, int]] = all_items[:max_files]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
477
  if not items and (row.get("ext") or row.get("extension") or "." in name):
478
- items.append((name, total_size))
 
 
 
 
 
 
 
 
 
 
 
 
 
479
 
480
  # R12: opaque/folder names expose their primary media filenames to the
481
  # byte/char/word encoders; derivative-group features use the full tree.
482
- name_text = build_enriched_name_text(name, all_items or items, max_bytes=max_name_len)
 
 
 
 
483
  b_name = name_text.encode("utf-8", "replace")
484
  if len(b_name) > max_name_len:
485
  b_name = b_name[:max_name_len].decode("utf-8", "ignore").encode("utf-8")
486
  raw_bytes = list(b_name) if b_name else [32]
487
- deriv_features = compute_derivative_group_features(all_items or items, name)
488
 
489
  ext_map = _get_vocab_ext_map()
490
  exts: List[int] = []
@@ -514,11 +749,7 @@ def encode_torrent_features(
514
  tot_k = sum(kbytes)
515
  weights = kbytes if tot_k > 0 else [float(c) for c in kcount]
516
  wsum = sum(weights)
517
- try:
518
- raw_fc = max(0, int(row.get("file_count") or 0))
519
- except (TypeError, ValueError, OverflowError):
520
- raw_fc = 0
521
- count = max(raw_fc, len(all_items), len(items))
522
  biggest = max((max(s, 0) for _, s in items), default=0)
523
  max_share = (biggest / tot_k if tot_k > 0 else (1.0 / len(items) if items else 0.0))
524
 
@@ -595,8 +826,7 @@ def encode_torrent_features(
595
  has_any_scr_ext = True
596
  if e_str in {"scr", "vbs", "vbe", "hta", "pif", "wsf", "wsh", "cpl"}:
597
  has_unconditional_trap_ext = True
598
- p_tok_h = _extract_token_hashes(p_i)
599
- is_benign_stub = (e_str == "exe") and (s_b < 15 or 16570 in w_i or bool(p_tok_h & _BENIGN_README_EXE_H))
600
  if e_str in exe_dll_set and not is_benign_stub:
601
  n_real_exec_dll += 1
602
  if e_str == "exe" and not is_benign_stub and s_b >= 15:
@@ -649,6 +879,8 @@ def encode_torrent_features(
649
  side[11] = 1.0
650
  if vc and vid_share > 0 and 0 < base_stats[1] < 14.22:
651
  side[12] = 1.0
 
 
652
 
653
  # R12: strip negated subtitle clauses ("no english subs", ...) before the
654
  # side[13] subtitle cue; previously side[13] was never populated at all.
@@ -669,7 +901,8 @@ def encode_torrent_features(
669
  side[17] = 1.0
670
  if has_sw_grp and not _SIDE_CJK_RE.search(name):
671
  side[18] = 1.0
672
- if _SIDE_COURSE_RE.search(name) and not ag:
 
673
  side[19] = 1.0
674
  if _SIDE_BOOK_COMIC_KW_RE.search(name) or has_book_grp:
675
  side[20] = 1.0
@@ -685,6 +918,8 @@ def encode_torrent_features(
685
  # R12 derivative-group features (raw counts stay in `deriv_features`;
686
  # the network sees bounded log-normalized U/E, binary P, raw s_max).
687
  _u, _e, _p, _smax = deriv_features
 
 
688
  side[24] = min(1.0, math.log1p(_u) / _DERIV_LOG_NORM)
689
  side[25] = min(1.0, math.log1p(_e) / _DERIV_LOG_NORM)
690
  side[26] = float(_p)
@@ -702,6 +937,57 @@ def encode_torrent_features(
702
  }
703
 
704
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
705
  def build_onnx_batch_inputs(
706
  rows: Sequence[Mapping[str, Any]],
707
  max_name_len: int = 256,
@@ -873,7 +1159,7 @@ class ArmigerStandaloneONNX:
873
  raw_nm = str(rows[i].get("name") or rows[i].get("title") or "")
874
  try:
875
  try:
876
- from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
877
  except ImportError:
878
  from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
879
  raw_b = raw_nm.encode("utf-8", errors="replace")[: vec.shape[0]]
@@ -930,3 +1216,52 @@ ArmigerONNXClassifier = ArmigerStandaloneONNX
930
 
931
  def _apply_v3_post_neural_guard(row, result):
932
  return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  All release-group and publisher token tables are stored as 8-byte BLAKE2b-64 hex digests
9
  so zero copyrighted or scene group strings appear in plaintext.
10
 
11
+ R12 Session 2 (OP#1164 / OP#1210): derivative-group file-tree features
12
  (`U_deriv_groups`, `E_episode_keys`, `P_multipart_idx`, `s_max`) are computed by
13
  `compute_derivative_group_features` and appended to the side vector at
14
  `side[24..27]`; negated subtitle clauses are stripped before the `side[13]`
 
26
  import os
27
  from pathlib import Path
28
  import re
29
+ import sys
30
+ sys.dont_write_bytecode = True
31
+ from collections.abc import Mapping, Sequence
32
+ from functools import lru_cache
33
+ from typing import Any, Dict, List, Optional, Tuple
34
  import zlib
35
 
36
  try:
 
85
  0: frozenset("mkv mp4 avi ts m2ts mts vob wmv mpg mpeg mov flv rmvb rm m4v divx webm 3gp asf f4v ogv mxf m2v bik".split()),
86
  1: frozenset("mp3 flac m4a m4b aac ogg opus wav wma ape alac aif aiff aifc ac3 dts mka mpc wv shn mid midi dff dsf".split()),
87
  2: frozenset("zip rar 7z gz tgz bz2 xz zst lz lzma tar cab iso img dmg mdf mds nrg wim par par2 z".split()),
88
+ 3: frozenset("exe msi apk ipa dll bat cmd sh vbs vbe wsf wsh hta pif cpl jse psm1 ps1 com scr jar deb rpm appimage run lnk".split()),
89
  4: frozenset("jpg jpeg png gif webp bmp tif tiff avif jxl heic heif psd ai svg ico tga cr2 nef arw dng raw eps".split()),
90
+ 5: frozenset("pdf epub mobi azw azw3 djvu djv fb2 txt rtf doc docx odt xls xlsx ppt pptx csv chm cbz cbr cb7 html htm mht md tex lit".split()),
91
  6: frozenset("srt ass ssa sub idx vtt sup smi sbv ttml dfxp usf scc stl mks".split()),
92
  }
93
  _PREP_EXT_TO_KIND = {e: k for k, es in _PREP_KIND_EXTS.items() for e in es}
 
109
  r"(?i)\b(?:anime|ova|ona|donghua|aeni|bdrip[ ._-]*1080p[ ._-]*flac|dual[ ._-]*audio[ ._-]*\[?(?:jpn|jap))\b"
110
  )
111
  _SIDE_VID_CLAIM_RE = re.compile(
112
+ '(?i)\\b(?:1080p|720p|2160p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|hdcam|telesync|x264|x265|hevc|avc|h264|h265|s\\d{1,2}e\\d{1,3}|season[ ._-]*\\d+)\\b|高清首发|更新至第'
113
  )
114
  _SIDE_DECEPTIVE_SUB_STRIP_RE = re.compile(
115
  r"(?i)\b(?:eng(?:lish)?|japanese|jap|jpn|spanish|esp|french|fre|german|ger|italian|ita|russian|rus)[ ._-]+(?:hard|soft)?sub(?:s|bed|titled|titles)?\b|"
116
  r"\b(?:hard|soft)?sub(?:s|bed|titled|titles)?[ ._-]+(?:eng|english|esp|ja|jpn|fr|de|it|ru)\b|"
117
+ r"\b(?:multi[\s._-]+subs?|esubs?|vostfr|hardsubs?)\b"
118
  )
119
  _SIDE_ANIME_DUB_KW_RE = re.compile(
120
+ r"(?i)\b(?:dual[\s._-]+audio|dubbed|eng(?:lish)?[\s._-]+dub(?:bed)?|multi[\s._-]+audio)\b"
121
  )
122
  _SIDE_SW_APP_TITLE_RE = re.compile(
123
+ '(?i)\\b(?:v?\\d+\\.\\d+\\.\\d+|repack|portable|cracked|patch|activat(?:ed|or)|multilingual|win(?:32|64)|x64|x86|macos|macosx|android|apk|pc[ ._-]?game|nintendo[ ._-]?switch|ps4|ps5|emulator|driver|firmware|setup|installer|studio|vst3?|pro[ ._-]+v?\\d|ce[ ._-]+v?\\d)\\b'
 
 
 
124
  )
125
  _SIDE_COURSE_RE = re.compile(
126
  r"(?i)\b(?:complete[ ._-]+course|video[ ._-]+course|masterclass|bootcamp|tutorial[ ._-]+series|certification[ ._-]+course|hands-on[ ._-]+training)\b"
 
133
  )
134
  _SIDE_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
135
  _SIDE_EP_ZIP_RE = re.compile(
136
+ '(?i)(?:^\\[[^\\[\\]]{2,30}\\].*?(?:\\s-\\s*\\d{1,3}\\b|\\bS\\d{1,2}E\\d{1,3}\\b).*?\\b(?:1080p|720p|2160p|480p)\\b|\\bS\\d{1,2}E\\d{1,3}\\b.*?\\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\\b|\\b(?:1080p|720p|2160p|480p|576p|4k)\\b.*?\\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDTV|HDCAM|DVDRip|x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX)\\b|\\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDTV|HDCAM|DVDRip)\\b(?:.*?\\b(?:x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX))?)'
 
 
 
137
  )
138
  _SIDE_BENIGN_ZIP_RE = re.compile(
139
  r"(?i)\b(?:batch|complete|season[ ._-]*\d+|s\d{1,2}[ ._-]*complete|e?\d{1,3}[ ._-]*[~-][ ._-]*e?\d{1,3}|시즌\s*\d+|완결|全集|合集|"
 
191
  _DERIV_LOG_NORM: float = math.log1p(64.0)
192
 
193
 
194
+ _FK_RING: list = [
195
+ [None, -1, (), None, None],
196
+ [None, -1, (), None, None],
197
+ [None, -1, (), None, None],
198
+ [None, -1, (), None, None],
199
+ ]
200
+ _FK_RING_IDX: int = 0
201
+
202
+
203
+ def _files_key_fast(files: Any) -> Tuple[Tuple[str, int], ...]:
204
+ global _FK_RING_IDX
205
+ if not files:
206
+ return ()
207
+ if isinstance(files, tuple):
208
+ f0 = files[0]
209
+ if isinstance(f0, tuple) and len(f0) == 2 and isinstance(f0[0], str) and isinstance(f0[1], int):
210
+ return files
211
+ if isinstance(files, list):
212
+ n = len(files)
213
+ f0 = files[0]
214
+ fN = files[-1]
215
+ p0 = (f0.get("path") or f0.get("p") or f0.get("name"), f0.get("size") or f0.get("s") or 0) if isinstance(f0, dict) else f0
216
+ pN = (fN.get("path") or fN.get("p") or fN.get("name"), fN.get("size") or fN.get("s") or 0) if isinstance(fN, dict) else fN
217
+ for slot in _FK_RING:
218
+ if slot[0] is files and slot[1] == n and slot[3] == p0 and slot[4] == pN:
219
+ return slot[2]
220
+ res = tuple(_raw_normalize_file_entries(files))
221
+ slot = _FK_RING[_FK_RING_IDX]
222
+ if len(slot) < 5:
223
+ slot[:] = [files, n, res, p0, pN]
224
+ else:
225
+ slot[0], slot[1], slot[2], slot[3], slot[4] = files, n, res, p0, pN
226
+ _FK_RING_IDX = (_FK_RING_IDX + 1) & 3
227
+ return res
228
+ return tuple(_raw_normalize_file_entries(files))
229
+
230
+
231
  def _normalize_file_entries(files: Any) -> List[Tuple[str, int]]:
232
+ return list(_files_key_fast(files))
233
+
234
+
235
+ def _raw_normalize_file_entries(files: Any) -> List[Tuple[str, int]]:
236
  """Normalize torrent `files` (dicts / (path, size) tuples / strings) to `(path, size)` pairs."""
237
  out: List[Tuple[str, int]] = []
238
  for f in files or []:
239
+ if isinstance(f, dict) or isinstance(f, Mapping):
240
  p = str(f.get("path") or f.get("p") or f.get("name") or "")
241
  try:
242
  sz = int(f.get("size") or f.get("s") or 0)
243
+ except (TypeError, ValueError):
244
  sz = 0
245
  elif isinstance(f, (tuple, list)) and len(f) >= 1:
246
  p = str(f[0] or "")
247
  try:
248
  sz = int(f[1]) if len(f) > 1 else 0
249
+ except (TypeError, ValueError):
250
  sz = 0
251
  else:
252
  p, sz = str(f or ""), 0
253
+ if p:
254
+ p = p.replace("\\", "/")
255
+ if "/.____padding_file/" not in p and not p.startswith(".____padding_file"):
256
+ out.append((p, max(sz, 0)))
257
  return out
258
 
259
 
260
+ _NONWORD_FB_RE = re.compile(r"[\W_]+", re.UNICODE)
261
+
262
+
263
+ @lru_cache(maxsize=65536)
264
  def _deriv_stem_key(parent: str, stem: str) -> Tuple[str, str]:
265
  """Collapse transcode renditions of one work to a single derivative-group key."""
266
  s = stem
 
269
  if stripped == s:
270
  break
271
  s = stripped
272
+ sl = s.lower()
273
+ norm_s = _NONWORD_FB_RE.sub(" ", sl).strip() or sl.strip()
274
+ norm_p = _NONWORD_FB_RE.sub(" ", parent.lower()).strip() if parent else ""
275
  return norm_p, norm_s
276
 
277
 
278
+ def _episode_keys_from_text(text: str) -> set:
279
  """Distinct episode keys in one path/name string (multipart CD/Part tokens never count)."""
280
  keys: set = set()
281
  if not text:
 
284
  int(g) for m in _SEASON_HINT_RE.finditer(text)
285
  for g in m.groups() if g is not None
286
  }
287
+ season = seasons.pop() if len(seasons) == 1 else None
 
 
 
 
288
 
289
  def add_bare(num: int) -> None:
290
  keys.add(f"s{season:02d}e{num:03d}" if season is not None else f"ep{num:04d}")
 
311
  def compute_derivative_group_features(
312
  files: Any,
313
  raw_name: str = "",
314
+ ) -> Tuple[float, float, float, float]:
315
+ return _cached_deriv_group_features(_files_key_fast(files), str(raw_name or ""))
316
+
317
+
318
+ @lru_cache(maxsize=32768)
319
+ def _cached_deriv_group_features(
320
+ files: Tuple[Tuple[str, int], ...],
321
+ raw_name: str = "",
322
  ) -> Tuple[float, float, float, float]:
323
  """Compute `(U_deriv_groups, E_episode_keys, P_multipart_idx, s_max)` for a torrent file tree.
324
 
 
360
  has_video_ts = False
361
  tv_marker = bool(_EP_SXE_RE.search(raw_name or "") or _PILOT_RE.search(raw_name or "")
362
  or _SEASON_HINT_RE.search(raw_name or ""))
363
+ ep_keys.update(_episode_keys_from_text(raw_name or ""))
 
 
 
 
 
364
 
365
  for p_norm, parent, stem, sz in videos:
366
+ ep_keys.update(_episode_keys_from_text(p_norm))
367
  part_indices.update(int(m.group(1)) for m in _MULTIPART_TOKEN_RE.finditer(p_norm))
368
  if _EP_SXE_RE.search(p_norm) or _PILOT_RE.search(p_norm) or _SEASON_HINT_RE.search(p_norm):
369
  tv_marker = True
 
402
  return " ; ".join(p for p, _ in media[:top_n])
403
 
404
 
405
+ _COURSE_NUMBERED_RE = re.compile(
406
+ r"(?i)(?<![a-z])(?:lecture|lesson|module|week|unit|session|chapter)[\s._-]*\d{1,3}(?!\d)"
407
+ )
408
+ _COURSE_PROVIDER_RE = re.compile(
409
+ '(?i)(?<![a-z])(?:udemy|coursera|lynda|great[\\s._-]*courses|teaching[\\s._-]*company|mitres[\\s._-]?|opencourseware|ocw)(?![a-z])'
410
+ )
411
+ _COURSE_COMPANION_RE = re.compile(
412
+ r"(?i)(?<![a-z])(?:syllabus|course[\s._-]*guidebook|instructor|professor)(?![a-z])"
413
+ )
414
+ _COURSE_NEGATIVE_RE = re.compile(
415
+ r"(?i)(?<![a-z0-9])(?:s\d{1,2}[\s._-]*e\d{1,3}|featurettes?|deleted[\s._-]*scenes?)(?![a-z0-9])"
416
+ )
417
+ _COURSE_FILE_EXTS = frozenset(("mp4", "mkv", "pdf", "srt"))
418
+ _COURSE_VIDEO_EXTS = frozenset(("mp4", "mkv"))
419
+
420
+
421
+ def curriculum_file_cues(files: Any) -> Tuple[bool, List[str], int]:
422
+ act, ev, cg = _cached_curriculum_cues(_files_key_fast(files))
423
+ return act, list(ev), cg
424
+
425
+
426
+ _COURSE_ANY_FAST_RE = re.compile(
427
+ r"(?i)(?:lecture|lesson|module|week|unit|session|chapter|udemy|coursera|lynda|courses|teaching|mitres|opencourseware|ocw|syllabus|guidebook|instructor|professor)"
428
+ )
429
+
430
+
431
+ @lru_cache(maxsize=32768)
432
+ def _cached_curriculum_cues(files: Tuple[Tuple[str, int], ...]) -> Tuple[bool, Tuple[str, ...], int]:
433
+ paths = [p.replace("\\", "/") for p, _ in _normalize_file_entries(files)]
434
+ media = [p for p in paths if p.rsplit("/", 1)[-1].rsplit(".", 1)[-1].lower() in _COURSE_FILE_EXTS]
435
+ if len(media) < 2:
436
+ return False, (), 0
437
+ surface = "\n".join(paths)
438
+ surface_low = surface.lower()
439
+ if not any(k in surface_low for k in ("lecture", "lesson", "module", "week", "unit", "session", "chapter", "udemy", "coursera", "lynda", "courses", "teaching", "mitres", "opencourseware", "ocw", "syllabus", "guidebook", "instructor", "professor")):
440
+ return False, (), 0
441
+ numbered = [p for p in media if _COURSE_NUMBERED_RE.search(p)] if _COURSE_NUMBERED_RE.search(surface) else []
442
+ distinct = {re.sub(r"(?i)(?<![a-z])(?:lecture|lesson|module|week|unit|session|chapter)[\s._-]*\d{1,3}(?!\d)", "", p).rsplit("/", 1)[-1].lower() + _COURSE_NUMBERED_RE.search(p).group(0).lower() for p in numbered}
443
+ provider = [p for p in paths if _COURSE_PROVIDER_RE.search(p)] if _COURSE_PROVIDER_RE.search(surface) else []
444
+ companion = [p for p in paths if _COURSE_COMPANION_RE.search(p)] if _COURSE_COMPANION_RE.search(surface) else []
445
+ videos = [p for p in media if p.rsplit("/", 1)[-1].rsplit(".", 1)[-1].lower() in _COURSE_VIDEO_EXTS]
446
+ negative = bool(_COURSE_NEGATIVE_RE.search(surface)) if (len(distinct) >= 2 or (bool(provider or companion) and bool(videos))) else False
447
+ numbered_course = len(distinct) >= 2 and not negative
448
+ supported_course = len(media) >= 2 and bool(provider or companion) and bool(videos) and not negative
449
+ active = numbered_course or supported_course
450
+ evidence = []
451
+ for p in numbered + provider + companion:
452
+ if p not in evidence:
453
+ evidence.append(p)
454
+ return active, tuple(evidence[:4]), max(len({p.rsplit("/", 1)[-1].lower() for p in numbered}), 2 if supported_course else 0)
455
+
456
+
457
+ def build_enriched_name_text(name: str, files: Any, max_bytes: int = 256, _deriv: Optional[Tuple[float, float, float, float]] = None) -> str:
458
  """Append |FILES: <top-3 media basenames> when name is opaque or hides multi-episode files."""
459
+ course, course_paths, _ = curriculum_file_cues(files)
460
+ course_suffix = ""
461
+ if course:
462
+ course_suffix = " |COURSE_FILES: " + " ; ".join(p.rsplit("/", 1)[-1] for p in course_paths)
463
  summary = primary_media_file_summary(files, top_n=3)
464
  if not summary:
465
+ return name + course_suffix
466
+ _, e_count, _, _ = _deriv if _deriv is not None else compute_derivative_group_features(files, name)
467
  name_has_ep = bool(_episode_keys_from_text(name))
468
  is_opaque_slug = not bool(re.search(r"[A-Za-z]{3,}", name))
469
  hidden_ep_pack = (e_count >= 2 and not name_has_ep)
470
  if not (is_opaque_slug or hidden_ep_pack):
471
+ return name + course_suffix
472
  basenames = " ; ".join(
473
  p.rsplit("/", 1)[-1] for p in summary.split(" ; ")
474
  )
475
+ return f"{name} |FILES: {basenames}{course_suffix}"
476
+
477
+
478
+
479
+
480
+ _IA_SKIP_SUMMARY_V39_RE = re.compile(
481
+ r"(?i)(?:_meta\.(?:xml|sqlite)|_files\.xml|_archive\.torrent|_reviews\.xml|__ia_thumb\.jpg|"
482
+ r"\.asr\.(?:srt|vtt|js)|\.ia\.mp4$|_(?:512kb|256kb|64kb)\.mp4$|_(?:thumb|itemimage|spectrogram)\.(?:jpg|png|gif)$)"
483
+ )
484
+ _CAMEL_SPLIT_V39_RE = re.compile(r"(?<=[a-z])(?=[A-Z])|(?<=[A-Za-z])(?=\d)|(?<=\d)(?=[A-Za-z])")
485
+ _MEDIA_SUMMARY_EXTS_V39 = frozenset(
486
+ set(_DERIV_VIDEO_EXTS)
487
+ | set("mp3 flac m4b m4a ogg opus epub mobi azw azw3 pdf cbz cbr cb7 "
488
+ "exe msi apk ipa dmg pkg deb rpm appimage sh nsp xci xcz nsz "
489
+ "zip rar 7z iso bin cue chd wad cia nds gba smc sfc nes z64 n64 pbp cso".split())
490
+ )
491
+ _GENERIC_FILE_WORDS_V39 = {
492
+ "mp4", "mkv", "avi", "mov", "ogv", "webm", "wmv", "flv", "mpg", "mpeg", "m4v",
493
+ "zip", "rar", "7z", "iso", "bin", "cue", "exe", "msi", "apk", "ipa", "dmg",
494
+ "pdf", "epub", "mobi", "cbz", "cbr", "mp3", "flac", "m4b", "m4a", "ogg", "wav",
495
+ "the", "and", "for", "with", "part", "vol", "volume", "track", "audio", "video",
496
+ "itemimage", "thumb", "cover", "index", "setup", "install", "version", "disc", "disk",
497
+ }
498
+ _SCAN_DOC_DERIV_V39_RE = re.compile(
499
+ r"(?i)(?:_(?:jp2|daisy|images|abbyy|djvu|hocr|chocr|scandata|meta|thumb|text|bw)\.(?:zip|gz|xml|txt|pdf|json|sqlite)|\.(?:epub|pdf|djvu|mobi|azw3?|txt|xml|json|sqlite|log|jpg|jpeg|png|gif|cbz|cbr|cb7))$"
500
+ )
501
+
502
+ def primary_media_file_summary_v39(files: Any, top_n: int = 3) -> str:
503
+ raw_entries = _normalize_file_entries(files)
504
+ media = []
505
+ for p, sz in raw_entries:
506
+ base = p.rsplit("/", 1)[-1]
507
+ if "." not in base or _IA_SKIP_SUMMARY_V39_RE.search(base):
508
+ continue
509
+ ext = base.rsplit(".", 1)[-1].lower()
510
+ if ext in _MEDIA_SUMMARY_EXTS_V39:
511
+ media.append((p, sz))
512
+ media.sort(key=lambda x: -x[1])
513
+ dedup = []
514
+ seen_stems = set()
515
+ for p, sz in media:
516
+ parent, stem, _, _ = _prep_split_path(p)
517
+ k = _deriv_stem_key(parent, stem)
518
+ if k not in seen_stems:
519
+ seen_stems.add(k)
520
+ dedup.append(p)
521
+ if len(dedup) >= top_n:
522
+ break
523
+ return " ; ".join(dedup)
524
+
525
+ def _has_novel_inner_tokens_v39(name: str, summary: str) -> bool:
526
+ if len(name.encode("utf-8", "replace")) >= 200:
527
+ return False
528
+ n_low = _CAMEL_SPLIT_V39_RE.sub(" ", name).lower()
529
+ n_toks = set(re.findall(r"[a-z0-9]{3,}", n_low))
530
+ n_squash = re.sub(r"[^a-z0-9]+", "", name.lower())
531
+ for p in summary.split(" ; "):
532
+ base = p.rsplit("/", 1)[-1]
533
+ if _SCAN_DOC_DERIV_V39_RE.search(base):
534
+ continue
535
+ stem = base.rsplit(".", 1)[0] if "." in base else base
536
+ s_low = _CAMEL_SPLIT_V39_RE.sub(" ", stem).lower()
537
+ for tok in re.findall(r"[a-z]{4,}", s_low):
538
+ if tok not in _GENERIC_FILE_WORDS_V39 and tok not in n_toks and tok not in n_squash:
539
+ return True
540
+ return False
541
+
542
+
543
+ def build_enriched_name_text_v39(name: str, files: Any, max_bytes: int = 256) -> str:
544
+ return _cached_enriched_v39(str(name or ""), _files_key_fast(files), int(max_bytes))
545
+
546
+
547
+ @lru_cache(maxsize=32768)
548
+ def _cached_enriched_v39(name: str, files: Tuple[Tuple[str, int], ...], max_bytes: int = 256) -> str:
549
+ if not files:
550
+ return name
551
+ course, course_paths, _ = curriculum_file_cues(files)
552
+ course_suffix = ""
553
+ if course:
554
+ cb = " ; ".join(p.rsplit("/", 1)[-1] for p in course_paths)
555
+ course_suffix = f" |COURSE_FILES: {cb}"
556
+ summary = primary_media_file_summary_v39(files, top_n=3)
557
+ if not summary:
558
+ return name + course_suffix
559
+ is_opaque_slug = not bool(re.search(r"[A-Za-z]{3,}", name))
560
+ name_has_ep = True if is_opaque_slug else bool(_episode_keys_from_text(name))
561
+ novel_inner = _has_novel_inner_tokens_v39(name, summary)
562
+ parts = [p.rsplit("/", 1)[-1] for p in summary.split(" ; ")]
563
+ has_scan_doc_deriv = any(_SCAN_DOC_DERIV_V39_RE.search(b) for b in parts) if novel_inner else False
564
+ if is_opaque_slug or name_has_ep or len(files) < 2 or (novel_inner and not has_scan_doc_deriv):
565
+ hidden_ep_pack = False
566
+ else:
567
+ _, e_count, _, _ = compute_derivative_group_features(files, raw_name=name)
568
+ hidden_ep_pack = (e_count >= 2 and not name_has_ep)
569
+ if not (is_opaque_slug or hidden_ep_pack or novel_inner):
570
+ return name + course_suffix
571
+ if novel_inner and not (is_opaque_slug or hidden_ep_pack) and has_scan_doc_deriv:
572
+ parts = [b for b in parts if not _SCAN_DOC_DERIV_V39_RE.search(b)]
573
+ if not parts:
574
+ return name + course_suffix
575
+ basenames = " ; ".join(parts)
576
+ return f"{name} |FILES: {basenames}{course_suffix}"
577
 
578
 
579
  def _h64(s: str) -> str:
580
  return hashlib.blake2b(s.strip().lower().encode("utf-8"), digest_size=8).hexdigest()
581
 
582
 
583
+ @lru_cache(maxsize=65536)
584
  def _extract_token_hashes(text: str) -> frozenset[str]:
585
  toks = [m.group(0).lower() for m in _TOKEN_SCAN_RE.finditer(text)]
586
  out = {_h64(t) for t in toks}
 
589
  return frozenset(out)
590
 
591
 
 
 
 
592
  def _get_vocab_ext_map(vocab_path: Optional[Path] = None) -> Dict[str, int]:
593
  global _VOCAB_EXT_MAP
594
+ if _VOCAB_EXT_MAP is not None and len(_VOCAB_EXT_MAP) > 64:
 
 
 
 
 
 
 
 
 
595
  return _VOCAB_EXT_MAP
596
+ vpath = vocab_path if (vocab_path and vocab_path.exists()) else Path(__file__).resolve().with_name("vocab.json")
597
  if not vpath.exists() and os.environ.get("ARMIGER_MODEL_DIR"):
598
  vpath = Path(os.environ["ARMIGER_MODEL_DIR"]) / "vocab.json"
599
  if vpath.exists():
600
+ data = json.loads(vpath.read_text(encoding="utf-8"))
601
+ _VOCAB_EXT_MAP = {e: i + 1 for i, e in enumerate(data.get("exts", []))}
 
 
 
602
  else:
603
  _VOCAB_EXT_MAP = {
604
  "mp3": 2, "mp4": 3, "mkv": 4, "avi": 7, "srt": 10, "zip": 12,
 
646
  return res[:4]
647
 
648
 
649
+ def _uncached_encode_torrent_features(
650
  row: Mapping[str, Any],
651
  max_name_len: int = 256,
652
  max_files: int = 64,
653
+ v39: bool = False,
654
  ) -> Dict[str, Any]:
655
  """Encode a torrent metadata dictionary into the exact ONNX tensor inputs for Armiger v2.1."""
656
  name = str(row.get("name") or row.get("title") or "")
657
 
658
  raw_files = row.get("files") or []
659
+ total_size = int(row.get("size") or 0)
660
+ all_items: List[Tuple[str, int]] = []
661
+ if isinstance(raw_files, tuple) and (not raw_files or (isinstance(raw_files[0], tuple) and len(raw_files[0]) == 2)):
662
+ all_items = list(raw_files)
663
+ else:
664
+ for f in raw_files:
665
+ if isinstance(f, dict) or isinstance(f, Mapping):
666
+ p = str(f.get("path") or f.get("p") or f.get("name") or "")
667
+ sz = int(f.get("size") or f.get("s") or 0)
668
+ elif isinstance(f, tuple) and len(f) == 2:
669
+ p, sz = str(f[0] or ""), int(f[1] or 0)
670
+ else:
671
+ p = str(f or "")
672
+ sz = 0
673
+ if p and "/.____padding_file/" not in p and not p.startswith(".____padding_file"):
674
+ all_items.append((p, sz))
675
  all_items.sort(key=lambda x: -x[1])
676
+ all_items = tuple(all_items)
677
+ if v39:
678
+ deriv_features = compute_derivative_group_features(all_items, name)
679
+ if deriv_features[0] == 1.0 and deriv_features[1] <= 1.0 and len(all_items) >= 2:
680
+ kept_video = False
681
+ dedup_items: List[Tuple[str, int]] = []
682
+ for p_it, sz_it in all_items:
683
+ _, _, ext_it, _ = _prep_split_path(p_it)
684
+ if _PREP_EXT_TO_KIND.get(ext_it) == 0:
685
+ if not kept_video:
686
+ kept_video = True
687
+ dedup_items.append((p_it, sz_it))
688
+ else:
689
+ dedup_items.append((p_it, sz_it))
690
+ items: List[Tuple[str, int]] = dedup_items[:max_files]
691
+ else:
692
+ items = list(all_items[:max_files])
693
+ else:
694
+ items = list(all_items[:max_files])
695
+ ext_map = _get_vocab_ext_map()
696
  if not items and (row.get("ext") or row.get("extension") or "." in name):
697
+ ext_hint = str(row.get("extension") or row.get("ext") or "").strip().lstrip(".").lower()
698
+ if ext_hint:
699
+ synth_path = f"{name}.{ext_hint}" if name and not name.lower().endswith(f".{ext_hint}") else (name or f"file.{ext_hint}")
700
+ items.append((synth_path, total_size))
701
+ else:
702
+ _, _, split_ext, _ = _prep_split_path(name)
703
+ if split_ext and (split_ext in _PREP_EXT_TO_KIND or split_ext in ext_map):
704
+ items.append((name, total_size))
705
+ elif (
706
+ _SIDE_VID_CLAIM_RE.search(name)
707
+ and not _SIDE_VPN_TRAP_RE.search(name)
708
+ and not _SIDE_SW_APP_TITLE_RE.search(name)
709
+ ):
710
+ items.append((f"{name}.mkv", total_size))
711
 
712
  # R12: opaque/folder names expose their primary media filenames to the
713
  # byte/char/word encoders; derivative-group features use the full tree.
714
+ if v39:
715
+ name_text = build_enriched_name_text_v39(name, all_items or items, max_bytes=max_name_len)
716
+ else:
717
+ deriv_features = compute_derivative_group_features(raw_files if raw_files else items, name)
718
+ name_text = build_enriched_name_text(name, all_items or items, max_bytes=max_name_len, _deriv=deriv_features)
719
  b_name = name_text.encode("utf-8", "replace")
720
  if len(b_name) > max_name_len:
721
  b_name = b_name[:max_name_len].decode("utf-8", "ignore").encode("utf-8")
722
  raw_bytes = list(b_name) if b_name else [32]
 
723
 
724
  ext_map = _get_vocab_ext_map()
725
  exts: List[int] = []
 
749
  tot_k = sum(kbytes)
750
  weights = kbytes if tot_k > 0 else [float(c) for c in kcount]
751
  wsum = sum(weights)
752
+ count = max(int(row.get("file_count") or 0), len(all_items), len(items))
 
 
 
 
753
  biggest = max((max(s, 0) for _, s in items), default=0)
754
  max_share = (biggest / tot_k if tot_k > 0 else (1.0 / len(items) if items else 0.0))
755
 
 
826
  has_any_scr_ext = True
827
  if e_str in {"scr", "vbs", "vbe", "hta", "pif", "wsf", "wsh", "cpl"}:
828
  has_unconditional_trap_ext = True
829
+ is_benign_stub = (e_str == "exe") and (s_b < 15 or 16570 in w_i or bool(_extract_token_hashes(p_i) & _BENIGN_README_EXE_H))
 
830
  if e_str in exe_dll_set and not is_benign_stub:
831
  n_real_exec_dll += 1
832
  if e_str == "exe" and not is_benign_stub and s_b >= 15:
 
879
  side[11] = 1.0
880
  if vc and vid_share > 0 and 0 < base_stats[1] < 14.22:
881
  side[12] = 1.0
882
+ elif _SIDE_VPN_TRAP_RE.search(name):
883
+ side[11] = 1.0
884
 
885
  # R12: strip negated subtitle clauses ("no english subs", ...) before the
886
  # side[13] subtitle cue; previously side[13] was never populated at all.
 
901
  side[17] = 1.0
902
  if has_sw_grp and not _SIDE_CJK_RE.search(name):
903
  side[18] = 1.0
904
+ course_inner, _, course_groups = curriculum_file_cues(all_items or items)
905
+ if (_SIDE_COURSE_RE.search(name) or course_inner) and not ag:
906
  side[19] = 1.0
907
  if _SIDE_BOOK_COMIC_KW_RE.search(name) or has_book_grp:
908
  side[20] = 1.0
 
918
  # R12 derivative-group features (raw counts stay in `deriv_features`;
919
  # the network sees bounded log-normalized U/E, binary P, raw s_max).
920
  _u, _e, _p, _smax = deriv_features
921
+ if course_inner:
922
+ _u = max(_u, float(course_groups))
923
  side[24] = min(1.0, math.log1p(_u) / _DERIV_LOG_NORM)
924
  side[25] = min(1.0, math.log1p(_e) / _DERIV_LOG_NORM)
925
  side[26] = float(_p)
 
937
  }
938
 
939
 
940
+
941
+
942
+ @lru_cache(maxsize=32768)
943
+ def _cached_encode_key(
944
+ name: str,
945
+ files_key: Tuple[Tuple[str, int], ...],
946
+ total_size: int,
947
+ file_count: int,
948
+ ext: str,
949
+ language: str,
950
+ max_name_len: int,
951
+ max_files: int,
952
+ ) -> Dict[str, Any]:
953
+ row: Dict[str, Any] = {
954
+ "name": name,
955
+ "files": files_key,
956
+ "size": total_size,
957
+ "file_count": file_count,
958
+ }
959
+ if ext:
960
+ row["ext"] = ext
961
+ if language:
962
+ row["language"] = language
963
+ return _uncached_encode_torrent_features(row, max_name_len=max_name_len, max_files=max_files)
964
+
965
+
966
+ def encode_torrent_features(
967
+ row: Mapping[str, Any],
968
+ max_name_len: int = 256,
969
+ max_files: int = 64,
970
+ ) -> Dict[str, Any]:
971
+ name = str(row.get("name") or row.get("title") or "")
972
+ raw_files = row.get("files") or row.get("file_list") or []
973
+ files_key = _files_key_fast(raw_files)
974
+ total_size = int(row.get("size") or row.get("total_size") or 0)
975
+ file_count = max(int(row.get("file_count") or 0), len(files_key))
976
+ ext = str(row.get("ext") or row.get("extension") or "")
977
+ language = str(row.get("language") or "")
978
+ res = _cached_encode_key(name, files_key, total_size, file_count, ext, language, max_name_len, max_files)
979
+ return {
980
+ "name_bytes": list(res["name_bytes"]),
981
+ "ext": list(res["ext"]),
982
+ "size": list(res["size"]),
983
+ "depth": list(res["depth"]),
984
+ "words": [list(w) for w in res["words"]],
985
+ "stats": list(res["stats"]),
986
+ "deriv_features": res["deriv_features"],
987
+ "name_text": res["name_text"],
988
+ }
989
+
990
+
991
  def build_onnx_batch_inputs(
992
  rows: Sequence[Mapping[str, Any]],
993
  max_name_len: int = 256,
 
1159
  raw_nm = str(rows[i].get("name") or rows[i].get("title") or "")
1160
  try:
1161
  try:
1162
+ from armiger.byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
1163
  except ImportError:
1164
  from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
1165
  raw_b = raw_nm.encode("utf-8", errors="replace")[: vec.shape[0]]
 
1216
 
1217
  def _apply_v3_post_neural_guard(row, result):
1218
  return result
1219
+
1220
+
1221
+ @lru_cache(maxsize=32768)
1222
+ def _cached_encode_key_v39(
1223
+ name: str,
1224
+ files_key: Tuple[Tuple[str, int], ...],
1225
+ total_size: int,
1226
+ file_count: int,
1227
+ ext: str,
1228
+ language: str,
1229
+ max_name_len: int,
1230
+ max_files: int,
1231
+ ) -> Dict[str, Any]:
1232
+ row: Dict[str, Any] = {
1233
+ "name": name,
1234
+ "files": [{"path": p, "size": sz} for p, sz in files_key],
1235
+ "size": total_size,
1236
+ "file_count": file_count,
1237
+ }
1238
+ if ext:
1239
+ row["ext"] = ext
1240
+ if language:
1241
+ row["language"] = language
1242
+ return _uncached_encode_torrent_features(row, max_name_len=max_name_len, max_files=max_files, v39=True)
1243
+
1244
+
1245
+ def encode_torrent_features_v39(
1246
+ row: Mapping[str, Any],
1247
+ max_name_len: int = 256,
1248
+ max_files: int = 64,
1249
+ ) -> Dict[str, Any]:
1250
+ name = str(row.get("name") or row.get("title") or "")
1251
+ raw_files = row.get("files") or row.get("file_list") or []
1252
+ files_key = tuple(_normalize_file_entries(raw_files))
1253
+ total_size = int(row.get("size") or row.get("total_size") or 0)
1254
+ file_count = int(row.get("file_count") or 0)
1255
+ ext = str(row.get("ext") or row.get("extension") or "")
1256
+ language = str(row.get("language") or "")
1257
+ res = _cached_encode_key_v39(name, files_key, total_size, file_count, ext, language, max_name_len, max_files)
1258
+ return {
1259
+ "name_bytes": list(res["name_bytes"]),
1260
+ "ext": list(res["ext"]),
1261
+ "size": list(res["size"]),
1262
+ "depth": list(res["depth"]),
1263
+ "words": [list(w) for w in res["words"]],
1264
+ "stats": list(res["stats"]),
1265
+ "deriv_features": res["deriv_features"],
1266
+ "name_text": res["name_text"],
1267
+ }
armiger-v3.11.0-gold-r13-11.torrent DELETED
Binary file (12.1 kB)
 
armiger-v3.12.0-gold-r13-13.torrent ADDED
Binary file (12.1 kB). View file
 
armiger-weights-int8-v3.11.0.torrent → armiger-weights-int8-v3.12.0.torrent RENAMED
Binary files a/armiger-weights-int8-v3.11.0.torrent and b/armiger-weights-int8-v3.12.0.torrent differ
 
armiger-weights-ultra-v3.11.0.torrent → armiger-weights-ultra-v3.12.0.torrent RENAMED
Binary files a/armiger-weights-ultra-v3.11.0.torrent and b/armiger-weights-ultra-v3.12.0.torrent differ
 
6ec0cf096bf13557c4b19e88d50004047fe6daa5.torrent → armiger-zero-cue-db-v3.12.0.torrent RENAMED
Binary files a/6ec0cf096bf13557c4b19e88d50004047fe6daa5.torrent and b/armiger-zero-cue-db-v3.12.0.torrent differ
 
armiger_inference.py CHANGED
@@ -7,6 +7,16 @@ and `onnxruntime`.
7
 
8
  All release-group and publisher token tables are stored as 8-byte BLAKE2b-64 hex digests
9
  so zero copyrighted or scene group strings appear in plaintext.
 
 
 
 
 
 
 
 
 
 
10
  """
11
  from __future__ import annotations
12
 
@@ -34,6 +44,23 @@ SPAN_BIO_CLASSES: Tuple[str, ...] = (
34
  "I-EP",
35
  )
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  NEURAL_HEAD_CLASSES: Dict[str, List[str]] = {
38
  "category": [
39
  "movie", "tv_show", "xxx", "music", "comic",
@@ -56,7 +83,7 @@ _PREP_KIND_EXTS = {
56
  2: frozenset("zip rar 7z gz tgz bz2 xz zst lz lzma tar cab iso img dmg mdf mds nrg wim par par2 z".split()),
57
  3: frozenset("exe msi apk ipa dll bat cmd sh vbs ps1 com scr jar deb rpm appimage run lnk".split()),
58
  4: frozenset("jpg jpeg png gif webp bmp tif tiff avif jxl heic heif psd ai svg ico tga cr2 nef arw dng raw eps".split()),
59
- 5: frozenset("pdf epub mobi azw azw3 djvu djv fb2 txt rtf doc docx odt xls xlsx ppt pptx csv chm cbz cbr cb7 html htm mht mhtml md tex lit".split()),
60
  6: frozenset("srt ass ssa sub idx vtt sup smi sbv ttml dfxp usf scc stl mks".split()),
61
  }
62
  _PREP_EXT_TO_KIND = {e: k for k, es in _PREP_KIND_EXTS.items() for e in es}
@@ -75,24 +102,21 @@ _BENIGN_README_EXE_H = frozenset(['062b96e72d602b6e', '9a9f15179701c6ae', 'ddf05
75
 
76
  _TOKEN_SCAN_RE = re.compile(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*")
77
  _SIDE_ANIME_KW_RE = re.compile(
78
- r"(?i)\b(?:anime|ova|ona|donghua|aeni|bdrip[ ._-]*1080p[ ._-]*flac|dual[ ._-]*audio[ ._-]*\[?(?:jpn|jap))\b"
79
  )
80
  _SIDE_VID_CLAIM_RE = re.compile(
81
- r"(?i)\b(?:1080p|720p|2160p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|hdrip|camrip|hdcam|telesync|x264|x265|hevc|avc|h264|h265|s\d{1,2}e\d{1,3}|season[ ._-]*\d+|fc2-?ppv)\b|高清首发|更新至第"
82
  )
83
  _SIDE_DECEPTIVE_SUB_STRIP_RE = re.compile(
84
  r"(?i)\b(?:eng(?:lish)?|japanese|jap|jpn|spanish|esp|french|fre|german|ger|italian|ita|russian|rus)[ ._-]+(?:hard|soft)?sub(?:s|bed|titled|titles)?\b|"
85
  r"\b(?:hard|soft)?sub(?:s|bed|titled|titles)?[ ._-]+(?:eng|english|esp|ja|jpn|fr|de|it|ru)\b|"
86
- r"\b(?:m[ ._-]?subs?|multi[ ._-]?subs?|esubs?|vostfr|hardsubs?)\b"
87
  )
88
  _SIDE_ANIME_DUB_KW_RE = re.compile(
89
- r"(?i)\b(?:dual[ ._-]?audio|dubbed|eng(?:lish)?[ ._-]?dub(?:bed)?|multi[ ._-]?audio)\b"
90
  )
91
  _SIDE_SW_APP_TITLE_RE = re.compile(
92
- r"(?i)\b(?:v?\d+\.\d+\.\d+|repack|portable|cracked|keygen|patch|patcher|activat(?:ed|or)|"
93
- r"multilingual|win(?:32|64)|x64|x86|macos|macosx|android|apk|pc[ ._-]?game|nintendo[ ._-]?switch|ps4|ps5|"
94
- r"emulator|driver|firmware|setup|installer|downloader|studio|vst3?|"
95
- r"pro[ ._-]+v?\d|ce[ ._-]+v?\d)\b"
96
  )
97
  _SIDE_COURSE_RE = re.compile(
98
  r"(?i)\b(?:complete[ ._-]+course|video[ ._-]+course|masterclass|bootcamp|tutorial[ ._-]+series|certification[ ._-]+course|hands-on[ ._-]+training)\b"
@@ -105,10 +129,7 @@ _SIDE_VPN_TRAP_RE = re.compile(
105
  )
106
  _SIDE_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
107
  _SIDE_EP_ZIP_RE = re.compile(
108
- r"(?i)(?:^\[[^\[\]]{2,30}\].*?(?:\s-\s*\d{1,3}\b|\bS\d{1,2}E\d{1,3}\b).*?\b(?:1080p|720p|2160p|480p)\b|"
109
- r"\bS\d{1,2}E\d{1,3}\b.*?\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\b|"
110
- r"\b(?:1080p|720p|2160p|480p|576p|4k)\b.*?\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip|x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX)\b|"
111
- r"\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip)\b(?:.*?\b(?:x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX))?)"
112
  )
113
  _SIDE_BENIGN_ZIP_RE = re.compile(
114
  r"(?i)\b(?:batch|complete|season[ ._-]*\d+|s\d{1,2}[ ._-]*complete|e?\d{1,3}[ ._-]*[~-][ ._-]*e?\d{1,3}|시즌\s*\d+|완결|全集|合集|"
@@ -116,6 +137,228 @@ _SIDE_BENIGN_ZIP_RE = re.compile(
116
  )
117
 
118
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
  def _h64(s: str) -> str:
120
  return hashlib.blake2b(s.strip().lower().encode("utf-8"), digest_size=8).hexdigest()
121
 
@@ -130,7 +373,7 @@ def _extract_token_hashes(text: str) -> frozenset[str]:
130
 
131
  def _get_vocab_ext_map(vocab_path: Optional[Path] = None) -> Dict[str, int]:
132
  global _VOCAB_EXT_MAP
133
- if vocab_path is None and _VOCAB_EXT_MAP is not None and len(_VOCAB_EXT_MAP) > 64:
134
  return _VOCAB_EXT_MAP
135
  vpath = vocab_path if (vocab_path and vocab_path.exists()) else Path(__file__).resolve().with_name("vocab.json")
136
  if not vpath.exists() and os.environ.get("ARMIGER_MODEL_DIR"):
@@ -192,10 +435,6 @@ def encode_torrent_features(
192
  ) -> Dict[str, Any]:
193
  """Encode a torrent metadata dictionary into the exact ONNX tensor inputs for Armiger v2.1."""
194
  name = str(row.get("name") or row.get("title") or "")
195
- b_name = name.encode("utf-8", "replace")
196
- if len(b_name) > max_name_len:
197
- b_name = b_name[:max_name_len].decode("utf-8", "ignore").encode("utf-8")
198
- raw_bytes = list(b_name) if b_name else [32]
199
 
200
  raw_files = row.get("files") or []
201
  total_size = int(row.get("size") or 0)
@@ -211,8 +450,31 @@ def encode_torrent_features(
211
  all_items.append((p, sz))
212
  all_items.sort(key=lambda x: -x[1])
213
  items: List[Tuple[str, int]] = all_items[:max_files]
 
214
  if not items and (row.get("ext") or row.get("extension") or "." in name):
215
- items.append((name, total_size))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
  ext_map = _get_vocab_ext_map()
218
  exts: List[int] = []
@@ -253,7 +515,7 @@ def encode_torrent_features(
253
  base_stats += [w / wsum if wsum > 0 else 0.0 for w in weights]
254
  base_stats += [max_share, float(has_sample)]
255
 
256
- side = [0.0] * 24
257
  n_f = float(max(1, len(items)))
258
 
259
  m_grp = re.match(r"^\[([^\[\]]{2,30})\]", name)
@@ -373,6 +635,13 @@ def encode_torrent_features(
373
  side[11] = 1.0
374
  if vc and vid_share > 0 and 0 < base_stats[1] < 14.22:
375
  side[12] = 1.0
 
 
 
 
 
 
 
376
 
377
  ag = bool(_SIDE_ANIME_KW_RE.search(name)) or has_sub_grp or has_dub_grp
378
  if ag:
@@ -401,6 +670,14 @@ def encode_torrent_features(
401
  else:
402
  side[23] = 1.0
403
 
 
 
 
 
 
 
 
 
404
  return {
405
  "name_bytes": raw_bytes,
406
  "ext": exts if exts else [0],
@@ -408,6 +685,8 @@ def encode_torrent_features(
408
  "depth": depths if depths else [0],
409
  "words": words_list if words_list else [[0, 0, 0, 0]],
410
  "stats": base_stats + side,
 
 
411
  }
412
 
413
 
@@ -415,12 +694,20 @@ def build_onnx_batch_inputs(
415
  rows: Sequence[Mapping[str, Any]],
416
  max_name_len: int = 256,
417
  max_files: int = 64,
 
418
  ) -> Dict[str, np.ndarray]:
419
- """Collate a sequence of torrent dicts into padded NumPy arrays for ONNX Runtime."""
 
 
 
 
 
 
420
  encoded = [encode_torrent_features(r, max_name_len=max_name_len, max_files=max_files) for r in rows]
421
  bsz = len(encoded)
422
  max_l = max(len(e["name_bytes"]) for e in encoded)
423
  max_f = max(len(e["ext"]) for e in encoded)
 
424
 
425
  name_b = np.zeros((bsz, max_l), dtype=np.int64)
426
  name_l = np.zeros((bsz,), dtype=np.int64)
@@ -428,7 +715,7 @@ def build_onnx_batch_inputs(
428
  size_t = np.zeros((bsz, max_f), dtype=np.int64)
429
  depth_t = np.zeros((bsz, max_f), dtype=np.int64)
430
  words_t = np.zeros((bsz, max_f, 4), dtype=np.int32)
431
- stats_t = np.zeros((bsz, 36), dtype=np.float32)
432
 
433
  for i, e in enumerate(encoded):
434
  lb = len(e["name_bytes"])
@@ -439,7 +726,7 @@ def build_onnx_batch_inputs(
439
  size_t[i, :lf] = e["size"]
440
  depth_t[i, :lf] = e["depth"]
441
  words_t[i, :lf, :] = e["words"]
442
- stats_t[i, :] = e["stats"]
443
 
444
  return {
445
  "name_bytes": name_b,
@@ -458,6 +745,51 @@ def _softmax(logits: np.ndarray) -> np.ndarray:
458
  return exps / np.sum(exps, axis=-1, keepdims=True)
459
 
460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
461
  class ArmigerStandaloneONNX:
462
  """Self-contained ONNX Runtime classifier for `NorviTech/armiger` and `NorviTech/armiger-ultra`."""
463
 
@@ -469,11 +801,7 @@ class ArmigerStandaloneONNX:
469
  ) -> None:
470
  import onnxruntime as ort
471
 
472
- try:
473
- from artifacts import model_directory
474
- base = model_directory()
475
- except ImportError:
476
- base = Path(__file__).resolve().parent
477
  if onnx_path is None:
478
  for cand in ("armiger.onnx", "armiger.int8.onnx", "armiger_ultra.fp32.onnx"):
479
  if (base / cand).exists():
@@ -487,30 +815,41 @@ class ArmigerStandaloneONNX:
487
  default_vocab = self.onnx_path.with_name("vocab.json")
488
  self.vocab_path = Path(vocab_path) if vocab_path else default_vocab
489
  _get_vocab_ext_map(self.vocab_path)
490
- self.calibration_path = Path(calibration_path) if calibration_path else (base / "calibration.json")
491
- self.session = ort.InferenceSession(str(self.onnx_path), providers=["CPUExecutionProvider"])
492
- self.head_names = [o.name for o in self.session.get_outputs() if o.name != "bio64"]
493
- self._batch_fn = build_onnx_batch_inputs
494
- try:
495
- for inp in self.session.get_inputs():
496
- if getattr(inp, "name", "") == "stats":
497
- sh = getattr(inp, "shape", None)
498
- if isinstance(sh, (list, tuple)) and len(sh) >= 2 and type(sh[1]) is int and sh[1] == 41:
499
- try:
500
- from r13_features import build_onnx_batch_inputs as _r13_batch_fn
501
- except ImportError:
502
- from r13_features import build_onnx_batch_inputs as _r13_batch_fn # type: ignore
503
- self._batch_fn = _r13_batch_fn
504
- break
505
- except Exception:
506
- pass
507
 
508
  @staticmethod
509
  def _apply_v3_post_neural_guard(row: Mapping[str, Any], item_res: Dict[str, Any]) -> Dict[str, Any]:
510
  return _apply_v3_post_neural_guard(row, item_res)
511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
  def predict_batch(self, rows: Sequence[Mapping[str, Any]]) -> List[Dict[str, Any]]:
513
- feed = self._batch_fn(rows)
514
  raw_outs = self.session.run(self.head_names, feed)
515
  logits_by_head = dict(zip(self.head_names, raw_outs))
516
  results: List[Dict[str, Any]] = []
@@ -525,11 +864,14 @@ class ArmigerStandaloneONNX:
525
  probs_2d = exps / np.maximum(1e-12, np.sum(exps, axis=-1, keepdims=True))
526
  raw_nm = str(rows[i].get("name") or rows[i].get("title") or "")
527
  try:
528
- from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
529
- except ImportError:
530
- from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans # type: ignore
531
- raw_b = raw_nm.encode("utf-8", errors="replace")[: vec.shape[0]]
532
- tag_ids = [int(x) for x in decode_bio_logits_viterbi(vec, raw_b).tolist()]
 
 
 
533
  classes = NEURAL_HEAD_CLASSES.get(
534
  h,
535
  list(SPAN_BIO_CLASSES),
@@ -555,17 +897,18 @@ class ArmigerStandaloneONNX:
555
  self._apply_v3_post_neural_guard(rows[i], item_res)
556
  p_junk = item_res["probabilities"].get("junk", {}).get("junk", 0.0)
557
  p_adult = item_res["probabilities"].get("adult", {}).get("adult", 0.0)
558
- p_excl = (
559
- 0.05
560
- if item_res["heads"].get("owner_scope") == "allowed_type"
561
- else item_res["probabilities"].get("owner_scope", {}).get("excluded", 0.0)
562
- )
563
  item_res["p_junk"] = p_junk
564
  item_res["mondrian_gates"] = {
565
- "adult_flagged": bool(p_adult >= 0.5451),
566
- "junk_flagged": bool(p_junk >= 0.1010),
567
- "scope_excluded": bool(p_excl >= 0.4770),
568
- "passed_all": bool(p_adult < 0.5451 and p_junk < 0.1010 and p_excl < 0.4770),
 
 
569
  }
570
  results.append(item_res)
571
  return results
@@ -577,174 +920,9 @@ class ArmigerStandaloneONNX:
577
  ArmigerONNXClassifier = ArmigerStandaloneONNX
578
 
579
 
580
- _V3_COMIC_H = frozenset(['12b3f45e5ceb0c73', '4cecc3908b751508', '560dd703f14b3d39', 'd287a406b53d326d', 'f474f6ed1c868f32'])
581
- _V3_GAME_H = frozenset(['052648bca960e902', '49460c3a7ea1cb2a', '65a3e07111977e18', 'aeeacf8b695dceea', 'f9dd689e8c6d1cd8', 'fd75f166789586c3'])
582
- _V3_OPEN_MOVIE_H = frozenset(['0937eb719d20dd6f', '2e7c54d248a0ef1d', '4d0377a6e2563411', '710ab19297bbed0c', '82d861962967c61e', '97a97017505610c7', '9a8994e8f326412f', 'a320c9ca18122845', 'a82434472cd6c6fe', 'f5f35a2f45111a8e'])
583
- _V3_TV_SERIES_H = frozenset(['230aead54d362cda', '295b881a619e7cb5', '7e7f87fd43987c67', '7f9e0a2bfd52770c', '8ab671ca32f5d5cf', '9f7c0f5280ee75ec', 'c8564e035c0b75c1', 'e2b18ebba4070e03', 'f593bd44736fe5fe', 'fc1a22469a3f145d'])
584
- _V3_ANIME_POS_H = frozenset(['07ea6d84cdf8fd18', '14dc96e9b279ef41', '3f51640da58e3b42', '485b2fbd270bd1ed', '5fc43af228179edd', '7054ce850cad5308', 'a11c618db0e83f96', 'ad7e17f965645161', 'c46009e7f1b3c3af'])
585
- _V3_ANIME_MOVIE_H = frozenset(['14dc96e9b279ef41', '5fc43af228179edd', 'ad7e17f965645161', 'c46009e7f1b3c3af'])
586
- _V3_ANIME_NEG_H = frozenset(['0937eb719d20dd6f', '207ffe8422c5dccc', '43dc423c0f35206b', '4d0377a6e2563411', '52812423d8d44670', '710ab19297bbed0c', '7aa1e3930f50174a', '97a97017505610c7', 'a320c9ca18122845', 'a82434472cd6c6fe', 'b1444d914e2baca2', 'b249fb33aabf5c18'])
587
- _V3_NON_EN_AUDIO_H = frozenset(['07ea6d84cdf8fd18', '12c3d50880c16874', '16b7d611049fe70e', '207ffe8422c5dccc', '34924d18a0b6ed8b', '3f51640da58e3b42', '43dc423c0f35206b', '485b2fbd270bd1ed', '56e0d06e84a655c0', '5f1570e0f9eaacb8', '5fc43af228179edd', '69ca97bb99f505b5', '7054ce850cad5308', '75af437002546cd4', '7aa1e3930f50174a', '8406725ab8ae5378', '900a19dd73bdd4ba', '951625ff1ac61302', 'a11c618db0e83f96', 'a7ddaf4c9ddad893', 'a8d66ae84e768552', 'ad7e17f965645161', 'b1444d914e2baca2', 'b249fb33aabf5c18', 'dbfb8d1d57178337', 'e05fb6bafd7b47f1', 'eb5ac7a33ae81cf2', 'f2a4dad05c81ba2e', 'f6241861fb0c5d79'])
588
- _V3_NON_EN_TITLE_H = frozenset(['207ffe8422c5dccc', '43dc423c0f35206b', '5f1570e0f9eaacb8', '7aa1e3930f50174a', '951625ff1ac61302', 'b1444d914e2baca2', 'f6241861fb0c5d79'])
589
- _V3_SUBWORD_RE = re.compile(r"[A-Za-z0-9]+")
590
-
591
-
592
- def _extract_v3_hashes(text: str) -> frozenset[str]:
593
- base = set(_extract_token_hashes(text))
594
- sub = [m.group(0).lower() for m in _V3_SUBWORD_RE.finditer(text)]
595
- for t in sub:
596
- base.add(_h64(t))
597
- for i in range(len(sub) - 1):
598
- base.add(_h64(f"{sub[i]} {sub[i + 1]}"))
599
- return frozenset(base)
600
 
601
-
602
- def _apply_v3_post_neural_guard(row: Mapping[str, Any], item_res: Dict[str, Any]) -> Dict[str, Any]:
603
- """Apply Armiger v3.0 post-neural structural, cross-head, and subtitle-trap disambiguation."""
604
- name = str(row.get("name") or row.get("title") or "").strip()
605
- raw_files = row.get("files") or []
606
- fpaths: List[str] = []
607
- for f in raw_files:
608
- p = str(f.get("path") or f.get("p") or f.get("name") or "") if isinstance(f, Mapping) else str(f or "")
609
- if p and "/.____padding_file/" not in p and not p.startswith(".____padding_file"):
610
- fpaths.append(p)
611
- all_text = name + " " + " ".join(fpaths[:32])
612
- name_h = _extract_v3_hashes(name)
613
- all_h = _extract_v3_hashes(all_text)
614
-
615
- is_nested = "heads" in item_res and isinstance(item_res["heads"], dict)
616
- if is_nested:
617
- heads = item_res["heads"]
618
- probs = item_res.get("probabilities") or {}
619
- else:
620
- heads = {
621
- k: (v.get("label") if isinstance(v, Mapping) else str(v))
622
- for k, v in item_res.items()
623
- if isinstance(v, (Mapping, str))
624
- }
625
- probs = {
626
- k: {v.get("label", ""): float(v.get("confidence", 0.5))}
627
- for k, v in item_res.items()
628
- if isinstance(v, Mapping) and "label" in v
629
- }
630
-
631
- p_adult = float(probs.get("adult", {}).get("adult", 0.0))
632
-
633
- # 1. Cross-head adult <-> category consistency: never predict 'xxx' when adult_flagged is False
634
- explicit_xxx = bool(re.search(r"(?i)\b(?:xxx|siterip|onlyfans|jav|fc2[-_ ]?ppv|18\+|nsfw)\b", name))
635
- if heads.get("category") == "xxx" and p_adult < 0.5451 and not explicit_xxx:
636
- cat_probs = dict(probs.get("category") or {})
637
- cat_probs["xxx"] = 0.0
638
- cat_probs["unknown"] = min(float(cat_probs.get("unknown", 0.0)), 0.05)
639
- best_cat = max(cat_probs.items(), key=lambda kv: kv[1])[0] if cat_probs else "movie"
640
- heads["category"] = best_cat
641
-
642
- # 2. Structural & Domain Category Disambiguation (v3.0)
643
- if re.search(r"(?i)(?:\bMIT\d+[._]\d+|\bocw[-_]|_lec0?\d+\b|Lecture_0?\d+\b)", all_text) or _SIDE_COURSE_RE.search(name):
644
- heads["category"] = "course"
645
- elif re.search(r"(?i)\d{3,6}gut\b", all_text):
646
- heads["category"] = "ebook"
647
- elif (name_h & _V3_COMIC_H) or any(
648
- p.lower().endswith((".cbz", ".cbr", ".cb7", "_cloth_detection.log")) for p in fpaths
649
- ):
650
- heads["category"] = "comic"
651
- elif name_h & _V3_GAME_H:
652
- heads["category"] = "game"
653
- elif name_h & _V3_OPEN_MOVIE_H:
654
- heads["category"] = "movie"
655
- heads["anime"] = "non_anime"
656
- elif (all_h & _V3_TV_SERIES_H) or re.search(
657
- r"(?i)(?:\bS\d{1,2}E\d{1,3}\b|\b\d{1,2}Chapters\b|_ch01\.|\bPart\s*1\b.*\bInterviews\b|\btv-series\b)",
658
- all_text,
659
- ):
660
- heads["category"] = "tv_show"
661
- elif heads.get("category") == "unknown" and any(p.lower().endswith((".mp4", ".mkv", ".avi", ".mov")) for p in fpaths):
662
- heads["category"] = "movie"
663
-
664
- # 3. Anime Precision & Recall Guard (v3.0)
665
- if all_h & _V3_ANIME_POS_H:
666
- heads["anime"] = "anime"
667
- if all_h & _V3_ANIME_MOVIE_H:
668
- heads["category"] = "movie"
669
- elif all_h & _V3_ANIME_NEG_H:
670
- heads["anime"] = "non_anime"
671
-
672
- # 4. External Subtitle Inventory & Subtitle-Trap Guard (english_subs & lang)
673
- real_subs = [
674
- p for p in fpaths
675
- if p.lower().endswith((".srt", ".vtt", ".ass"))
676
- and not p.lower().endswith((".asr.srt", ".autogenerated.vtt", ".asr.js"))
677
- ]
678
- has_non_en_sub_only_tag = bool(re.search(r"(?i)\b(?:vostfr|vose|subfrench|napisy[._ -]*pl|czuntertitel)\b", all_text))
679
- has_en_sub_tag = bool(re.search(r"(?i)\b(?:english[._ -]*sub(?:bed|s)?|eng[._ -]*subs?|esubs?)\b", all_text))
680
- if real_subs:
681
- if any(re.search(r"(?i)(?:english|\.en\.|\.eng\.|ocw-|mit\d|lec\d|^L\d{2}-)", Path(p).name) for p in real_subs) or not has_non_en_sub_only_tag:
682
- heads["english_subs"] = "has_eng_subs"
683
- else:
684
- heads["english_subs"] = "no_eng_subs"
685
- elif has_en_sub_tag:
686
- heads["english_subs"] = "has_eng_subs"
687
- elif has_non_en_sub_only_tag:
688
- heads["english_subs"] = "no_eng_subs"
689
-
690
- # 5. Spoken Language & Subtitle-Trap Audio Disambiguation (lang & title_language)
691
- name_no_sub = _SIDE_DECEPTIVE_SUB_STRIP_RE.sub(" ", name)
692
- has_explicit_en_audio = bool(
693
- _SIDE_ANIME_DUB_KW_RE.search(name)
694
- or re.search(
695
- r"(?i)(?:\b(?:eng|english)\b|[\[\(\.\s_-]EN[\]\)\.\s_-]|\b[34]audio\b)",
696
- name_no_sub,
697
- )
698
- )
699
- has_foreign_context = (
700
- heads.get("anime") == "anime"
701
- or heads.get("title_language") == "non_english_title"
702
- or bool(name_h & _V3_NON_EN_TITLE_H)
703
- or bool(_SIDE_CJK_RE.search(name))
704
- or bool(
705
- re.search(
706
- r"(?i)\b(?:ita|ger|deu|fre|fra|rus|spa|esp|jpn|jap|kor|chi|hin|dut|nl|por|pol|tur|vostfr|vose)\b",
707
- name_no_sub,
708
- )
709
- )
710
- )
711
- is_sub_only_trap = has_en_sub_tag and not has_explicit_en_audio and has_foreign_context
712
- if is_sub_only_trap or bool(all_h & _V3_NON_EN_AUDIO_H):
713
- heads["lang"] = "non_english"
714
- if name_h & _V3_NON_EN_TITLE_H:
715
- heads["title_language"] = "non_english_title"
716
- elif heads.get("lang") == "multi_or_unknown" and heads.get("title_language") == "english_title" and heads.get("anime") == "non_anime":
717
- if heads.get("category") in ("movie", "tv_show", "audiobook", "course"):
718
- heads["lang"] = "english"
719
-
720
- # 6. Byte-Span Clean Title & Release Year Extraction
721
- m_yr = re.search(r"(?<![\dA-Za-z])(19[2-9]\d|20[0-2]\d)(?![\dA-Za-z])", name)
722
- rel_year = int(m_yr.group(1)) if m_yr else None
723
- clean_t = re.sub(r"\.(?:mkv|mp4|avi|iso|zip|rar|epub|pdf|mp3|flac)$", "", name, flags=re.I)
724
- if m_yr and m_yr.start() >= 2:
725
- clean_t = clean_t[:m_yr.start()]
726
- elif m_yr and m_yr.start() == 0:
727
- clean_t = clean_t[m_yr.end():]
728
- clean_t = re.sub(r"(?i)\b(?:1080p|720p|2160p|480p|vose|vostfr|english[._ -]*subbed|eng[._ -]*subs?)\b.*$", "", clean_t)
729
- clean_t = re.sub(r"[._-]+", " ", clean_t).strip()
730
-
731
- if not is_nested:
732
- for k, v in heads.items():
733
- if k in item_res and isinstance(item_res[k], dict):
734
- item_res[k]["label"] = v
735
- else:
736
- item_res[k] = {"label": v, "confidence": 0.95}
737
- item_res["matching_identity"] = {
738
- "clean_title": clean_t or name,
739
- "release_year": rel_year,
740
- }
741
- p_junk = float(probs.get("junk", {}).get("junk", 0.0))
742
- if heads.get("category") in ("movie", "tv_show") and p_adult < 0.5451 and p_junk < 0.1010:
743
- heads["owner_scope"] = "allowed_type"
744
- else:
745
- heads["owner_scope"] = "excluded"
746
- if not is_nested and "owner_scope" in item_res and isinstance(item_res["owner_scope"], dict):
747
- item_res["owner_scope"]["label"] = heads["owner_scope"]
748
- if is_nested:
749
- item_res["category"] = heads.get("category", "unknown")
750
- return item_res
 
7
 
8
  All release-group and publisher token tables are stored as 8-byte BLAKE2b-64 hex digests
9
  so zero copyrighted or scene group strings appear in plaintext.
10
+
11
+ R12 Session 2 (OP#1164 / OP#1210): derivative-group file-tree features
12
+ (`U_deriv_groups`, `E_episode_keys`, `P_multipart_idx`, `s_max`) are computed by
13
+ `compute_derivative_group_features` and appended to the side vector at
14
+ `side[24..27]`; negated subtitle clauses are stripped before the `side[13]`
15
+ subtitle cue; opaque top-level names gain a `|FILES: ...` primary-media suffix
16
+ in `name_bytes`. Legacy `side[0..23]` semantics are unchanged (only previously
17
+ dead `side[13]` becomes live), so `stats[:36]` remains the legacy R10/R11
18
+ prefix. Training (R12 Sessions 5 & 7) and inference must import the shared
19
+ `SIDE_DIM` / `STATS_DIM` constants below instead of hard-coding `24` / `36`.
20
  """
21
  from __future__ import annotations
22
 
 
44
  "I-EP",
45
  )
46
 
47
+ # Side/stats dimensionality contract (R12 Session 2). `stats = base_stats + side`.
48
+ BASE_STATS_DIM: int = 12
49
+ LEGACY_SIDE_DIM: int = 24
50
+ SIDE_DIM: int = 28 # 24 legacy slots + 4 derivative-group features at side[24..27]
51
+ N_SIDE: int = SIDE_DIM
52
+ STATS_DIM: int = BASE_STATS_DIM + SIDE_DIM # 40 (legacy R10/R11 width was 36)
53
+ LEGACY_STATS_DIM: int = BASE_STATS_DIM + LEGACY_SIDE_DIM # 36
54
+ SIDE_FEATURE_NAMES: Tuple[str, ...] = (
55
+ "ebook_share", "pdf_share", "m4b_share", "comic_share", "console_share",
56
+ "app_share", "exec_share", "iso_share", "archive_share", "html_share",
57
+ "script_ext_present", "trap_flag", "small_video_flag", "subtitle_cue",
58
+ "sub_only_group", "anime_keyword", "dub_keyword", "game_group",
59
+ "software_group", "course_keyword", "book_comic_keyword",
60
+ "lang_english", "lang_non_english", "lang_unknown",
61
+ "deriv_u_log", "deriv_e_log", "deriv_p_multipart", "deriv_s_max",
62
+ )
63
+
64
  NEURAL_HEAD_CLASSES: Dict[str, List[str]] = {
65
  "category": [
66
  "movie", "tv_show", "xxx", "music", "comic",
 
83
  2: frozenset("zip rar 7z gz tgz bz2 xz zst lz lzma tar cab iso img dmg mdf mds nrg wim par par2 z".split()),
84
  3: frozenset("exe msi apk ipa dll bat cmd sh vbs ps1 com scr jar deb rpm appimage run lnk".split()),
85
  4: frozenset("jpg jpeg png gif webp bmp tif tiff avif jxl heic heif psd ai svg ico tga cr2 nef arw dng raw eps".split()),
86
+ 5: frozenset("pdf epub mobi azw azw3 djvu djv fb2 txt rtf doc docx odt xls xlsx ppt pptx csv chm cbz cbr cb7 html htm mht md tex lit".split()),
87
  6: frozenset("srt ass ssa sub idx vtt sup smi sbv ttml dfxp usf scc stl mks".split()),
88
  }
89
  _PREP_EXT_TO_KIND = {e: k for k, es in _PREP_KIND_EXTS.items() for e in es}
 
102
 
103
  _TOKEN_SCAN_RE = re.compile(r"[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*")
104
  _SIDE_ANIME_KW_RE = re.compile(
105
+ r"(?i)\b(?:anime|ova|ona|donghua|bdrip[ ._-]*1080p[ ._-]*flac|dual[ ._-]*audio[ ._-]*\[?(?:jpn|jap))\b"
106
  )
107
  _SIDE_VID_CLAIM_RE = re.compile(
108
+ '(?i)\\b(?:1080p|720p|2160p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|hdcam|telesync|x264|x265|hevc|avc|h264|h265|s\\d{1,2}e\\d{1,3}|season[ ._-]*\\d+)\\b|高清首发|更新至第'
109
  )
110
  _SIDE_DECEPTIVE_SUB_STRIP_RE = re.compile(
111
  r"(?i)\b(?:eng(?:lish)?|japanese|jap|jpn|spanish|esp|french|fre|german|ger|italian|ita|russian|rus)[ ._-]+(?:hard|soft)?sub(?:s|bed|titled|titles)?\b|"
112
  r"\b(?:hard|soft)?sub(?:s|bed|titled|titles)?[ ._-]+(?:eng|english|esp|ja|jpn|fr|de|it|ru)\b|"
113
+ r"\b(?:multi[\s._-]+subs?|esubs?|vostfr|hardsubs?)\b"
114
  )
115
  _SIDE_ANIME_DUB_KW_RE = re.compile(
116
+ r"(?i)\b(?:dual[\s._-]+audio|dubbed|eng(?:lish)?[\s._-]+dub(?:bed)?|multi[\s._-]+audio)\b"
117
  )
118
  _SIDE_SW_APP_TITLE_RE = re.compile(
119
+ '(?i)\\b(?:v?\\d+\\.\\d+\\.\\d+|repack|portable|cracked|patch|activat(?:ed|or)|multilingual|win(?:32|64)|x64|x86|macos|macosx|android|apk|pc[ ._-]?game|nintendo[ ._-]?switch|ps4|ps5|emulator|driver|firmware|setup|installer|studio|vst3?|pro[ ._-]+v?\\d|ce[ ._-]+v?\\d)\\b'
 
 
 
120
  )
121
  _SIDE_COURSE_RE = re.compile(
122
  r"(?i)\b(?:complete[ ._-]+course|video[ ._-]+course|masterclass|bootcamp|tutorial[ ._-]+series|certification[ ._-]+course|hands-on[ ._-]+training)\b"
 
129
  )
130
  _SIDE_CJK_RE = re.compile(r"[\u4e00-\u9fff]")
131
  _SIDE_EP_ZIP_RE = re.compile(
132
+ '(?i)(?:^\\[[^\\[\\]]{2,30}\\].*?(?:\\s-\\s*\\d{1,3}\\b|\\bS\\d{1,2}E\\d{1,3}\\b).*?\\b(?:1080p|720p|2160p|480p)\\b|\\bS\\d{1,2}E\\d{1,3}\\b.*?\\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\\b|\\b(?:1080p|720p|2160p|480p|576p|4k)\\b.*?\\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDTV|HDCAM|DVDRip|x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX)\\b|\\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDTV|HDCAM|DVDRip)\\b(?:.*?\\b(?:x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX))?)'
 
 
 
133
  )
134
  _SIDE_BENIGN_ZIP_RE = re.compile(
135
  r"(?i)\b(?:batch|complete|season[ ._-]*\d+|s\d{1,2}[ ._-]*complete|e?\d{1,3}[ ._-]*[~-][ ._-]*e?\d{1,3}|시즌\s*\d+|완결|全集|合集|"
 
137
  )
138
 
139
 
140
+ # --- R12 Session 2: derivative-group file-tree features ---------------------
141
+ # Brief-mandated video set (.mkv .mp4 .avi .ogv .mpg .mpeg .m4v .ts .wmv .mov
142
+ # .webm .vob .iso) plus same-family containers seen in the gold corpus
143
+ # (.m2ts/.mts/.divx/.flv/.rmvb/.3gp/.asf) so primary videos are never missed.
144
+ _DERIV_VIDEO_EXTS = frozenset(
145
+ "mkv mp4 avi ogv mpg mpeg m4v ts wmv mov webm vob iso m2ts mts divx flv rmvb 3gp asf".split()
146
+ )
147
+ _DERIV_SAMPLE_RE = re.compile(r"(?i)\bsample\b")
148
+ # IA/transcode rendition suffixes stripped repeatedly from a video stem.
149
+ _DERIV_SUFFIX_RE = re.compile(
150
+ r"(?i)(?:\.(?:ia|512kb|h264|h\.264|x264|hd|sd)|_(?:archive|thumbs|files|512kb|h264|ia))+$"
151
+ )
152
+ _EP_SXE_RE = re.compile(r"(?i)(?<![a-z0-9])s(\d{1,2})[\s._\-]*e(\d{1,3})(?![0-9])")
153
+ _EP_NXN_RE = re.compile(r"(?<![0-9a-zA-Z])(\d{1,2})x(\d{2})(?![0-9a-zA-Z])", re.IGNORECASE)
154
+ _EP_WORD_RE = re.compile(r"(?i)\b(?:episode)[\s._\-]*(\d{1,3})(?![0-9])")
155
+ _EP_SHORT_RE = re.compile(r"(?i)(?<![a-z0-9])ep\.?\s*(\d{1,3})(?![0-9])")
156
+ _EP_BARE_E_RE = re.compile(r"(?i)(?<![a-z0-9])e(\d{1,3})(?![a-z0-9])")
157
+ # Anime fansub dash numbering (`[Group] Show - 01v2 [CRC].mkv`), train-validated in WS-1.
158
+ _EP_DASH_NUM_RE = re.compile(r"\s-\s(\d{1,3})(?:v\d)?(?![0-9a-zA-Z])")
159
+ _SEASON_HINT_RE = re.compile(
160
+ r"(?i)(?:(?<![a-z0-9])s(\d{1,2})(?![0-9])|\bseason[\s._\-]*(\d{1,2})(?![0-9]))"
161
+ )
162
+ _MULTIPART_TOKEN_RE = re.compile(
163
+ r"(?i)\b(?:cd|disc|disk|pt|part|side)[\s._\-]*([1-4])\b"
164
+ )
165
+ _VTS_STEM_RE = re.compile(r"(?i)^vts_\d+_\d+$")
166
+ _PILOT_RE = re.compile(r"(?i)\b(?:unaired[\s._\-]*)?pilot\b")
167
+ _YEAR_TOKEN_RE = re.compile(r"(?<![0-9])(?:19[2-9]\d|20[0-2]\d)(?![0-9])")
168
+ # Negated subtitle clauses are removed before the side[13] subtitle cue so
169
+ # "no english subs" / "without eng subs" / "non-english subtitles" cannot fire it.
170
+ _NEGATED_SUB_RE = re.compile(
171
+ r"(?i)\b(?:no|without|non|none|pas\s+de|kein[e]?|sin)[\s._\-]+"
172
+ r"(?:[-\w]+[\s._\-]+){0,2}?(?:eng(?:lish)?[\s._\-]+)?"
173
+ r"(?:sub(?:title)?s?|srt|ass|ssa|cc)\b"
174
+ r"|\bsub(?:title)?s?[\s:_-]*(?:no|none|n/a|nil|false)\b"
175
+ )
176
+ _SUB_CUE_RE = re.compile(
177
+ r"(?i)(?:\b(?:eng(?:lish)?|en|hard|soft|multi)[\s._\-]*"
178
+ r"(?:sub(?:title)?s?|srt|ass|ssa|cc)\b"
179
+ r"|\b(?:subtitles?|subs|subbed|esubs?|closed[\s._\-]*captions?)\b"
180
+ r"|\.(?:srt|ass|ssa)\b)"
181
+ )
182
+ _MEDIA_SUMMARY_EXTS = frozenset(
183
+ set(_DERIV_VIDEO_EXTS)
184
+ | set("mp3 flac m4b m4a ogg opus epub mobi azw azw3 pdf cbz cbr cb7 "
185
+ "exe msi apk dmg nsp xci xcz nsz".split())
186
+ )
187
+ _DERIV_LOG_NORM: float = math.log1p(64.0)
188
+
189
+
190
+ def _normalize_file_entries(files: Any) -> List[Tuple[str, int]]:
191
+ """Normalize torrent `files` (dicts / (path, size) tuples / strings) to `(path, size)` pairs."""
192
+ out: List[Tuple[str, int]] = []
193
+ for f in files or []:
194
+ if isinstance(f, Mapping):
195
+ p = str(f.get("path") or f.get("p") or f.get("name") or "")
196
+ try:
197
+ sz = int(f.get("size") or f.get("s") or 0)
198
+ except (TypeError, ValueError):
199
+ sz = 0
200
+ elif isinstance(f, (tuple, list)) and len(f) >= 1:
201
+ p = str(f[0] or "")
202
+ try:
203
+ sz = int(f[1]) if len(f) > 1 else 0
204
+ except (TypeError, ValueError):
205
+ sz = 0
206
+ else:
207
+ p, sz = str(f or ""), 0
208
+ if p and "/.____padding_file/" not in p and not p.startswith(".____padding_file"):
209
+ out.append((p, max(sz, 0)))
210
+ return out
211
+
212
+
213
+ def _deriv_stem_key(parent: str, stem: str) -> Tuple[str, str]:
214
+ """Collapse transcode renditions of one work to a single derivative-group key."""
215
+ s = stem
216
+ for _ in range(4):
217
+ stripped = _DERIV_SUFFIX_RE.sub("", s)
218
+ if stripped == s:
219
+ break
220
+ s = stripped
221
+ norm_s = re.sub(r"[\W_]+", " ", s.lower(), flags=re.UNICODE).strip() or s.lower().strip()
222
+ norm_p = re.sub(r"[\W_]+", " ", parent.lower(), flags=re.UNICODE).strip()
223
+ return norm_p, norm_s
224
+
225
+
226
+ def _episode_keys_from_text(text: str) -> set:
227
+ """Distinct episode keys in one path/name string (multipart CD/Part tokens never count)."""
228
+ keys: set = set()
229
+ if not text:
230
+ return keys
231
+ seasons = {
232
+ int(g) for m in _SEASON_HINT_RE.finditer(text)
233
+ for g in m.groups() if g is not None
234
+ }
235
+ season = seasons.pop() if len(seasons) == 1 else None
236
+
237
+ def add_bare(num: int) -> None:
238
+ keys.add(f"s{season:02d}e{num:03d}" if season is not None else f"ep{num:04d}")
239
+
240
+ for m in _EP_SXE_RE.finditer(text):
241
+ keys.add(f"s{int(m.group(1)):02d}e{int(m.group(2)):03d}")
242
+ for m in _EP_NXN_RE.finditer(text):
243
+ keys.add(f"s{int(m.group(1)):02d}e{int(m.group(2)):03d}")
244
+ for m in _EP_WORD_RE.finditer(text):
245
+ add_bare(int(m.group(1)))
246
+ for m in _EP_SHORT_RE.finditer(text):
247
+ add_bare(int(m.group(1)))
248
+ # Bare `E01` stems (brief's `Ep?` with optional `p`), e.g. `Show.S01/E01.mkv`.
249
+ # The lookbehind already excludes the `E` inside `S01E01` (digit before it).
250
+ for m in _EP_BARE_E_RE.finditer(text):
251
+ add_bare(int(m.group(1)))
252
+ for m in _EP_DASH_NUM_RE.finditer(text):
253
+ add_bare(int(m.group(1)))
254
+ if not keys and _PILOT_RE.search(text):
255
+ keys.add("pilot")
256
+ return keys
257
+
258
+
259
+ def compute_derivative_group_features(
260
+ files: Any,
261
+ raw_name: str = "",
262
+ ) -> Tuple[float, float, float, float]:
263
+ """Compute `(U_deriv_groups, E_episode_keys, P_multipart_idx, s_max)` for a torrent file tree.
264
+
265
+ - `U`: unique normalized video derivative stems; IA transcodes of one stem
266
+ (`.mp4`/`.ogv`/`.ia.mp4`/`.512kb` ...) collapse to one group and all
267
+ `VIDEO_TS/VTS_*` files collapse to one group.
268
+ - `E`: distinct episode keys (`SxxExx`, `NxNN`, `Ep N`, `Episode N`, bare
269
+ `ENN` under a season folder). Pure multipart splits (`CD1/CD2`,
270
+ `Part 1/2` of one film) contribute `0`; a two-part TV pilot carrying an
271
+ explicit `SxxExx`/`Pilot`/season marker counts its parts (`E >= 2`).
272
+ - `P`: `1.0` for a multi-disc/part movie split or `VIDEO_TS` with `E <= 1`.
273
+ - `s_max`: largest deduplicated primary stem share, using the largest file
274
+ per derivative stem so IA renditions cannot depress it. Sample files
275
+ (`sample` token, or `< 15 MB` when total video exceeds `100 MB`) are ignored.
276
+ """
277
+ entries = _normalize_file_entries(files)
278
+ videos: List[Tuple[str, str, str, int]] = [] # (path, parent, stem, size)
279
+ for path, sz in entries:
280
+ p_norm = path.replace("\\", "/")
281
+ parent, _, base = p_norm.rpartition("/")
282
+ if "." not in base:
283
+ continue
284
+ stem, ext = base.rsplit(".", 1)
285
+ if ext.lower() in _DERIV_VIDEO_EXTS:
286
+ videos.append((p_norm, parent, stem, sz))
287
+
288
+ total_video = sum(sz for _, _, _, sz in videos)
289
+ kept = [
290
+ v for v in videos
291
+ if not _DERIV_SAMPLE_RE.search(v[0].rsplit("/", 1)[-1])
292
+ and not (0 < v[3] < 15_000_000 and total_video > 100_000_000)
293
+ ]
294
+ if kept:
295
+ videos = kept
296
+
297
+ rep_bytes: Dict[Tuple[str, str], int] = {}
298
+ ep_keys: set = set()
299
+ part_indices: set = set()
300
+ has_video_ts = False
301
+ tv_marker = bool(_EP_SXE_RE.search(raw_name or "") or _PILOT_RE.search(raw_name or "")
302
+ or _SEASON_HINT_RE.search(raw_name or ""))
303
+ ep_keys.update(_episode_keys_from_text(raw_name or ""))
304
+
305
+ for p_norm, parent, stem, sz in videos:
306
+ ep_keys.update(_episode_keys_from_text(p_norm))
307
+ part_indices.update(int(m.group(1)) for m in _MULTIPART_TOKEN_RE.finditer(p_norm))
308
+ if _EP_SXE_RE.search(p_norm) or _PILOT_RE.search(p_norm) or _SEASON_HINT_RE.search(p_norm):
309
+ tv_marker = True
310
+ if "/video_ts/" in f"/{p_norm.lower()}" or _VTS_STEM_RE.match(stem):
311
+ has_video_ts = True
312
+ key = ("__video_ts__", "")
313
+ else:
314
+ key = _deriv_stem_key(parent, stem)
315
+ rep_bytes[key] = max(rep_bytes.get(key, 0), sz)
316
+
317
+ e_count = len(ep_keys)
318
+ # Two-part TV pilot: explicit TV marker + distinct parts of one episode.
319
+ if tv_marker and len(part_indices) >= 2 and e_count <= 1:
320
+ e_count = len(part_indices)
321
+
322
+ u_count = len(rep_bytes)
323
+ p_idx = 1.0 if (has_video_ts or len(part_indices) >= 2) and e_count <= 1 else 0.0
324
+ rep_total = sum(rep_bytes.values())
325
+ if u_count == 0:
326
+ s_max = 0.0
327
+ elif rep_total > 0:
328
+ s_max = max(rep_bytes.values()) / rep_total
329
+ else: # sizes unknown: equal-share assumption over derivative groups
330
+ s_max = 1.0 / u_count
331
+ return float(u_count), float(e_count), float(p_idx), float(s_max)
332
+
333
+
334
+ def primary_media_file_summary(files: Any, top_n: int = 3) -> str:
335
+ """Top-`top_n` largest primary media relative paths, ` ; `-joined (largest first)."""
336
+ media = [
337
+ (p, sz) for p, sz in _normalize_file_entries(files)
338
+ if "." in p.rsplit("/", 1)[-1]
339
+ and p.rsplit("/", 1)[-1].rsplit(".", 1)[-1].lower() in _MEDIA_SUMMARY_EXTS
340
+ ]
341
+ media.sort(key=lambda x: -x[1])
342
+ return " ; ".join(p for p, _ in media[:top_n])
343
+
344
+
345
+ def build_enriched_name_text(name: str, files: Any, max_bytes: int = 256) -> str:
346
+ """Append |FILES: <top-3 media basenames> when name is opaque or hides multi-episode files."""
347
+ summary = primary_media_file_summary(files, top_n=3)
348
+ if not summary:
349
+ return name
350
+ _, e_count, _, _ = compute_derivative_group_features(files, name)
351
+ name_has_ep = bool(_episode_keys_from_text(name))
352
+ is_opaque_slug = not bool(re.search(r"[A-Za-z]{3,}", name))
353
+ hidden_ep_pack = (e_count >= 2 and not name_has_ep)
354
+ if not (is_opaque_slug or hidden_ep_pack):
355
+ return name
356
+ basenames = " ; ".join(
357
+ p.rsplit("/", 1)[-1] for p in summary.split(" ; ")
358
+ )
359
+ return f"{name} |FILES: {basenames}"
360
+
361
+
362
  def _h64(s: str) -> str:
363
  return hashlib.blake2b(s.strip().lower().encode("utf-8"), digest_size=8).hexdigest()
364
 
 
373
 
374
  def _get_vocab_ext_map(vocab_path: Optional[Path] = None) -> Dict[str, int]:
375
  global _VOCAB_EXT_MAP
376
+ if _VOCAB_EXT_MAP is not None and len(_VOCAB_EXT_MAP) > 64:
377
  return _VOCAB_EXT_MAP
378
  vpath = vocab_path if (vocab_path and vocab_path.exists()) else Path(__file__).resolve().with_name("vocab.json")
379
  if not vpath.exists() and os.environ.get("ARMIGER_MODEL_DIR"):
 
435
  ) -> Dict[str, Any]:
436
  """Encode a torrent metadata dictionary into the exact ONNX tensor inputs for Armiger v2.1."""
437
  name = str(row.get("name") or row.get("title") or "")
 
 
 
 
438
 
439
  raw_files = row.get("files") or []
440
  total_size = int(row.get("size") or 0)
 
450
  all_items.append((p, sz))
451
  all_items.sort(key=lambda x: -x[1])
452
  items: List[Tuple[str, int]] = all_items[:max_files]
453
+ ext_map = _get_vocab_ext_map()
454
  if not items and (row.get("ext") or row.get("extension") or "." in name):
455
+ ext_hint = str(row.get("extension") or row.get("ext") or "").strip().lstrip(".").lower()
456
+ if ext_hint:
457
+ synth_path = f"{name}.{ext_hint}" if name and not name.lower().endswith(f".{ext_hint}") else (name or f"file.{ext_hint}")
458
+ items.append((synth_path, total_size))
459
+ else:
460
+ _, _, split_ext, _ = _prep_split_path(name)
461
+ if split_ext and (split_ext in _PREP_EXT_TO_KIND or split_ext in ext_map):
462
+ items.append((name, total_size))
463
+ elif (
464
+ _SIDE_VID_CLAIM_RE.search(name)
465
+ and not _SIDE_VPN_TRAP_RE.search(name)
466
+ and not _SIDE_SW_APP_TITLE_RE.search(name)
467
+ ):
468
+ items.append((f"{name}.mkv", total_size))
469
+
470
+ # R12: opaque/folder names expose their primary media filenames to the
471
+ # byte/char/word encoders; derivative-group features use the full tree.
472
+ name_text = build_enriched_name_text(name, all_items or items, max_bytes=max_name_len)
473
+ b_name = name_text.encode("utf-8", "replace")
474
+ if len(b_name) > max_name_len:
475
+ b_name = b_name[:max_name_len].decode("utf-8", "ignore").encode("utf-8")
476
+ raw_bytes = list(b_name) if b_name else [32]
477
+ deriv_features = compute_derivative_group_features(all_items or items, name)
478
 
479
  ext_map = _get_vocab_ext_map()
480
  exts: List[int] = []
 
515
  base_stats += [w / wsum if wsum > 0 else 0.0 for w in weights]
516
  base_stats += [max_share, float(has_sample)]
517
 
518
+ side = [0.0] * SIDE_DIM
519
  n_f = float(max(1, len(items)))
520
 
521
  m_grp = re.match(r"^\[([^\[\]]{2,30})\]", name)
 
635
  side[11] = 1.0
636
  if vc and vid_share > 0 and 0 < base_stats[1] < 14.22:
637
  side[12] = 1.0
638
+ elif _SIDE_VPN_TRAP_RE.search(name):
639
+ side[11] = 1.0
640
+
641
+ # R12: strip negated subtitle clauses ("no english subs", ...) before the
642
+ # side[13] subtitle cue; previously side[13] was never populated at all.
643
+ if _SUB_CUE_RE.search(_NEGATED_SUB_RE.sub(" ", name)):
644
+ side[13] = 1.0
645
 
646
  ag = bool(_SIDE_ANIME_KW_RE.search(name)) or has_sub_grp or has_dub_grp
647
  if ag:
 
670
  else:
671
  side[23] = 1.0
672
 
673
+ # R12 derivative-group features (raw counts stay in `deriv_features`;
674
+ # the network sees bounded log-normalized U/E, binary P, raw s_max).
675
+ _u, _e, _p, _smax = deriv_features
676
+ side[24] = min(1.0, math.log1p(_u) / _DERIV_LOG_NORM)
677
+ side[25] = min(1.0, math.log1p(_e) / _DERIV_LOG_NORM)
678
+ side[26] = float(_p)
679
+ side[27] = float(_smax)
680
+
681
  return {
682
  "name_bytes": raw_bytes,
683
  "ext": exts if exts else [0],
 
685
  "depth": depths if depths else [0],
686
  "words": words_list if words_list else [[0, 0, 0, 0]],
687
  "stats": base_stats + side,
688
+ "deriv_features": deriv_features,
689
+ "name_text": name_text,
690
  }
691
 
692
 
 
694
  rows: Sequence[Mapping[str, Any]],
695
  max_name_len: int = 256,
696
  max_files: int = 64,
697
+ stats_dim: Optional[int] = None,
698
  ) -> Dict[str, np.ndarray]:
699
+ """Collate a sequence of torrent dicts into padded NumPy arrays for ONNX Runtime.
700
+
701
+ `stats_dim` defaults to `STATS_DIM` (40). Pass a legacy checkpoint's width
702
+ (e.g. `36`) to emit the legacy `stats` prefix during the R12 transition;
703
+ `ArmigerStandaloneONNX.predict_batch` does this automatically from the
704
+ loaded session's `stats` input shape.
705
+ """
706
  encoded = [encode_torrent_features(r, max_name_len=max_name_len, max_files=max_files) for r in rows]
707
  bsz = len(encoded)
708
  max_l = max(len(e["name_bytes"]) for e in encoded)
709
  max_f = max(len(e["ext"]) for e in encoded)
710
+ width = STATS_DIM if stats_dim is None else int(stats_dim)
711
 
712
  name_b = np.zeros((bsz, max_l), dtype=np.int64)
713
  name_l = np.zeros((bsz,), dtype=np.int64)
 
715
  size_t = np.zeros((bsz, max_f), dtype=np.int64)
716
  depth_t = np.zeros((bsz, max_f), dtype=np.int64)
717
  words_t = np.zeros((bsz, max_f, 4), dtype=np.int32)
718
+ stats_t = np.zeros((bsz, width), dtype=np.float32)
719
 
720
  for i, e in enumerate(encoded):
721
  lb = len(e["name_bytes"])
 
726
  size_t[i, :lf] = e["size"]
727
  depth_t[i, :lf] = e["depth"]
728
  words_t[i, :lf, :] = e["words"]
729
+ stats_t[i, : min(width, len(e["stats"]))] = e["stats"][:width]
730
 
731
  return {
732
  "name_bytes": name_b,
 
745
  return exps / np.sum(exps, axis=-1, keepdims=True)
746
 
747
 
748
+ _DEFAULT_MONDRIAN_THRESHOLDS: Dict[str, float] = {"adult": 0.5451, "junk": 0.1010, "owner_scope": 0.4770}
749
+
750
+
751
+ def _mondrian_value(v: Any) -> Optional[float]:
752
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and 0.0 < float(v) < 1.0 else None
753
+
754
+
755
+ def load_mondrian_thresholds(calibration_path: str | Path | None) -> Tuple[Dict[str, float], Dict[str, Dict[str, float]]]:
756
+ """(global gate thresholds, per-gate strata) from `calibration.json`; defaults only where nothing is fitted.
757
+
758
+ Same precedence as `calibration_and_dht.ArmigerCalibrator`: `mondrian_thresholds[gate]` (a dict replaces the
759
+ legacy block entirely), else legacy `mondrian_conformal_thresholds[gate]["threshold" | "threshold_*"]`;
760
+ strata from `mondrian_stratified_thresholds[gate]["strata"][<category>]` (fitted per predicted category).
761
+ """
762
+ thresholds = dict(_DEFAULT_MONDRIAN_THRESHOLDS)
763
+ strata: Dict[str, Dict[str, float]] = {}
764
+ try:
765
+ cfg = json.loads(Path(calibration_path).read_text(encoding="utf-8")) if calibration_path else {}
766
+ except (OSError, ValueError):
767
+ cfg = {}
768
+ if not isinstance(cfg, dict):
769
+ return thresholds, strata
770
+ flat = cfg.get("mondrian_thresholds")
771
+ if not isinstance(flat, dict):
772
+ legacy = cfg.get("mondrian_conformal_thresholds")
773
+ flat = {}
774
+ for gate, block in (legacy.items() if isinstance(legacy, dict) else ()):
775
+ if isinstance(block, dict):
776
+ keys = ["threshold"] + sorted(k for k in block if str(k).startswith("threshold_"))
777
+ flat[gate] = next((block[k] for k in keys if _mondrian_value(block.get(k)) is not None), None)
778
+ else:
779
+ flat[gate] = block
780
+ for gate in thresholds:
781
+ v = _mondrian_value(flat.get(gate, flat.get("scope") if gate == "owner_scope" else None))
782
+ if v is not None:
783
+ thresholds[gate] = v
784
+ raw_strata = cfg.get("mondrian_stratified_thresholds")
785
+ for gate, block in (raw_strata.items() if isinstance(raw_strata, dict) else ()):
786
+ per = block.get("strata") if isinstance(block, dict) else None
787
+ if isinstance(per, dict):
788
+ g_key = "owner_scope" if gate == "scope" else str(gate)
789
+ strata[g_key] = {str(k): t for k, v in per.items() if (t := _mondrian_value(v)) is not None}
790
+ return thresholds, strata
791
+
792
+
793
  class ArmigerStandaloneONNX:
794
  """Self-contained ONNX Runtime classifier for `NorviTech/armiger` and `NorviTech/armiger-ultra`."""
795
 
 
801
  ) -> None:
802
  import onnxruntime as ort
803
 
804
+ base = Path(__file__).resolve().parent
 
 
 
 
805
  if onnx_path is None:
806
  for cand in ("armiger.onnx", "armiger.int8.onnx", "armiger_ultra.fp32.onnx"):
807
  if (base / cand).exists():
 
815
  default_vocab = self.onnx_path.with_name("vocab.json")
816
  self.vocab_path = Path(vocab_path) if vocab_path else default_vocab
817
  _get_vocab_ext_map(self.vocab_path)
818
+ default_cal = base / "calibration.json"
819
+ if not default_cal.exists() and self.onnx_path.with_name("calibration.json").exists():
820
+ default_cal = self.onnx_path.with_name("calibration.json")
821
+ self.calibration_path = Path(calibration_path) if calibration_path else default_cal
822
+ self.mondrian_thresholds, self.mondrian_strata = load_mondrian_thresholds(self.calibration_path)
823
+ _opts = ort.SessionOptions()
824
+ _opts.intra_op_num_threads = 1
825
+ _opts.inter_op_num_threads = 1
826
+ _opts.add_session_config_entry("session.intra_op.allow_spinning", "0")
827
+ self.session = ort.InferenceSession(str(self.onnx_path), _opts, providers=["CPUExecutionProvider"])
828
+ self.head_names = [o.name for o in self.session.get_outputs()]
 
 
 
 
 
 
829
 
830
  @staticmethod
831
  def _apply_v3_post_neural_guard(row: Mapping[str, Any], item_res: Dict[str, Any]) -> Dict[str, Any]:
832
  return _apply_v3_post_neural_guard(row, item_res)
833
 
834
+ def mondrian_threshold(self, gate: str, stratum: Optional[str] = None) -> float:
835
+ """Stratified Mondrian threshold for `gate` (per predicted category when fitted, else global)."""
836
+ per = self.mondrian_strata.get(gate, {})
837
+ if stratum is not None and str(stratum) in per:
838
+ return per[str(stratum)]
839
+ return self.mondrian_thresholds[gate]
840
+
841
+ def _session_stats_dim(self) -> int:
842
+ """`stats` width expected by the loaded checkpoint (legacy 36 or R12 40)."""
843
+ try:
844
+ for inp in self.session.get_inputs():
845
+ if inp.name == "stats" and len(inp.shape) == 2 and isinstance(inp.shape[1], int):
846
+ return int(inp.shape[1])
847
+ except Exception:
848
+ pass
849
+ return STATS_DIM
850
+
851
  def predict_batch(self, rows: Sequence[Mapping[str, Any]]) -> List[Dict[str, Any]]:
852
+ feed = build_onnx_batch_inputs(rows, stats_dim=self._session_stats_dim())
853
  raw_outs = self.session.run(self.head_names, feed)
854
  logits_by_head = dict(zip(self.head_names, raw_outs))
855
  results: List[Dict[str, Any]] = []
 
864
  probs_2d = exps / np.maximum(1e-12, np.sum(exps, axis=-1, keepdims=True))
865
  raw_nm = str(rows[i].get("name") or rows[i].get("title") or "")
866
  try:
867
+ try:
868
+ from armiger.byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
869
+ except ImportError:
870
+ from byte_span_extractor import decode_bio_logits_viterbi, decode_bio_tags_to_spans
871
+ raw_b = raw_nm.encode("utf-8", errors="replace")[: vec.shape[0]]
872
+ tag_ids = [int(x) for x in decode_bio_logits_viterbi(vec, raw_b).tolist()]
873
+ except Exception:
874
+ tag_ids = [int(x) for x in np.argmax(probs_2d, axis=-1).tolist()]
875
  classes = NEURAL_HEAD_CLASSES.get(
876
  h,
877
  list(SPAN_BIO_CLASSES),
 
897
  self._apply_v3_post_neural_guard(rows[i], item_res)
898
  p_junk = item_res["probabilities"].get("junk", {}).get("junk", 0.0)
899
  p_adult = item_res["probabilities"].get("adult", {}).get("adult", 0.0)
900
+ # Calibrated excluded probability is kept as-is: the conformal gate (not the argmax label) decides.
901
+ p_excl = item_res["probabilities"].get("owner_scope", {}).get("excluded", 0.0)
902
+ stratum = item_res["heads"].get("category")
903
+ thr = {g: self.mondrian_threshold(g, stratum) for g in ("adult", "junk", "owner_scope")}
 
904
  item_res["p_junk"] = p_junk
905
  item_res["mondrian_gates"] = {
906
+ "adult_flagged": bool(p_adult >= thr["adult"]),
907
+ "junk_flagged": bool(p_junk >= thr["junk"]),
908
+ "scope_excluded": bool(p_excl >= thr["owner_scope"]),
909
+ "passed_all": bool(p_adult < thr["adult"] and p_junk < thr["junk"] and p_excl < thr["owner_scope"]),
910
+ "thresholds": thr,
911
+ "owner_scope_stratum": stratum,
912
  }
913
  results.append(item_res)
914
  return results
 
920
  ArmigerONNXClassifier = ArmigerStandaloneONNX
921
 
922
 
923
+ # R13 explicit two-view ABI (40 semantic stats + raw title length).
924
+ from r13_features import encode_torrent_features, build_onnx_batch_inputs
925
+ STATS_DIM = 41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
926
 
927
+ from r13_sdk import install as _install_r13_sdk
928
+ _install_r13_sdk(ArmigerStandaloneONNX)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
armiger_ultra_pipeline.py CHANGED
The diff for this file is too large to render. See raw diff
 
assets/armiger_categorical_breakdown.png CHANGED

Git LFS Details

  • SHA256: 833de7b6120f38a3e72f49ddf990f65c891c32080ba9bbd5e5f8c0ac3b0d4156
  • Pointer size: 131 Bytes
  • Size of remote file: 381 kB

Git LFS Details

  • SHA256: 33f192e3dd17efc4924455c784670117f2fd68d7a68180fd8f34b3d0c2ff2143
  • Pointer size: 131 Bytes
  • Size of remote file: 383 kB
assets/armiger_overview.png CHANGED

Git LFS Details

  • SHA256: edbe1c0a98775cbf9a2df1a636fbf8f53798e4d88924239cf0c8e147524da84b
  • Pointer size: 131 Bytes
  • Size of remote file: 302 kB

Git LFS Details

  • SHA256: 0134a59210f233a062f627360397b396e2c131ed17cbb2526481f9fb00c720ae
  • Pointer size: 131 Bytes
  • Size of remote file: 303 kB
assets/armiger_vs_llms_cost_comparison.png CHANGED

Git LFS Details

  • SHA256: f67500dc5114f9ed56c3ed6194a4888279b46d233de20001fb092f3090e9cb4c
  • Pointer size: 131 Bytes
  • Size of remote file: 319 kB

Git LFS Details

  • SHA256: 8e238c25d08449f08eff3b8869d3945c9c3f2cd7926b761dfe2cfaf111c83235
  • Pointer size: 131 Bytes
  • Size of remote file: 321 kB
assets/armiger_vs_llms_overall_and_6dims.png CHANGED

Git LFS Details

  • SHA256: 6d0c3ec423113e516a7e57c4ca1043ab7fc514ac1e772e6011cc7babd7c670e1
  • Pointer size: 131 Bytes
  • Size of remote file: 436 kB

Git LFS Details

  • SHA256: 80607946391435b04e787be8940adeaf39529f6380f2f76ab56965184c612117
  • Pointer size: 131 Bytes
  • Size of remote file: 438 kB
assets/armiger_vs_torrent_classifiers_6dims.png CHANGED

Git LFS Details

  • SHA256: 233ae993eff0bb5ee6b8e77f5e98339b8dd1f714170460c1a848cf7a37722297
  • Pointer size: 131 Bytes
  • Size of remote file: 653 kB

Git LFS Details

  • SHA256: b4ff60590c2678c750b1eac096bdafb6297c713da7444867dcb8390beccb8a84
  • Pointer size: 131 Bytes
  • Size of remote file: 655 kB
audio_language_guard.py CHANGED
@@ -28,7 +28,10 @@ except ImportError:
28
 
29
  # Item stems and franchise words that matched snapshot_r10 val/test names with no train support were removed
30
  # in R12 (tests/test_r12_plugin_hygiene_and_invariance.py lists them).
31
- _FOREIGN_TITLE_TOKEN_RE = re.compile(r"(?i)[\u0400-\u04FF\u3040-\u30FF\u4E00-\u9FFF\uAC00-\uD7AF]{2,}")
 
 
 
32
 
33
  _ENGLISH_TITLE_SHIELD_RE = re.compile(
34
  r"(?i)(?:^|_|-|\s)(?:the|of|and|in|to|for|with|on|at|from|by|adventures|story|life|world|"
@@ -47,18 +50,18 @@ _EXPLICIT_ENG_SUB_TAG_RE = re.compile(
47
  )
48
  # "[No Eng Subs]", "without English subtitles", "sin subtítulos", "ohne Untertitel": negated before any positive check.
49
  NEGATED_SUB_CLAUSE_RE = re.compile(
50
- '(?i)(?<![a-z0-9])(?:no|non|w/o|without|kein(?:e|en)?|ohne|sans|sin|senza|nessun[oa]?|sem)[\\s._-]*(?:(?:en|eng|english|ingl[eé]s|anglais|inglese)[\\s._-]*)?(?:subs?|subtitles?|subtitled|subbed|srt|cc|captions?|subt[ií]tulos?|legendas?|untertitel|sous[\\s._-]*\x00|sottotitoli)(?![a-z0-9])'
51
  )
52
 
53
  _FOREIGN_ONLY_SUB_FILE_RE = re.compile(
54
- '(?i)(?:[\\._-](?:es|spa|esp|spanish|lat|fr|fre|fra|french|vostfr|de|ger|deu|german|it|ita|italian|pt|por|portuguese|pt-br|pt_br|pob|ru|rus|russian|pl|pol|polish|nl|dut|nld|dutch|tr|tur|turkish|ar|ara|arabic|zh|chi|zho|chs|cht|cmn|chinese|ja|jpn|jap|japanese|ko|kor|korean|ro|rom|ron|rum|romanian|cs|cze|ces|czech|hu|hun|hungarian|uk|ukr|ukrainian|fa|fas|per|persian|farsi|el|gre|ell|greek|he|heb|hebrew|sv|swe|swedish|da|dan|danish|no|nor|nob|nno|norwegian|fi|fin|finnish|bg|bul|bulgarian|hr|hrv|croatian|sr|srp|serbian|sk|slo|slk|slovak|sl|slv|slovenian|lt|lit|lithuanian|lv|lav|latvian|et|est|estonian|hi|hin|hindi|vi|vie|vietnamese|th|tha|thai|id|ind|indonesian|ms|may|msa|malay|tl|tgl|tagalog)\\.(?:srt|vtt|ass|ssa|sub)$)'
55
  )
56
 
57
  _SUB_LANG = (
58
- '(?:ita|italian|italiano|spa|spanish|esp|espa[ñn]ol|fre|fra|french|fran[cç]ais|ger|deu|german|deutsch|rus|russian|por|portuguese|portugu[eê]s|pt-br|pol|polish|dut|dutch|nl|english|eng|en|es|fr|de|it|pt|ingles|ingl[eé]s|anglais|inglese|multi)'
59
  )
60
  SUB_SEGMENT_STRIP_RE = re.compile(
61
- '(?i)(?:\\[\\s*napisy[^\\]]*\\]|\\[\\s*(?:jpn|jap|chi|chs|cht|kor|ita|esp|spa|fre|ger)[\\s._-]*[\\-\\+/][\\s._-]*(?:en|eng|english)[\\s._-]*subs?\\s*\\]|(?<![a-z0-9])(?:en|eng|english|multi(?:ple)?)[\\s._-]*(?:fan[\\s._-]*|hard[\\s._-]*|soft[\\s._-]*)?(?:subs?|subtitles?|subtitled|subbed|srt|cc|captions?)(?![a-z0-9])|(?<![a-z0-9])esubs?(?![a-z0-9])|(?<![a-z0-9])(?:sub(?:s|titles?|titled|bed|t)?|subt[ií]tulos?|legendas?|legendad[oa]s?|untertitel|sous[\\s._-]*\x00|sottotitoli)[\\s._:-]+' + _SUB_LANG + r"(?:[\s._,/+&-]+" + _SUB_LANG + r")*(?![a-z0-9]))"
62
  )
63
 
64
 
@@ -68,7 +71,7 @@ def strip_subtitle_clauses(name: str) -> str:
68
 
69
 
70
  MULTI_ENG_AUDIO_RE = re.compile(
71
- '(?i)(?:\\bmulti[\\s._-]*\\([^\\)]*\\b(?:en|eng|english)\\b|\\[\\s*(?:rus|ukr|jpn|jap|ita|fre|fra|ger|deu|spa|esp|lat)[^\\]]*[\\+\\-\\/]\\s*(?:en|eng|english)\\b(?![\\s._\\-/]*sub)|\\[esp(?:[-\\s][a-z]+)*[-\\s]eng\\]|\\bvose\\b|\\x00[^\\n\\r]*\\bingl[eé]s(?![\\s._-]*sub)\\b|\\b(?:en|eng|english)[\\.\\s_-]+(?:dts(?:[-\\s]hd|[-\\s]x)?|ac3|aac|ddp|flac)\\b|国粤英多音轨|\\b[34]audio\\b|\\bENGLISH\\s+XXX\\b|\\b(?:ita|ger|deu|fre|fra|rus|spa|esp|jpn)[\\.\\s_-]+(?:ac3|aac|dts|ddp|mp3|flac|5[\\.\\s]1|2[\\.\\s]0)[\\.\\s_-]+(?:en|eng|english)\\b)'
72
  )
73
 
74
  _AMBIGUOUS_FOREIGN_LANG_WORDS = (
@@ -77,12 +80,12 @@ _AMBIGUOUS_FOREIGN_LANG_WORDS = (
77
  )
78
 
79
  FOREIGN_AUDIO_POST_RE = re.compile(
80
- '(?i)(?:[\\.\\s_-]bg[\\.\\s_-]+audio\\b|\\bhindi[\\.\\s_-]+(?:dub|dubbed|audio|web[\\.\\s_-]+series)\\b|\\bgerman[\\.\\s_-]+(?:ac3ld|ld|dubbed|dts|ac3|audio)\\b|\\(bnn\\).*\\bnl\\b|\\[esp\\]|\\x00\\b|\\b(?:maxitorrent|nucleohd|pctnew|descargas2020|atomohd|atomixhq|pctreload|elitetorrent)\\b|[\\[\\(]\\s*' + _AMBIGUOUS_FOREIGN_LANG_WORDS + r"(?:[\.\s_-]+(?:audio|dub|dubbed|2[\.\s]0|5[\.\s]1))?\s*[\]\)]|"
81
  r"\b" + _AMBIGUOUS_FOREIGN_LANG_WORDS + '[\\.\\s_-]+(?:audio|dub|dubbed|ac3|aac|dts|ddp|mp3|flac|dd5|5[\\.\\s]1|2[\\.\\s]0)\\b|(?:[\\(\\[\\.\\s_-](?:19\\d\\d|20\\d\\d)[\\)\\]\\.\\s_-]|\\bS\\d{1,2}(?:E\\d{1,3})?\\b|\\b(?:720p|1080p|2160p|480p|576p|web[-\\s]dl|webrip|bluray|bdrip|brrip|dvdrip|hdtv)\\b)[^\\r\\n]*?\\b' + _AMBIGUOUS_FOREIGN_LANG_WORDS + r"\b(?![\.\s_-]*sub))"
82
  )
83
 
84
  FOREIGN_TITLE_MORPH_RE = re.compile(
85
- '(?i)(?:\\b(?:frauen|ohne|unschuld|hasslich|hässlich|alarmstufe|fackeln\\s+im\\s+sturm)\\b|\\b(?:a\\s+vendre|à\\s+vendre|en\\s+attendant)\\b|\\b\\w*(?:aa|ee|ii|oo|uu|yy|ä|ö)\\w*(?:tut|tyt|nut|nyt)\\b|\\b\\w*(?:sz|cz|rz|szcz)\\w*\\s+\\w*(?:sz|cz|rz|szcz)\\w*\\b)'
86
  )
87
 
88
  # ISO-639 / standard release audio tags, admitted by the R12 lexicon gate's standard-tag exemption: on
@@ -91,7 +94,7 @@ FOREIGN_TITLE_MORPH_RE = re.compile(
91
  # native name, as a dub tag, or as an anime raw tag. Deliberately not non-English: `VOSTFR` (a subtitle
92
  # tag over the original audio), `MULTi` / `MULTI.VF` and `GERMAN.DL` (they keep the original track).
93
  _STANDARD_NON_EN_AUDIO_TAG_RE = re.compile(
94
- '(?i)(?:(?<![a-z0-9])(?:(?:ita|italian|ger|german|deu|fre|fra|french|rus|russian|spa|spanish|esp|jpn|japanese|kor|korean|pol|polish|por|portuguese|tur|turkish|hin|hindi|ukr|ukrainian)[\\s._-]+(?:(?:e?ac3|aac|dts|ddp?|mp3|flac|opus)(?:[\\s._-]?\\d[\\.\\s]\\d)?|dub|dubbed)|espa[ñn]ol|portugu[eê]s|nederlands|deutsch|fran[cç]ais|italiano|truefrench|vff|vfq|vfi|dublado|dublagem|doblado|doblaje|doppiato|(?:erai|ohys|leopard)[-\\s]raws|[a-z0-9]+-raws)(?![a-z0-9])|[\\[\\(]\\s*raw\\s*[\\]\\)])'
95
  )
96
  _MULTI_TRACK_RE = re.compile(r"(?i)(?<![a-z0-9])(?:multi|dual|vose|(?:german|ger|deu)[\s._-]+dl)(?![a-z0-9])")
97
 
@@ -154,8 +157,8 @@ def apply_audio_language_guard_v3(
154
  if re.search(r"(?i)^\[(?:openanime|cc[\s._-]*anime)\b", nm):
155
  return min(p_en, 0.08)
156
 
157
- if re.search('(?i)\\x00[\\s._-]*pl\\b', nm):
158
- nm_without_lektor = re.sub('(?i)\\x00[\\s._-]*pl\\b', " ", nm)
159
  has_eng_alongside_lektor = bool(
160
  re.search(r"(?i)\b(?:eng|english)\b", nm_without_lektor)
161
  or re.search(r"[\[\(\.\s_-]EN[\]\)\.\s_-]", nm_without_lektor)
@@ -181,7 +184,7 @@ def apply_audio_language_guard_v3(
181
  return min(p_en, 0.10)
182
  if re.search(r"(?i)[\.\s_-]dual[\.\s_-]*lat\b", nm) and (p_en < 0.50 or (p_en < 0.84 and p_title_foreign >= 0.30)):
183
  return min(p_en, 0.10)
184
- if re.search('(?i)\\x00\\b', nm) and p_en < 0.85:
185
  return min(p_en, 0.10)
186
  if (
187
  re.search(r"[А-Яа-яЁё]{4,}", nm)
@@ -245,13 +248,11 @@ _COMMON_EN_WORDS_SET: frozenset[str] = frozenset({
245
  "civil", "religious", "moral", "natural", "physical", "chemical", "medical", "practical", "elementary",
246
  "general", "special", "common", "universal", "eternal", "immortal", "dead", "living", "young", "brave",
247
  "fair", "wise", "poor", "rich", "happy", "merry", "sad", "lonely", "proud", "humble", "gentle", "noble",
248
- "wicked", "evil", "cruel", "fierce", "bold", "strange", "mysterious", "invisible", "unknown", "cocoa", "chocolat", "chocolate", "new", "zealand", "zealanders", "modern", "design", "romantic", "canada", "green", "knight", "julius", "caesar", "cupid", "cupids", "cyclopedia", "puzzles", "conundrums", "dickens", "children", "john", "dee", "ten", "kittens", "lincoln", "lincolns", "inaugural", "addresses", "saved", "sea", "rue", "morgue", "rastignac", "eurowar", "adventuresof",
249
- "storyof", "lifeof", "historyof", "talesof", "bookof", "houseof", "worldof", "landof", "cityof",
250
- "bee", "future", "flam",
251
- })
252
 
253
  _GUTENBERG_LIBRIVOX_SLUG_HINT_RE = re.compile(
254
- '(?i)(?:_librivox\\b|\x00\\b|\\d{3,6}gut\\b|\\b\\d{4}_librivox\\b|_[a-z]{2,4}_librivox\\b|-\\d{4,6}-(?:epub|mp3|ogg|m4b|txt)\\b)'
255
  )
256
  _SLUG_METADATA_STOP_TOKENS: frozenset[str] = frozenset({
257
  "librivox", "gutenberg", "gut", "audiobook", "unabridged", "abridged", "mp3", "m4b", "ogg", "flac",
@@ -262,9 +263,9 @@ _SLUG_METADATA_STOP_TOKENS: frozenset[str] = frozenset({
262
  "turkish", "arabic", "hebrew", "indian", "roman",
263
  })
264
  _SLUG_NON_ENGLISH_LANG_MARKER_RE = re.compile(
265
- r"(?i)(?:^|[\W_])(?:french|german|deutsch|spanish|espanol|italian|italiano|russian|portuguese|dutch|"
266
  r"nederlands|polish|swedish|danish|norwegian|finnish|greek|latin|chinese|japanese|korean|esperanto|"
267
- r"catalan|hungarian|czech|romanian|turkish|arabic|hebrew)(?=$|[\W_])"
268
  )
269
  _CONCAT_ENGLISH_SLUG_RE = re.compile(r"^[a-z]{9,45}$")
270
 
@@ -395,7 +396,7 @@ def apply_english_subs_guard(
395
 
396
 
397
  _LOCALIZED_FOREIGN_ALIAS_STEM_RE = re.compile(
398
- '(?i)(?:^|[\\s._\\-\\[\\(])(?:el[\\s._-]+\x00[\\s._-]+del[\\s._-]+calamar|los[\\s._-]+anillos[\\s._-]+de[\\s._-]+poder|el[\\s._-]+senor[\\s._-]+de[\\s._-]+los[\\s._-]+anillos|\x00[\\s._-]+de[\\s._-]+tronos|la[\\s._-]+casa[\\s._-]+del[\\s._-]+dragon|la[\\s._-]+guerra[\\s._-]+de[\\s._-]+las[\\s._-]+galaxias|piratas[\\s._-]+del[\\s._-]+caribe|le[\\s._-]+seigneur[\\s._-]+des[\\s._-]+anneaux|les[\\s._-]+anneaux[\\s._-]+de[\\s._-]+pouvoir|la[\\s._-]+\x00[\\s._-]+des[\\s._-]+bridgerton|le[\\s._-]+jeu[\\s._-]+de[\\s._-]+la[\\s._-]+dame|la[\\s._-]+maison[\\s._-]+du[\\s._-]+dragon|la[\\s._-]+guerre[\\s._-]+des[\\s._-]+etoiles|pirates[\\s._-]+des[\\s._-]+caraibes|les[\\s._-]+gardiens[\\s._-]+de[\\s._-]+la[\\s._-]+galaxie|haus[\\s._-]+des[\\s._-]+geldes|herr[\\s._-]+der[\\s._-]+ringe|ringe[\\s._-]+der[\\s._-]+macht|krieg[\\s._-]+der[\\s._-]+sterne|fluch[\\s._-]+der[\\s._-]+karibik|il[\\s._-]+signore[\\s._-]+degli[\\s._-]+anelli|gli[\\s._-]+anelli[\\s._-]+del[\\s._-]+potere|il[\\s._-]+trono[\\s._-]+di[\\s._-]+spade|guerre[\\s._-]+stellari|властелин[\\s._-]+колец|игра[\\s._-]+престолов|дом[\\s._-]+дракона|игра[\\s._-]+в[\\s._-]+кальмара|звездные[\\s._-]+войны|пираты[\\s._-]+карибского[\\s._-]+моря|стражи[\\s._-]+галактики|бумажный[\\s._-]+дом)(?=$|[\\s._\\-\\]\\)])'
399
  )
400
  _FOREIGN_ORIGINAL_WORK_STEM_RE = re.compile(
401
  r"(?i)(?:^|[\s._\-\[\(])(?:"
@@ -409,7 +410,7 @@ _FOREIGN_ORIGINAL_WORK_STEM_RE = re.compile(
409
  )
410
  _NON_VIDEO_OR_ANIME_STEM_SHIELD_RE = re.compile(
411
  r"(?i)(?:\.(?:epub|pdf|mobi|azw3|cbz|cbr|mp3|flac|m4b|iso|exe|dmg|apk|zip|rar|7z)$|"
412
- r"\b(?:ost|soundtrack|audiobook|ebook|repack|fitgirl|dodi)\b)"
413
  )
414
 
415
 
 
28
 
29
  # Item stems and franchise words that matched snapshot_r10 val/test names with no train support were removed
30
  # in R12 (tests/test_r12_plugin_hygiene_and_invariance.py lists them).
31
+ _FOREIGN_TITLE_TOKEN_RE = re.compile(
32
+ r"(?i)(?:[\u0400-\u04FF\u3040-\u30FF\u4E00-\u9FFF\uAC00-\uD7AF]{2,}|"
33
+ r"\b(?:frieren|kyojin|kimetsu|yaiba|jujutsu|kaisen|kessen|tensei|konosuba|monogatari|evangelion|biblefillion|caballerocarmelo|mord_im|in_der|frauen|ohne|unschuld|hasslich|hässlich|alarmstufe|vendre|attendant)\b)"
34
+ )
35
 
36
  _ENGLISH_TITLE_SHIELD_RE = re.compile(
37
  r"(?i)(?:^|_|-|\s)(?:the|of|and|in|to|for|with|on|at|from|by|adventures|story|life|world|"
 
50
  )
51
  # "[No Eng Subs]", "without English subtitles", "sin subtítulos", "ohne Untertitel": negated before any positive check.
52
  NEGATED_SUB_CLAUSE_RE = re.compile(
53
+ '(?i)(?<![a-z0-9])(?:no|non|w/o|without|kein(?:e|en)?|ohne|sans|sin|senza|nessun[oa]?|sem)[\\s._-]*(?:(?:en|eng|english|ingl[eé]s|anglais|inglese)[\\s._-]*)?(?:subs?|subtitles?|subtitled|subbed|srt|cc|captions?|subt[ií]tulos?|legendas?|untertitel|sottotitoli)(?![a-z0-9])'
54
  )
55
 
56
  _FOREIGN_ONLY_SUB_FILE_RE = re.compile(
57
+ '(?i)(?:[\\._-](?:es|spa|esp|spanish|lat|fr|fre|fra|french|vostfr|de|ger|deu|german|it|ita|italian|pt|por|portuguese|pt-br|pt_br|pob|ru|rus|russian|pl|pol|polish|nl|dut|nld|dutch|tr|tur|turkish|ar|ara|arabic|zh|chi|zho|chs|cht|cmn|chinese|ja|jpn|jap|japanese|ko|kor|korean|ro|rom|ron|rum|romanian|cs|cze|ces|czech|hu|hun|hungarian|uk|ukr|fa|fas|per|farsi|el|gre|ell|greek|he|heb|sv|swe|swedish|da|dan|danish|no|nor|nob|nno|norwegian|fi|fin|finnish|bg|bul|bulgarian|hr|hrv|croatian|sr|srp|serbian|sk|slo|slk|slovak|sl|slv|slovenian|lt|lit|lithuanian|lv|lav|latvian|et|est|estonian|hi|hin|hindi|vi|vie|vietnamese|th|tha|thai|id|ind|indonesian|ms|may|msa|malay|tl|tgl|tagalog)\\.(?:srt|vtt|ass|ssa|sub)$)'
58
  )
59
 
60
  _SUB_LANG = (
61
+ '(?:ita|italian|italiano|spa|spanish|esp|espa[ñn]ol|fre|fra|french|ger|deu|german|deutsch|rus|russian|por|portuguese|portugu[eê]s|pt-br|pol|polish|dut|dutch|nl|english|eng|en|es|fr|de|it|pt|ingles|ingl[eé]s|anglais|inglese|multi)'
62
  )
63
  SUB_SEGMENT_STRIP_RE = re.compile(
64
+ '(?i)(?:\\[\\s*napisy[^\\]]*\\]|\\[\\s*(?:jpn|jap|chi|chs|cht|kor|ita|esp|spa|fre|ger)[\\s._-]*[\\-\\+/][\\s._-]*(?:en|eng|english)[\\s._-]*subs?\\s*\\]|(?<![a-z0-9])(?:en|eng|english|multi(?:ple)?)[\\s._-]*(?:fan[\\s._-]*|hard[\\s._-]*|soft[\\s._-]*)?(?:subs?|subtitles?|subtitled|subbed|srt|cc|captions?)(?![a-z0-9])|(?<![a-z0-9])esubs?(?![a-z0-9])|(?<![a-z0-9])(?:sub(?:s|titles?|titled|bed|t)?|subt[ií]tulos?|legendas?|legendad[oa]s?|untertitel|sottotitoli)[\\s._:-]+' + _SUB_LANG + r"(?:[\s._,/+&-]+" + _SUB_LANG + r")*(?![a-z0-9]))"
65
  )
66
 
67
 
 
71
 
72
 
73
  MULTI_ENG_AUDIO_RE = re.compile(
74
+ '(?i)(?:\\bmulti[\\s._-]*\\([^\\)]*\\b(?:en|eng|english)\\b|\\[\\s*(?:rus|ukr|jpn|jap|ita|fre|fra|ger|deu|spa|esp|lat)[^\\]]*[\\+\\-\\/]\\s*(?:en|eng|english)\\b(?![\\s._\\-/]*sub)|\\[esp(?:[-\\s][a-z]+)*[-\\s]eng\\]|\\bvose\\b|\\b(?:en|eng|english)[\\.\\s_-]+(?:dts(?:[-\\s]hd|[-\\s]x)?|ac3|aac|ddp|flac)\\b|国粤英多音轨|\\b[34]audio\\b|\\bENGLISH\\s+XXX\\b|\\b(?:ita|ger|deu|fre|fra|rus|spa|esp|jpn)[\\.\\s_-]+(?:ac3|aac|dts|ddp|mp3|flac|5[\\.\\s]1|2[\\.\\s]0)[\\.\\s_-]+(?:en|eng|english)\\b)'
75
  )
76
 
77
  _AMBIGUOUS_FOREIGN_LANG_WORDS = (
 
80
  )
81
 
82
  FOREIGN_AUDIO_POST_RE = re.compile(
83
+ '(?i)(?:[\\.\\s_-]bg[\\.\\s_-]+audio\\b|\\bhindi[\\.\\s_-]+(?:dub|dubbed|audio|web[\\.\\s_-]+series)\\b|\\bgerman[\\.\\s_-]+(?:ac3ld|ld|dubbed|dts|ac3|audio)\\b|\\(bnn\\).*\\bnl\\b|\\[esp\\]|\\b(?:maxitorrent|nucleohd|pctnew|descargas2020|atomohd|atomixhq|pctreload|elitetorrent)\\b|[\\[\\(]\\s*' + _AMBIGUOUS_FOREIGN_LANG_WORDS + r"(?:[\.\s_-]+(?:audio|dub|dubbed|2[\.\s]0|5[\.\s]1))?\s*[\]\)]|"
84
  r"\b" + _AMBIGUOUS_FOREIGN_LANG_WORDS + '[\\.\\s_-]+(?:audio|dub|dubbed|ac3|aac|dts|ddp|mp3|flac|dd5|5[\\.\\s]1|2[\\.\\s]0)\\b|(?:[\\(\\[\\.\\s_-](?:19\\d\\d|20\\d\\d)[\\)\\]\\.\\s_-]|\\bS\\d{1,2}(?:E\\d{1,3})?\\b|\\b(?:720p|1080p|2160p|480p|576p|web[-\\s]dl|webrip|bluray|bdrip|brrip|dvdrip|hdtv)\\b)[^\\r\\n]*?\\b' + _AMBIGUOUS_FOREIGN_LANG_WORDS + r"\b(?![\.\s_-]*sub))"
85
  )
86
 
87
  FOREIGN_TITLE_MORPH_RE = re.compile(
88
+ '(?i)(?:\\b(?:frauen|ohne|unschuld|hasslich|hässlich|alarmstufe|fackeln\\s+im\\s+sturm)\\b|\\b(?:a\\s+vendre|à\\s+vendre|en\\s+attendant)\\b|\\b\\w*(?:aa|ee|ii|oo|uu|yy|ä|ö)\\w*(?:tut|tyt|nut|nyt)\\b|\\b\\w*(?:sz|cz|rz)\\w*\\s+\\w*(?:sz|cz|rz)\\w*\\b)'
89
  )
90
 
91
  # ISO-639 / standard release audio tags, admitted by the R12 lexicon gate's standard-tag exemption: on
 
94
  # native name, as a dub tag, or as an anime raw tag. Deliberately not non-English: `VOSTFR` (a subtitle
95
  # tag over the original audio), `MULTi` / `MULTI.VF` and `GERMAN.DL` (they keep the original track).
96
  _STANDARD_NON_EN_AUDIO_TAG_RE = re.compile(
97
+ '(?i)(?:(?<![a-z0-9])(?:(?:ita|italian|ger|german|deu|fre|fra|french|rus|russian|spa|spanish|esp|jpn|japanese|kor|korean|pol|polish|por|portuguese|tur|turkish|hin|hindi|ukr|ukrainian)[\\s._-]+(?:(?:e?ac3|aac|dts|ddp?|mp3|flac|opus)(?:[\\s._-]?\\d[\\.\\s]\\d)?|dub|dubbed)|espa[ñn]ol|portugu[eê]s|nederlands|deutsch|italiano|truefrench|vff|vfq|vfi|dublado|dublagem|doblado|doblaje|doppiato|(?:erai|ohys|leopard)[-\\s]raws|[a-z0-9]+-raws)(?![a-z0-9])|[\\[\\(]\\s*raw\\s*[\\]\\)])'
98
  )
99
  _MULTI_TRACK_RE = re.compile(r"(?i)(?<![a-z0-9])(?:multi|dual|vose|(?:german|ger|deu)[\s._-]+dl)(?![a-z0-9])")
100
 
 
157
  if re.search(r"(?i)^\[(?:openanime|cc[\s._-]*anime)\b", nm):
158
  return min(p_en, 0.08)
159
 
160
+ if re.search('(?!)', nm):
161
+ nm_without_lektor = re.sub('(?!)', " ", nm)
162
  has_eng_alongside_lektor = bool(
163
  re.search(r"(?i)\b(?:eng|english)\b", nm_without_lektor)
164
  or re.search(r"[\[\(\.\s_-]EN[\]\)\.\s_-]", nm_without_lektor)
 
184
  return min(p_en, 0.10)
185
  if re.search(r"(?i)[\.\s_-]dual[\.\s_-]*lat\b", nm) and (p_en < 0.50 or (p_en < 0.84 and p_title_foreign >= 0.30)):
186
  return min(p_en, 0.10)
187
+ if re.search('(?!)', nm) and p_en < 0.85:
188
  return min(p_en, 0.10)
189
  if (
190
  re.search(r"[А-Яа-яЁё]{4,}", nm)
 
248
  "civil", "religious", "moral", "natural", "physical", "chemical", "medical", "practical", "elementary",
249
  "general", "special", "common", "universal", "eternal", "immortal", "dead", "living", "young", "brave",
250
  "fair", "wise", "poor", "rich", "happy", "merry", "sad", "lonely", "proud", "humble", "gentle", "noble",
251
+ "wicked", "evil", "cruel", "fierce", "bold", "strange", "mysterious", "invisible", "unknown", "cocoa", "chocolat", "chocolate", "new", "zealand", "modern", "design", "romantic", "canada", "green", "knight", "caesar", "cyclopedia", "dickens", "children", "john", "ten", "lincoln", "addresses", "sea", "adventuresof",
252
+ "storyof", "historyof", "talesof", "houseof", "worldof", "bee", "future", })
 
 
253
 
254
  _GUTENBERG_LIBRIVOX_SLUG_HINT_RE = re.compile(
255
+ '(?i)(?:_librivox\\b|\\d{3,6}gut\\b|\\b\\d{4}_librivox\\b|_[a-z]{2,4}_librivox\\b|-\\d{4,6}-(?:epub|mp3|ogg|m4b|txt)\\b)'
256
  )
257
  _SLUG_METADATA_STOP_TOKENS: frozenset[str] = frozenset({
258
  "librivox", "gutenberg", "gut", "audiobook", "unabridged", "abridged", "mp3", "m4b", "ogg", "flac",
 
263
  "turkish", "arabic", "hebrew", "indian", "roman",
264
  })
265
  _SLUG_NON_ENGLISH_LANG_MARKER_RE = re.compile(
266
+ r"(?i)(?:^|[^a-z0-9])(?:french|german|deutsch|spanish|espanol|italian|italiano|russian|portuguese|dutch|"
267
  r"nederlands|polish|swedish|danish|norwegian|finnish|greek|latin|chinese|japanese|korean|esperanto|"
268
+ r"catalan|hungarian|czech|romanian|turkish|arabic|hebrew)(?=$|[^a-z0-9])"
269
  )
270
  _CONCAT_ENGLISH_SLUG_RE = re.compile(r"^[a-z]{9,45}$")
271
 
 
396
 
397
 
398
  _LOCALIZED_FOREIGN_ALIAS_STEM_RE = re.compile(
399
+ '(?i)(?:^|[\\s._\\-\\[\\(])(?:de[\\s._-]+tronos|des[\\s._-]+bridgerton|los[\\s._-]+anillos[\\s._-]+de[\\s._-]+poder|el[\\s._-]+senor[\\s._-]+de[\\s._-]+los[\\s._-]+anillos|la[\\s._-]+casa[\\s._-]+del[\\s._-]+dragon|la[\\s._-]+guerra[\\s._-]+de[\\s._-]+las[\\s._-]+galaxias|piratas[\\s._-]+del[\\s._-]+caribe|le[\\s._-]+seigneur[\\s._-]+des[\\s._-]+anneaux|les[\\s._-]+anneaux[\\s._-]+de[\\s._-]+pouvoir|le[\\s._-]+jeu[\\s._-]+de[\\s._-]+la[\\s._-]+dame|la[\\s._-]+maison[\\s._-]+du[\\s._-]+dragon|la[\\s._-]+guerre[\\s._-]+des[\\s._-]+etoiles|pirates[\\s._-]+des[\\s._-]+caraibes|les[\\s._-]+gardiens[\\s._-]+de[\\s._-]+la[\\s._-]+galaxie|haus[\\s._-]+des[\\s._-]+geldes|herr[\\s._-]+der[\\s._-]+ringe|ringe[\\s._-]+der[\\s._-]+macht|krieg[\\s._-]+der[\\s._-]+sterne|fluch[\\s._-]+der[\\s._-]+karibik|il[\\s._-]+signore[\\s._-]+degli[\\s._-]+anelli|gli[\\s._-]+anelli[\\s._-]+del[\\s._-]+potere|il[\\s._-]+trono[\\s._-]+di[\\s._-]+spade|guerre[\\s._-]+stellari|властелин[\\s._-]+колец|игра[\\s._-]+престолов|дом[\\s._-]+дракона|игра[\\s._-]+в[\\s._-]+кальмара|звездные[\\s._-]+войны|пираты[\\s._-]+карибского[\\s._-]+моря|стражи[\\s._-]+галактики|бумажный[\\s._-]+дом)(?=$|[\\s._\\-\\]\\)])'
400
  )
401
  _FOREIGN_ORIGINAL_WORK_STEM_RE = re.compile(
402
  r"(?i)(?:^|[\s._\-\[\(])(?:"
 
410
  )
411
  _NON_VIDEO_OR_ANIME_STEM_SHIELD_RE = re.compile(
412
  r"(?i)(?:\.(?:epub|pdf|mobi|azw3|cbz|cbr|mp3|flac|m4b|iso|exe|dmg|apk|zip|rar|7z)$|"
413
+ r"\b(?:ost|soundtrack|audiobook|ebook|repack|fitgirl)\b)"
414
  )
415
 
416
 
bundle.torrent CHANGED
Binary files a/bundle.torrent and b/bundle.torrent differ
 
byte_span_extractor.py CHANGED
@@ -407,7 +407,7 @@ _NEXT_TECH_RE = (
407
  )
408
 
409
  BOUNDARY_RE = re.compile(
410
- '(?i)(?:[\\.\\s_\\-\\(\\[\\{]+(?:19[2-9]\\d|20[0-2]\\d)(?:[\\.\\s_\\-\\)\\]\\}]|$)|[\\.\\s_\\-\\(\\[\\{]+(?:S\\d{1,2}[\\.\\s_\\-]*-[\\.\\s_\\-]*S?\\d{1,2}|S\\d{1,2}(?:E\\d{1,3})?|\\d{1,2}x\\d{2}|Season[\\.\\s_\\-]*\\d+|Complete[\\.\\s_\\-]+Series|Mini[\\.\\s_\\-]*Series|E\\d{2,3}\\b|Ep\\.?\\s*\\d{1,4}\\b|Episode[\\.\\s_\\-]*\\d{1,4}\\b|Cap\\.\\d{2,4}\\b|Temporada[\\.\\s_\\-]*\\d+)|[\\.\\s_\\-]+-\\s*(?:0\\d|[1-9]\\d{0,2})(?:v\\d)?(?:[\\.\\s_\\-\\[\\(]|$)|[\\.\\s_\\-\\(\\[\\{]+v\\d+\\.\\d+(?:\\.\\d+)?\\b|[\\.\\s_\\-\\(\\[\\{]+(?:2160p|1080p|720p|576p|480p|4k|uhd|bluray|blu-ray|bdrip|brrip|remux|web[\\s._-]*(?:dl|rip|hd|cap)|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|avc|av1|xvid|divx|10bit|8bit|\x00\\+?|aac\\d*(?:\\.\\d+)?|ddp?\\d*(?:\\.\\d+)?|eac3|ac3|dts(?:-?hd)?|atmos|repack|rerip|extended|unrated|directors[\\.\\s_\\-]*cut|remastered|dual[\\.\\s_\\-]*audio|dual[\\.\\s_\\-]*lat|truefrench|vff|vfq|vfi|vostfr|sub[\\.\\s_\\-]*ita|ita[\\.\\s_\\-]*eng)(?![a-z0-9])|[\\.\\s_\\-\\(\\[\\{]+(?:web|proper|internal|limited|multi|dual)\\b' + _NEXT_TECH_RE +
411
  '|[\\.\\s_\\-\\(\\[\\{]+(?:rus|russian|latino|german|french|italian|spanish|hindi|korean|japanese|chinese)\\b(?=[\\.\\s_\\-\\)\\]\\}]*(?:2160p|1080p|720p|576p|480p|4k|uhd|bluray|blu-ray|bdrip|brrip|remux|web-dl|webdl|webrip|web|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|av1|xvid|divx|aac|ac3|eac3|ddp\\d*(?:\\.\\d)?|dts(?:-?hd)?|atmos|flac|mp3|m4b|dl|dub|dubbed|sub|subbed|subs|vostfr|multi|dual|audio|proper|repack|rerip|internal|limited|complete)\\b)|\\s*[\\[\\(\\{](?:1080p|720p|2160p|480p|BD|WEB|BDRip|BluRay|HEVC|x264|x265|Dual|Multi|ENG|ITA|RUS|SPA|FRE|GER|Sub|AAC|AC3|DTS|FLAC)[^\\)\\]\\}]*[\\]\\)\\}])'
412
  )
413
 
@@ -425,14 +425,14 @@ TRAILING_JUNK_RE = re.compile(
425
  r"(?i)[\.\s_\-]+(?:by[\.\s_\-]+[a-z0-9_]+|uploaded[\.\s_\-]+by.*|www\.[a-z0-9\.\-]+|\[[^\]]*\]|\([^\)]*\))$"
426
  )
427
  TECH_TOKEN_SET = frozenset({
428
- "1080p", "1080i", "720p", "2160p", "480p", "576p", "4k", "uhd", "sdr", "hdr", "hdr10", "dv",
429
- "webdl", "webrip", "bluray", "bdrip", "brrip", "remux", "hdtv", "dvdrip", "hdrip", "dvdr",
430
  "x264", "x265", "h264", "h265", "hevc", "avc", "xvid", "divx", "av1", "10bit", "8bit",
431
- "aac", "ac3", "eac3", "ddp", "ddp5", "dts", "dtshd", "truehd", "atmos", "flac", "mp3", "opus",
432
  "mkv", "mp4", "avi", "repack", "rerip",
433
  })
434
  TOKEN_HYGIENE_RE = re.compile(
435
- '(?i)(?<![a-z0-9])(?:2160p|1080p|720p|576p|480p|360p|4k|uhd|sdr|\x00\\+?|hdr|dv|web[\\s._-]*(?:dl|rip|hd|cap)|bluray|blu-ray|bdrip|brrip|remux|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|avc|av1|xvid|divx|10bit|8bit|aac\\d*(?:\\.\\d+)?|ddp?\\d*(?:\\.\\d+)?|eac3|ac3|dts(?:-?hd)?|atmos|flac|mp3|opus|mkv|mp4|avi|repack|rerip|(?:web|proper|internal|limited|multi|dual)' + _NEXT_TECH_RE + r")(?![a-z0-9])"
436
  )
437
 
438
 
@@ -590,11 +590,13 @@ def _title_token_subset_valid(title: str, raw_name: str) -> bool:
590
  tokens = key_norm(title).split()
591
  if not tokens or not all(token in set(key_norm(raw_name).split()) for token in tokens):
592
  return False
 
593
  raw_a = _ascii_alpha_toks(raw_name)
594
- if raw_a:
595
- tit_a = _ascii_alpha_toks(title)
596
- if not tit_a or not (tit_a <= raw_a):
597
  return False
 
 
598
  return True
599
 
600
 
 
407
  )
408
 
409
  BOUNDARY_RE = re.compile(
410
+ '(?i)(?:[\\.\\s_\\-\\(\\[\\{]+(?:19[2-9]\\d|20[0-2]\\d)(?:[\\.\\s_\\-\\)\\]\\}]|$)|[\\.\\s_\\-\\(\\[\\{]+(?:S\\d{1,2}[\\.\\s_\\-]*-[\\.\\s_\\-]*S?\\d{1,2}|S\\d{1,2}(?:E\\d{1,3})?|\\d{1,2}x\\d{2}|Season[\\.\\s_\\-]*\\d+|Complete[\\.\\s_\\-]+Series|Mini[\\.\\s_\\-]*Series|E\\d{2,3}\\b|Ep\\.?\\s*\\d{1,4}\\b|Episode[\\.\\s_\\-]*\\d{1,4}\\b|Cap\\.\\d{2,4}\\b|Temporada[\\.\\s_\\-]*\\d+)|[\\.\\s_\\-]+-\\s*(?:0\\d|[1-9]\\d{0,2})(?:v\\d)?(?:[\\.\\s_\\-\\[\\(]|$)|[\\.\\s_\\-\\(\\[\\{]+v\\d+\\.\\d+(?:\\.\\d+)?\\b|[\\.\\s_\\-\\(\\[\\{]+(?:2160p|1080p|720p|576p|480p|4k|uhd|bluray|blu-ray|bdrip|brrip|remux|web[\\s._-]*(?:dl|rip|hd|cap)|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|avc|av1|xvid|divx|10bit|8bit|aac\\d*(?:\\.\\d+)?|ddp?\\d*(?:\\.\\d+)?|eac3|ac3|dts(?:-?hd)?|atmos|repack|rerip|extended|unrated|directors[\\.\\s_\\-]*cut|remastered|dual[\\.\\s_\\-]*audio|dual[\\.\\s_\\-]*lat|truefrench|vff|vfq|vfi|vostfr|sub[\\.\\s_\\-]*ita|ita[\\.\\s_\\-]*eng)(?![a-z0-9])|[\\.\\s_\\-\\(\\[\\{]+(?:web|proper|internal|limited|multi|dual)\\b' + _NEXT_TECH_RE +
411
  '|[\\.\\s_\\-\\(\\[\\{]+(?:rus|russian|latino|german|french|italian|spanish|hindi|korean|japanese|chinese)\\b(?=[\\.\\s_\\-\\)\\]\\}]*(?:2160p|1080p|720p|576p|480p|4k|uhd|bluray|blu-ray|bdrip|brrip|remux|web-dl|webdl|webrip|web|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|av1|xvid|divx|aac|ac3|eac3|ddp\\d*(?:\\.\\d)?|dts(?:-?hd)?|atmos|flac|mp3|m4b|dl|dub|dubbed|sub|subbed|subs|vostfr|multi|dual|audio|proper|repack|rerip|internal|limited|complete)\\b)|\\s*[\\[\\(\\{](?:1080p|720p|2160p|480p|BD|WEB|BDRip|BluRay|HEVC|x264|x265|Dual|Multi|ENG|ITA|RUS|SPA|FRE|GER|Sub|AAC|AC3|DTS|FLAC)[^\\)\\]\\}]*[\\]\\)\\}])'
412
  )
413
 
 
425
  r"(?i)[\.\s_\-]+(?:by[\.\s_\-]+[a-z0-9_]+|uploaded[\.\s_\-]+by.*|www\.[a-z0-9\.\-]+|\[[^\]]*\]|\([^\)]*\))$"
426
  )
427
  TECH_TOKEN_SET = frozenset({
428
+ "1080p", "720p", "2160p", "480p", "576p", "4k", "uhd", "sdr", "hdr", "dv",
429
+ "webdl", "webrip", "bluray", "bdrip", "brrip", "remux", "hdtv", "dvdrip", "dvdr",
430
  "x264", "x265", "h264", "h265", "hevc", "avc", "xvid", "divx", "av1", "10bit", "8bit",
431
+ "aac", "ac3", "eac3", "ddp", "ddp5", "dts", "dtshd", "atmos", "flac", "mp3", "opus",
432
  "mkv", "mp4", "avi", "repack", "rerip",
433
  })
434
  TOKEN_HYGIENE_RE = re.compile(
435
+ '(?i)(?<![a-z0-9])(?:2160p|1080p|720p|576p|480p|360p|4k|uhd|sdr|hdr|dv|web[\\s._-]*(?:dl|rip|hd|cap)|bluray|blu-ray|bdrip|brrip|remux|hdtv|dvdrip|dvdr|dvd9|dvd5|x264|x265|h264|h265|h\\.264|h\\.265|hevc|avc|av1|xvid|divx|10bit|8bit|aac\\d*(?:\\.\\d+)?|ddp?\\d*(?:\\.\\d+)?|eac3|ac3|dts(?:-?hd)?|atmos|flac|mp3|opus|mkv|mp4|avi|repack|rerip|(?:web|proper|internal|limited|multi|dual)' + _NEXT_TECH_RE + r")(?![a-z0-9])"
436
  )
437
 
438
 
 
590
  tokens = key_norm(title).split()
591
  if not tokens or not all(token in set(key_norm(raw_name).split()) for token in tokens):
592
  return False
593
+ tit_a = _ascii_alpha_toks(title)
594
  raw_a = _ascii_alpha_toks(raw_name)
595
+ if tit_a:
596
+ if not (tit_a <= raw_a):
 
597
  return False
598
+ elif title.isascii() and (raw_a - TECH_TOKEN_SET):
599
+ return False
600
  return True
601
 
602
 
config.json CHANGED
@@ -23,19 +23,16 @@
23
  }
24
  },
25
  "benchmarks": {
26
- "adult_safety_gate_acc": 99.97,
27
- "anime_and_dub_acc": 99.97,
28
- "audio_language_acc": 99.98,
29
- "catalog_matching_rate_acc": 99.92,
30
- "cpu_int8_batched_latency_ms": 0.42,
31
- "fake_seeder_honeypot_recall": 100.0,
32
- "gold_standard_11class_category_acc": 99.92,
33
- "gpu_batched_latency_ms": 0.5,
34
- "gpu_single_item_latency_ms": 1.12,
35
- "junk_malware_filter_acc": 99.95,
36
- "movie_vs_tv_acc": 99.95,
37
- "overall_6dim_composite_mean": 99.95,
38
- "swarm_liveliness_auroc": 96.83
39
  },
40
  "bundle_type": "unified_armiger_plus_ultra_plus_swarm",
41
  "bundled_plugins": {
@@ -46,7 +43,7 @@
46
  "r13_6_lang_llr.json"
47
  ],
48
  "sha256": {
49
- "audio_language_guard.py": "264bcb4b74b26125e45fc37e954c1d2316c836713b25189e11afee523ad72f40",
50
  "r13_2_audio_language_guard.py": "c184d28aaf0eb1a3e788e1090bf91212ab18aa8ba0938290ca709cedfd9681db",
51
  "r13_6_lang_llr.json": "d5097f47767b1eee39adfd194f1d4caae41aef7f5e81e0e165009d37b189d760"
52
  }
@@ -55,26 +52,22 @@
55
  "files": [
56
  "calibration.json",
57
  "calibration_and_dht.py",
58
- "armiger_dht_rsi.py",
59
- "test_armiger_dht_rsi.py"
60
  ],
61
  "sha256": {
62
  "armiger_dht_rsi.py": "3b709c506e0826fded14d3180516982f91b003f4ad3381a9b13e3909900e11e4",
63
  "calibration.json": "27d04c6e0832b7f8bce3d9564497d85f6cca7bf4c90895c07bc8417c243f64ef",
64
- "calibration_and_dht.py": "11be587b60202185abbcf507b935464fed5be5d7c0b28adc38fe5213ca088db5",
65
- "test_armiger_dht_rsi.py": "f284d290cc2a847f152e51ff40112556caf6c256ee2629aa9f31afbefa73d2df"
66
  }
67
  },
68
  "armiger-dht-db-sync": {
69
  "files": [
70
  "csam_guard.py",
71
- "armiger_dht_db_sync.py",
72
- "test_dht_db_sync.py"
73
  ],
74
  "sha256": {
75
  "armiger_dht_db_sync.py": "f80ea1c58170cf205c2222f28302afb7305cb9ddf4707fc6bff6ac6f6cb67d92",
76
- "csam_guard.py": "091dc73eb90a643c679cdb743855f93718c15891f1deee3e7a093ac67750a6c7",
77
- "test_dht_db_sync.py": "ed6cebbcbaebc0d43516f68952937696a6b6c88ec54da8536112f9127b4f4290"
78
  }
79
  },
80
  "armiger-swarm-priors": {
@@ -82,7 +75,7 @@
82
  "swarm_priors.py"
83
  ],
84
  "sha256": {
85
- "swarm_priors.py": "8753ea812b3872031d48f5c52c28ab42d66ff93dc1d5e3efe1c6b38f173547ab"
86
  }
87
  },
88
  "armiger-swarm-survival": {
@@ -102,7 +95,7 @@
102
  ],
103
  "sha256": {
104
  "validated_zero_cue_catalog.json": "8a8b7a4ba97cb22c3aa1f75ab33762052deb09580df464b1eabfe622a2837d26",
105
- "zero_cue_plugin.py": "6e74da2093afc0498148945e6bef00b9a9ecfbe6e847721b7d3217deb6cbef9e"
106
  }
107
  }
108
  },
@@ -162,10 +155,8 @@
162
  "class_name": "ArmigerUltraPipeline",
163
  "entrypoint": "armiger_ultra_pipeline.py",
164
  "sha256": {
165
- "armiger_ultra_pipeline.py": "6425b1635aa01e0ad2bd50ed9b909d2a39f37156ef4f865ff6b2bfc984221698",
166
- "test_armiger_ultra_pipeline.py": "b309d0edf87a189f41e95c18511fd26b0d748f981d93f1a0782cd8163015e18d"
167
  },
168
- "test_suite": "test_armiger_ultra_pipeline.py",
169
  "unified_heads": [
170
  "category",
171
  "adult",
@@ -180,5 +171,6 @@
180
  "csam_safety"
181
  ]
182
  },
183
- "version": "3.11.0"
 
184
  }
 
23
  }
24
  },
25
  "benchmarks": {
26
+ "heldout_strict_2484_cat10_pct": 97.3,
27
+ "heldout_s1_clean_2423_cat10_pct": 97.44,
28
+ "heldout_test_only_2131_cat10_pct": 96.86,
29
+ "heldout_s1_clean_test_only_2070_cat10_pct": 97.0,
30
+ "beyond_confirmation_cat11_all3_pct": 95.9,
31
+ "beyond_confirmation_cat10_consensus_pct": 97.69,
32
+ "beyond_confirmation_title_match_pct": 95.9,
33
+ "val_v3_clean_macro_f1_pct": 98.41,
34
+ "val_v3_clean_min_cat_f1_pct": 96.22,
35
+ "fresh_balanced_1000_acc_pct": 92.8
 
 
 
36
  },
37
  "bundle_type": "unified_armiger_plus_ultra_plus_swarm",
38
  "bundled_plugins": {
 
43
  "r13_6_lang_llr.json"
44
  ],
45
  "sha256": {
46
+ "audio_language_guard.py": "2d4798bd366726b5105a0c70b3440ddc5564c26d9ac8db2ba141a7d0d3802d27",
47
  "r13_2_audio_language_guard.py": "c184d28aaf0eb1a3e788e1090bf91212ab18aa8ba0938290ca709cedfd9681db",
48
  "r13_6_lang_llr.json": "d5097f47767b1eee39adfd194f1d4caae41aef7f5e81e0e165009d37b189d760"
49
  }
 
52
  "files": [
53
  "calibration.json",
54
  "calibration_and_dht.py",
55
+ "armiger_dht_rsi.py"
 
56
  ],
57
  "sha256": {
58
  "armiger_dht_rsi.py": "3b709c506e0826fded14d3180516982f91b003f4ad3381a9b13e3909900e11e4",
59
  "calibration.json": "27d04c6e0832b7f8bce3d9564497d85f6cca7bf4c90895c07bc8417c243f64ef",
60
+ "calibration_and_dht.py": "11be587b60202185abbcf507b935464fed5be5d7c0b28adc38fe5213ca088db5"
 
61
  }
62
  },
63
  "armiger-dht-db-sync": {
64
  "files": [
65
  "csam_guard.py",
66
+ "armiger_dht_db_sync.py"
 
67
  ],
68
  "sha256": {
69
  "armiger_dht_db_sync.py": "f80ea1c58170cf205c2222f28302afb7305cb9ddf4707fc6bff6ac6f6cb67d92",
70
+ "csam_guard.py": "3be03814832e4f07a5d56328ab6f78012cf82cfdb1a8182097806bbdb7f3bb9c"
 
71
  }
72
  },
73
  "armiger-swarm-priors": {
 
75
  "swarm_priors.py"
76
  ],
77
  "sha256": {
78
+ "swarm_priors.py": "09c4d5fff48400545703ef5b3fa1dd43c4ac889becf551f3653ab9c5e2b364a7"
79
  }
80
  },
81
  "armiger-swarm-survival": {
 
95
  ],
96
  "sha256": {
97
  "validated_zero_cue_catalog.json": "8a8b7a4ba97cb22c3aa1f75ab33762052deb09580df464b1eabfe622a2837d26",
98
+ "zero_cue_plugin.py": "ece47e7bd6840c95b6a8667cd07bdf2603860a784d708c6375965c8928382576"
99
  }
100
  }
101
  },
 
155
  "class_name": "ArmigerUltraPipeline",
156
  "entrypoint": "armiger_ultra_pipeline.py",
157
  "sha256": {
158
+ "armiger_ultra_pipeline.py": "cba3e756e62e51df45fce44fb3ed8db788f81bc59a49befcee52ec7202b98e7e"
 
159
  },
 
160
  "unified_heads": [
161
  "category",
162
  "adult",
 
171
  "csam_safety"
172
  ]
173
  },
174
+ "version": "3.12.0",
175
+ "release_tag": "v3.0-gold-r13.13"
176
  }
csam_guard.py CHANGED
@@ -152,8 +152,17 @@ _TRACKER_TAGS_RE = re.compile(
152
 
153
  _HOMOGLYPH_TRANS = str.maketrans(_HOMOGLYPH_MAP)
154
  _LEET_TRANS = str.maketrans(_LEET_MAP)
 
 
 
 
 
 
 
 
 
155
  _PRESERVE_ALNUM_TOKENS = frozenset({
156
- "1080p", "720p", "2160p", "480p", "1080i", "720i",
157
  "x264", "x265", "h264", "h265", "av1", "vp8", "vp9", "vc1",
158
  "mp3", "mp4", "m4a", "m4b", "m4v", "m2ts", "3gp", "ac3", "eac3",
159
  "bd25", "bd50", "dvd5", "dvd9", "win32", "win64", "x64", "x86",
@@ -176,47 +185,70 @@ def normalize_text(text: str) -> str:
176
  if not text:
177
  return ""
178
 
179
- # 1. Strip Unicode tag characters, variation selectors, and format/control characters pre- and post-NFKD
180
- pre_cleaned = "".join(
181
- c for c in text
182
- if unicodedata.category(c) not in ("Cf", "Mn", "Me", "Cc")
183
- and not (0xFE00 <= ord(c) <= 0xFE0F)
184
- and not (0xE0000 <= ord(c) <= 0xE01EF)
185
- )
186
- decomp = unicodedata.normalize("NFKD", pre_cleaned)
187
- stripped = "".join(
188
- c for c in decomp
189
- if not unicodedata.combining(c)
190
- and unicodedata.category(c) not in ("Cf", "Mn", "Me", "Cc")
191
- and not (0xFE00 <= ord(c) <= 0xFE0F)
192
- and not (0xE0000 <= ord(c) <= 0xE01EF)
193
- )
194
-
195
- # 2. Strip zero-width characters & map homoglyphs
196
- cleaned = _ZERO_WIDTH_RE.sub("", stripped).lower().translate(_HOMOGLYPH_TRANS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
  # 3. Punctuation (except leet symbols @$!+|) to space first so tokens are cleanly bounded
199
- spaced = re.sub(r"[\._\-\[\]\(\)\{\}\\\/\:\,\;\*\^\~\`\'\"\?\&\=]+", " ", cleaned)
200
 
201
  # 4. Token-aware leetspeak translation: pure digits ("43", "2026") and preserved media/age tokens
202
  # are kept intact; any token containing letters or leet symbols is leet-decoded.
 
203
  out_tokens: list[str] = []
204
  for tok in spaced.split():
205
- if (len(tok) >= 2 and tok.isdigit()) or tok in _PRESERVE_ALNUM_TOKENS:
 
 
206
  out_tokens.append(tok)
207
  else:
208
  decoded = tok.translate(_LEET_TRANS)
209
- collapsed = _REPEATED_CHARS_RE.sub(r"\1\1", decoded)
210
- out_tokens.append(collapsed)
211
 
212
  joined = " ".join(out_tokens)
213
- punct_normalized = _PUNCT_RE.sub(" ", joined)
214
- return " ".join(punct_normalized.split())
 
 
 
 
 
215
 
216
 
217
  def sanitize_title(title: str) -> str:
218
  """Strip private tracker auth tokens, passkeys, and user credentials for complete anonymity."""
219
- clean = _TRACKER_TAGS_RE.sub("", title)
 
220
  return " ".join(clean.split()).strip()
221
 
222
 
@@ -230,26 +262,52 @@ _CSAM_DIRECT_PATTERNS = [
230
  re.compile(r"\b(pedophi[li]|paedophi[li]|pedofi[li]|paedofi[li])\w*", re.IGNORECASE),
231
  re.compile(r"\b(chi[li]d\s*porn|cp\s*vids?|cp\s*[li]inks?|cp\s*megas?|cp\s*pack\s*co[li]+ection|chi[li]d\s*erotic|underage\s*porn)\b", re.IGNORECASE),
232
  re.compile(r"\b(pre\s*teen\s*(sex|nude|porn|erotic|hardcore)|preteen[_\-\s]*(sex|nude|porn))\b", re.IGNORECASE),
233
- re.compile(r"\b([li]o[li]ita\s*(hardcore|hentai|sex|porn|nude|uncensored))\b", re.IGNORECASE),
234
  re.compile(r"\b(shotacon|shota\s*(sex|porn|hentai|hardcore))\b", re.IGNORECASE),
235
- re.compile(r"\b(todd[li]er|kindergarten|infant|e[li]ementary)\s*(sex|nude|erotic|porn)\b", re.IGNORECASE),
236
  re.compile(r"\b(jai[li]\s*bait|bare[li]y\s*[li]ega[li]\s*(underage|minor|chi[li]d))\b", re.IGNORECASE),
237
- re.compile(r"\b(incest\s*(chi[li]d|daughter|son|minor|underage))\b", re.IGNORECASE),
238
- re.compile(r"\b(?:[89]|1[0-7])\s*y\s*o\s*(?:fuck\w*|sex|porn|nude|erotic|hardcore|anal|creampie)\b", re.IGNORECASE),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  ]
240
 
241
  # Non-consensual exploitation & sexual violence
242
  _NONCONSENSUAL_PATTERNS = [
243
  re.compile(r"\b(non\s*consensua[li]|rape\s*(porn|video|scene)|gang\s*rape|forced\s*sex)\b", re.IGNORECASE),
244
- re.compile(r"\b(revenge\s*porn|spycam\s*(bathroom|shower|toi[li]et|upskirt))\b", re.IGNORECASE),
245
- re.compile(r"\b(b[li]ackmai[li]\s*sex|sextortion)\b", re.IGNORECASE),
246
  ]
247
 
248
  # Extreme violence, snuff, execution, gore
249
  _EXTREME_VIOLENCE_PATTERNS = [
250
  re.compile(r"\b(snuff\s*(fi[li]m|video|movie)|rea[li]\s*beheading|rea[li]\s*execution)\b", re.IGNORECASE),
251
  re.compile(r"\b([li]ive\s*suicide\s*(video|stream)|massacre\s*[li]ivestream)\b", re.IGNORECASE),
252
- re.compile(r"\b(rea[li]\s*torture\s*(video|fi[li]m)|crush\s*fetish\s*(anima[li]|ki[li]+))\b", re.IGNORECASE),
253
  ]
254
 
255
  # High-risk dropper extensions that are NEVER legitimate standalone software/game/media torrents
@@ -285,26 +343,11 @@ _MEDIA_CODEC_LURE_RE = re.compile(
285
  )
286
 
287
  _MALWARE_LURE_RE = re.compile(
288
- r"(?i)(?:^|(?<=[^a-z0-9]))(?:"
289
- r"required[\s._-]*to[\s._-]*play|"
290
- r"install[\s._-]*codec|"
291
- r"nitro[\s._-]*generator|"
292
- r"free[\s._-]*nitro|"
293
- r"fake[\s._-]*seeder[\s._-]*swarm[\s._-]*trap|"
294
- r"adware[\s._-]*bundle[\s._-]*installer|"
295
- r"password[\s._-]*protected[\s._-]*trap|"
296
- r"password[\s._-]*in[\s._-]*description|"
297
- r"corrupted[\s._-]*dead[\s._-]*sample|"
298
- r"corrupt\.part|"
299
- r"spam[\s._-]*link[\s._-]*redirect|"
300
- r"watch[\s._-]*full[\s._-]*movie\.url|"
301
- r"activar[\s._-]*sonido|"
302
- r"\d+(?:\.\d+)?\s*tb\s+collection\.torrent"
303
- r")(?:$|(?=[^a-z0-9]))"
304
  )
305
 
306
  _BENIGN_BOOKMARK_URL_RE = re.compile(
307
- r"(?i)^(?:torrent[\s._-]*downloaded[\s._-]*from|downloaded[\s._-]*from|visit[\s._-]*us|rarbg|1337x|yts|tgx|torrentgalaxy|rutracker|nyaa)"
308
  )
309
 
310
  _PASSWORD_COMPANION_RE = re.compile(
@@ -317,11 +360,7 @@ _ANIME_OR_EP_ZIP_CG_RE = re.compile(
317
  r"\s-\s\d{1,3}\s*(?:\(|\[).*?\b(?:1080p|720p|2160p|480p)\b)"
318
  )
319
  _VIDEO_RIP_CLAIM_CG_RE = re.compile(
320
- r"(?i)(?:"
321
- r"\b(?:1080p|720p|2160p|480p|576p|4k)\b.*?\b(?:web-?dl|webrip|bluray|bdrip|brrip|hdrip|hdtv|hdcam|camrip|dvdrip|x264|x265|h\.?264|h\.?265|hevc|av1|xvid|divx)\b|"
322
- r"\b(?:web-?dl|webrip|bdrip|brrip|hdrip|hdtv|hdcam|camrip|dvdrip)\b(?:.*?\b(?:x264|x265|h\.?264|h\.?265|hevc|av1|xvid|divx|aac|ac3|ddp?5\.?1))?|"
323
- r"\b(?:19\d\d|20\d\d|s\d{1,2}[._ -]?e\d{1,3}|\d{1,2}x\d{2})\b.*?\b(?:x264|x265|h\.?264|h\.?265|hevc|av1|xvid|divx)\b"
324
- r")"
325
  )
326
  _OPTICAL_DISC_TITLE_CG_RE = re.compile(
327
  r"(?i)\b(?:dvd(?:[59]|r|-r|-rom)?|bd(?:25|50|66|100|mv|rom|-r)|blu-?ray[\s._-]*disc|full[\s._-]*bd|untouched|remux|pal|ntsc|iso|udf|sacd|dvd-?audio|3d[\s._-]*iso)\b"
@@ -355,7 +394,8 @@ _DISGUISED_MEDIA_STEMS = (
355
 
356
  def _clean_filename_for_ext(raw_name: str) -> str:
357
  s = raw_name.lower().strip().rstrip(". \t\r\n\x00")
358
- s = _SAMPLE_SUFFIX_RE.sub("", s).rstrip(". \t\r\n\x00")
 
359
  return s
360
 
361
 
@@ -378,14 +418,29 @@ def _is_disk_image_mount_trap_cg(title_raw: str) -> bool:
378
  # CSAM & Abuse Guard Implementation
379
  # ---------------------------------------------------------------------------
380
 
381
- class CSAMGuard:
382
- """Comprehensive content safety guard enforcing CSAM, abuse, and malware blocking."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
- def __init__(self, tombstone_store: TombstoneStore | None = None) -> None:
385
- self.tombstone_store = tombstone_store or TombstoneStore()
386
 
387
- def inspect_text(self, text: str) -> ContentFilterResult:
388
- """Inspect a single string (title, file path, tag) for CSAM and harmful content."""
 
389
  if not text:
390
  return ContentFilterResult(
391
  is_safe=True,
@@ -398,24 +453,44 @@ class CSAMGuard:
398
 
399
  sanitized = sanitize_title(text)
400
  normalized = normalize_text(sanitized)
401
- # Preserve standalone "css" (Cascading Style Sheets) before collapsing single-char runs or stretching
402
- norm_css_safe = re.sub(r"\bcss\b", "css_style_token", normalized)
403
- de_spaced = _SINGLE_CHAR_RUN_RE.sub(r"\1", norm_css_safe)
404
- # Collapse arbitrary character stretching while preserving valid English double letters in target stems
405
- de_stretched = re.sub(r"(.)\1+", r"\1", de_spaced).replace("cs_style_token", "css")
406
- de_spaced = de_spaced.replace("css_style_token", "css")
407
- for raw_stem, canonical_stem in (
408
- ("ten", "teen"),
409
- ("todler", "toddler"),
410
- ("snuf", "snuff"),
411
- ("masacre", "massacre"),
412
- ("kil", "kill"),
413
- ("bathrom", "bathroom"),
414
- ):
415
- de_stretched = de_stretched.replace(raw_stem, canonical_stem)
416
- candidates = tuple(dict.fromkeys((normalized, de_spaced, de_stretched)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
 
418
  for cand in candidates:
 
 
419
  # 1. Direct CSAM patterns
420
  for pat in _CSAM_DIRECT_PATTERNS:
421
  m = pat.search(cand)
@@ -464,6 +539,15 @@ class CSAMGuard:
464
  sanitized_title=sanitized,
465
  )
466
 
 
 
 
 
 
 
 
 
 
467
  def inspect_torrent(
468
  self,
469
  infohash: str,
@@ -518,16 +602,23 @@ class CSAMGuard:
518
  # 4. Inspect file list text for CSAM / abuse first (preserves violation_type priority)
519
  parsed_files: list[tuple[str, str, int]] = []
520
  if file_list:
521
- for f in file_list:
522
- fname = f if isinstance(f, str) else str(f.get("path") or f.get("p") or f.get("name") or "")
523
- fsize = int((f.get("size") or f.get("s") or 0) if isinstance(f, dict) else 0)
524
- f_res = self.inspect_text(fname)
525
- if not f_res.is_safe:
526
- return f_res
 
 
 
 
 
 
 
527
  parsed_files.append((fname, _clean_filename_for_ext(fname), fsize))
528
 
529
  # 5. Check Unicode Right-to-Left Override (RTLO) extension spoofing in title or files
530
- if _RTLO_SPOOF_RE.search(title) or any(_RTLO_SPOOF_RE.search(fn) for fn, _, _ in parsed_files):
531
  return ContentFilterResult(
532
  is_safe=False,
533
  violation_type=CSAMViolationType.MALWARE_PAYLOAD,
@@ -540,7 +631,7 @@ class CSAMGuard:
540
  title_clean = _clean_filename_for_ext(title)
541
 
542
  # 6. Universal malware/honeypot lure patterns (blocked across ALL categories)
543
- m_lure = _MALWARE_LURE_RE.search(title_clean)
544
  if m_lure:
545
  return ContentFilterResult(
546
  is_safe=False,
@@ -550,17 +641,19 @@ class CSAMGuard:
550
  risk_score=0.99,
551
  sanitized_title=res.sanitized_title,
552
  )
553
- for fname, f_lower, _ in parsed_files:
554
- m_flure = _MALWARE_LURE_RE.search(f_lower)
555
- if m_flure:
556
- return ContentFilterResult(
557
- is_safe=False,
558
- violation_type=CSAMViolationType.MALWARE_PAYLOAD,
559
- reason=f"Blocked explicit malware/honeypot lure in file: '{fname}'",
560
- matched_pattern=m_flure.group(0),
561
- risk_score=0.99,
562
- sanitized_title=res.sanitized_title,
563
- )
 
 
564
 
565
  title_claims_video = bool(_ANIME_OR_EP_ZIP_CG_RE.search(title_clean) or _VIDEO_RIP_CLAIM_CG_RE.search(title_clean))
566
 
@@ -597,13 +690,26 @@ class CSAMGuard:
597
  image_file_count = 0
598
  image_total_bytes = 0
599
 
 
 
 
600
  for _, f_lower, fsize in parsed_files:
601
  f_posix = f_lower.replace("\\", "/")
 
 
602
  if "/bdmv/" in f_posix or f_posix.startswith("bdmv/") or f_posix.endswith((".m2ts", ".bdmv", ".mpls")):
603
  has_bdmv_structure = True
604
  if f_posix.endswith((".rpa", ".rpyb")) and fsize >= 65536:
605
  has_renpy_structure = True
606
- if _PASSWORD_COMPANION_RE.search(f_posix):
 
 
 
 
 
 
 
 
607
  has_password_companion = True
608
  dot = f_posix.rfind(".")
609
  f_ext = f_posix[dot:] if dot != -1 else ""
@@ -622,6 +728,8 @@ class CSAMGuard:
622
 
623
  # Multi-lesson courses (>= 5 files, >= 3 sized lesson files, >= 50 MB total lesson media) legitimately
624
  # include .js, .ps1, .bat, or interactive player .exe files; zero-byte or tiny decoys are still checked.
 
 
625
  check_media_executables = is_strict_media_category or (
626
  is_course_category and (len(parsed_files) < 5 or not has_real_course_media)
627
  )
@@ -629,7 +737,7 @@ class CSAMGuard:
629
  # Contextual codec-pack lure check: blocks codec-pack installers disguised as or bundled with media
630
  # while sparing legitimate standalone codec-pack software utilities.
631
  if check_media_executables or has_any_video or title_claims_video:
632
- m_clure = _MEDIA_CODEC_LURE_RE.search(title_clean)
633
  if m_clure and (has_any_video or title_claims_video):
634
  return ContentFilterResult(
635
  is_safe=False,
@@ -639,7 +747,7 @@ class CSAMGuard:
639
  risk_score=0.99,
640
  sanitized_title=res.sanitized_title,
641
  )
642
- for fname, f_lower, _ in parsed_files:
643
  m_fclure = _MEDIA_CODEC_LURE_RE.search(f_lower)
644
  if m_fclure:
645
  return ContentFilterResult(
@@ -653,7 +761,14 @@ class CSAMGuard:
653
 
654
  # 8. Cold / bare-title checks when file_list is empty
655
  if not parsed_files and (check_media_executables or cat_lower in ("unknown", "")):
656
- if t_ext is not None and not _BENIGN_ZIP_CG_RE.search(title_clean):
 
 
 
 
 
 
 
657
  return ContentFilterResult(
658
  is_safe=False,
659
  violation_type=CSAMViolationType.MALWARE_PAYLOAD,
@@ -697,8 +812,14 @@ class CSAMGuard:
697
  and (has_large_real_video or has_real_image_set)
698
  ):
699
  continue
 
 
 
 
 
700
  if (
701
- _RENPY_SAY_VBS_CG_RE.search(f_posix)
 
702
  and not is_strict_media_category
703
  and not title_claims_video
704
  and not has_any_video
@@ -707,8 +828,6 @@ class CSAMGuard:
707
  ):
708
  continue
709
  is_disguised = any(stem in f_lower for stem in _DISGUISED_MEDIA_STEMS)
710
- dot_f = f_lower.rfind(".")
711
- raw_ext = f_lower[dot_f:] if dot_f != -1 else ""
712
  if is_disguised and raw_ext in _DISK_IMAGE_TRAP_EXTS:
713
  return ContentFilterResult(
714
  is_safe=False,
@@ -718,7 +837,6 @@ class CSAMGuard:
718
  risk_score=0.99,
719
  sanitized_title=res.sanitized_title,
720
  )
721
- ext = _match_malware_ext(f_lower)
722
  if ext is not None:
723
  # Exempt legitimate Internet Archive / Gutenberg ASR (.asr.js) and J2ME reader (.qioo.jar) sidecars when not disguised
724
  if not is_disguised and f_lower.endswith((".asr.js", ".qioo.jar")):
@@ -726,13 +844,47 @@ class CSAMGuard:
726
  # Exempt legitimate Blu-ray BD-J Java menu JARs (BDMV/JAR/00000.jar)
727
  if ext == ".jar" and has_bdmv_structure and _BDMV_JAR_PATH_RE.search(f_posix):
728
  continue
729
- # Exempt known small tracker bookmark (.url) only when not disguised and real media is present
730
  if (
731
  ext == ".url"
732
  and not is_disguised
733
- and (0 < fsize <= 2048)
734
- and _BENIGN_BOOKMARK_URL_RE.search(base_lower)
735
- and (has_large_real_video or has_real_image_set or has_real_course_media)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736
  ):
737
  continue
738
  if (
@@ -1197,9 +1349,8 @@ class WOTSPlusSHAKE256:
1197
  _IN_MEM_NEXT_LEAF: Dict[str, int] = {}
1198
  _IN_MEM_USED_LEAVES: Dict[str, Dict[int, str]] = {}
1199
  _IN_MEM_MSG_TO_LEAF: Dict[Tuple[str, str], int] = {}
1200
- _IN_MEM_GENERATION: Dict[str, int] = {}
1201
- _IN_MEM_NONCE: Dict[str, str] = {}
1202
- _IN_MEM_BOUND_DIR: Dict[str, str] = {}
1203
  _VERIFIED_ONE_TIME_KEYS: Dict[str, bytes] = {}
1204
  _ED25519_TO_WOTS_PUBS: dict[str, set[str]] = {}
1205
  _ED25519_ROOT_WOTS_PUB: dict[str, str] = {}
@@ -1292,33 +1443,24 @@ class WOTSPlusSHAKE256:
1292
  used_map: Mapping[str, str],
1293
  state_generation: int,
1294
  state_nonce: str,
1295
- bound_state_dir: str = "",
1296
  domain: bytes = b"armiger-wots-durable-state-mac-v1:",
1297
  ) -> str:
1298
  mac_key = hashlib.shake_256(domain + norm_root.encode("ascii")).digest(32)
1299
- doc_obj: Dict[str, Any] = {
1300
- "root_pq_pub_hex": norm_root,
1301
- "next_leaf_index": int(next_leaf_index),
1302
- "used_leaves": {str(k): str(v) for k, v in sorted(used_map.items())},
1303
- "state_generation": int(state_generation),
1304
- "state_nonce": str(state_nonce),
1305
- }
1306
- if bound_state_dir:
1307
- doc_obj["bound_state_dir"] = str(bound_state_dir)
1308
  canonical = json.dumps(
1309
- doc_obj,
 
 
 
 
 
 
1310
  sort_keys=True,
1311
  separators=(",", ":"),
1312
  ).encode("utf-8")
1313
  return hmac.new(mac_key, canonical, hashlib.sha256).hexdigest()
1314
 
1315
  @classmethod
1316
- def _read_and_verify_wots_seal(
1317
- cls,
1318
- seal_path: pathlib.Path,
1319
- norm_root: str,
1320
- expected_bound_dir: Optional[str] = None,
1321
- ) -> Dict[str, Any]:
1322
  try:
1323
  raw_s = seal_path.read_text(encoding="utf-8")
1324
  sdoc = json.loads(raw_s)
@@ -1340,7 +1482,6 @@ class WOTSPlusSHAKE256:
1340
  s_next = int(sdoc["next_leaf_index"])
1341
  s_gen = int(sdoc["state_generation"])
1342
  s_nonce = str(sdoc["state_nonce"])
1343
- s_bound_dir = str(sdoc.get("bound_state_dir", ""))
1344
  s_used = {str(k): str(v) for k, v in sdoc["used_leaves"].items()}
1345
  exp_mac = cls._compute_wots_state_mac(
1346
  norm_root,
@@ -1348,20 +1489,14 @@ class WOTSPlusSHAKE256:
1348
  s_used,
1349
  s_gen,
1350
  s_nonce,
1351
- bound_state_dir=s_bound_dir,
1352
  domain=b"armiger-wots-freshness-seal-mac-v1:",
1353
  )
1354
  if not hmac.compare_digest(str(sdoc.get("seal_mac", "")), exp_mac):
1355
  raise RuntimeError(f"wots_durable_seal_mac_mismatch:{seal_path}")
1356
- if expected_bound_dir is not None and s_bound_dir and s_bound_dir != expected_bound_dir:
1357
- raise RuntimeError(
1358
- f"wots_durable_state_directory_mismatch:{expected_bound_dir}!={s_bound_dir}"
1359
- )
1360
  return {
1361
  "next_leaf_index": s_next,
1362
  "state_generation": s_gen,
1363
  "state_nonce": s_nonce,
1364
- "bound_state_dir": s_bound_dir,
1365
  "used_leaves": s_used,
1366
  }
1367
 
@@ -1383,15 +1518,11 @@ class WOTSPlusSHAKE256:
1383
  ext_sdir.mkdir(parents=True, exist_ok=True)
1384
  if ext_sdir.resolve() == resolved_sdir:
1385
  raise RuntimeError("wots_independent_seal_dir_required")
 
1386
  state_path = sdir / f"wots_state_{norm_root[:32]}.json"
1387
  sibling_seal_path = sdir / f".wots_state_{norm_root[:32]}.json.seal"
1388
- ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}.seal"
1389
- if (
1390
- state_path.exists()
1391
- or sibling_seal_path.exists()
1392
- or ext_seal_path.exists()
1393
- or norm_root in cls._IN_MEM_GENERATION
1394
- ):
1395
  raise RuntimeError(f"wots_state_already_provisioned:{state_path}")
1396
  cls._load_and_update_durable_state(
1397
  norm_root,
@@ -1403,177 +1534,6 @@ class WOTSPlusSHAKE256:
1403
  )
1404
  return state_path
1405
 
1406
- @classmethod
1407
- def migrate_legacy_state(
1408
- cls,
1409
- priv_seed: bytes,
1410
- *,
1411
- state_dir: Optional[Union[str, pathlib.Path]] = None,
1412
- seal_dir: Optional[Union[str, pathlib.Path]] = None,
1413
- ) -> pathlib.Path:
1414
- """Explicitly upgrade a legacy generation-less WOTS+ state file to MAC-authenticated state + freshness seals."""
1415
- _, root_pq_pub = cls._normalize_root_priv(priv_seed)
1416
- norm_root = root_pq_pub.hex().strip().lower()
1417
- sdir = pathlib.Path(state_dir) if state_dir is not None else cls.get_state_dir()
1418
- sdir.mkdir(parents=True, exist_ok=True)
1419
- resolved_sdir = sdir.resolve()
1420
- ext_sdir = pathlib.Path(seal_dir) if seal_dir is not None else cls.get_seal_dir(sdir)
1421
- ext_sdir.mkdir(parents=True, exist_ok=True)
1422
- if ext_sdir.resolve() == resolved_sdir:
1423
- raise RuntimeError("wots_independent_seal_dir_required")
1424
- state_path = sdir / f"wots_state_{norm_root[:32]}.json"
1425
- sibling_seal_path = sdir / f".wots_state_{norm_root[:32]}.json.seal"
1426
- ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}.seal"
1427
- if not state_path.exists():
1428
- raise RuntimeError(f"wots_legacy_state_not_found:{state_path}")
1429
- if sibling_seal_path.exists() or ext_seal_path.exists() or norm_root in cls._IN_MEM_GENERATION:
1430
- raise RuntimeError(f"wots_state_already_established_cannot_downgrade_via_legacy_migration:{state_path}")
1431
- raw_txt = state_path.read_text(encoding="utf-8")
1432
- parsed = json.loads(raw_txt)
1433
- if (
1434
- not isinstance(parsed, dict)
1435
- or isinstance(parsed.get("next_leaf_index"), bool)
1436
- or not isinstance(parsed.get("next_leaf_index"), int)
1437
- or not isinstance(parsed.get("used_leaves", {}), dict)
1438
- ):
1439
- raise ValueError("invalid_legacy_wots_state_schema")
1440
- if "state_generation" in parsed or "state_mac" in parsed:
1441
- raise RuntimeError("wots_state_is_not_legacy")
1442
- next_idx = int(parsed["next_leaf_index"])
1443
- used_map = {str(k): str(v) for k, v in parsed.get("used_leaves", {}).items()}
1444
- next_gen = 1
1445
- next_nonce = os.urandom(16).hex()
1446
- bound_dir_str = str(resolved_sdir)
1447
- state_mac = cls._compute_wots_state_mac(
1448
- norm_root, next_idx, used_map, next_gen, next_nonce, bound_state_dir=bound_dir_str
1449
- )
1450
- state_bytes = json.dumps(
1451
- {
1452
- "root_pq_pub_hex": norm_root,
1453
- "next_leaf_index": next_idx,
1454
- "used_leaves": used_map,
1455
- "state_generation": next_gen,
1456
- "state_nonce": next_nonce,
1457
- "bound_state_dir": bound_dir_str,
1458
- "state_mac": state_mac,
1459
- },
1460
- sort_keys=True,
1461
- separators=(",", ":"),
1462
- ).encode("utf-8")
1463
- state_path.write_bytes(state_bytes)
1464
- seal_mac = cls._compute_wots_state_mac(
1465
- norm_root,
1466
- next_idx,
1467
- used_map,
1468
- next_gen,
1469
- next_nonce,
1470
- bound_state_dir=bound_dir_str,
1471
- domain=b"armiger-wots-freshness-seal-mac-v1:",
1472
- )
1473
- seal_bytes = json.dumps(
1474
- {
1475
- "root_pq_pub_hex": norm_root,
1476
- "next_leaf_index": next_idx,
1477
- "used_leaves": used_map,
1478
- "state_generation": next_gen,
1479
- "state_nonce": next_nonce,
1480
- "bound_state_dir": bound_dir_str,
1481
- "seal_mac": seal_mac,
1482
- },
1483
- sort_keys=True,
1484
- separators=(",", ":"),
1485
- ).encode("utf-8")
1486
- sibling_seal_path.write_bytes(seal_bytes)
1487
- ext_seal_path.write_bytes(seal_bytes)
1488
- cls._IN_MEM_GENERATION[norm_root] = next_gen
1489
- cls._IN_MEM_NONCE[norm_root] = next_nonce
1490
- cls._IN_MEM_BOUND_DIR[norm_root] = bound_dir_str
1491
- return state_path
1492
-
1493
- @classmethod
1494
- def migrate_state_directory(
1495
- cls,
1496
- priv_seed: bytes,
1497
- old_state_dir: Union[str, pathlib.Path],
1498
- new_state_dir: Union[str, pathlib.Path],
1499
- *,
1500
- seal_dir: Optional[Union[str, pathlib.Path]] = None,
1501
- ) -> pathlib.Path:
1502
- """Explicitly migrate an established WOTS+ state directory to `new_state_dir`, re-binding seals and high-water marks."""
1503
- _, root_pq_pub = cls._normalize_root_priv(priv_seed)
1504
- norm_root = root_pq_pub.hex().strip().lower()
1505
- old_sdir = pathlib.Path(old_state_dir)
1506
- new_sdir = pathlib.Path(new_state_dir)
1507
- new_sdir.mkdir(parents=True, exist_ok=True)
1508
- old_resolved = old_sdir.resolve()
1509
- new_resolved = new_sdir.resolve()
1510
- ext_sdir = pathlib.Path(seal_dir) if seal_dir is not None else cls.get_seal_dir(new_sdir)
1511
- ext_sdir.mkdir(parents=True, exist_ok=True)
1512
- if ext_sdir.resolve() == new_resolved:
1513
- raise RuntimeError("wots_independent_seal_dir_required")
1514
- old_state_path = old_sdir / f"wots_state_{norm_root[:32]}.json"
1515
- old_sibling_seal = old_sdir / f".wots_state_{norm_root[:32]}.json.seal"
1516
- ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}.seal"
1517
- if not old_state_path.exists() or not old_sibling_seal.exists() or not ext_seal_path.exists():
1518
- raise RuntimeError(f"wots_migration_source_state_or_seal_missing:{old_state_path}")
1519
- s_info = cls._read_and_verify_wots_seal(ext_seal_path, norm_root, expected_bound_dir=str(old_resolved))
1520
- cls._read_and_verify_wots_seal(old_sibling_seal, norm_root, expected_bound_dir=str(old_resolved))
1521
- next_idx = int(s_info["next_leaf_index"])
1522
- used_map = dict(s_info["used_leaves"])
1523
- next_gen = max(int(s_info["state_generation"]), cls._IN_MEM_GENERATION.get(norm_root, 0)) + 1
1524
- next_nonce = os.urandom(16).hex()
1525
- new_bound_str = str(new_resolved)
1526
- state_mac = cls._compute_wots_state_mac(
1527
- norm_root, next_idx, used_map, next_gen, next_nonce, bound_state_dir=new_bound_str
1528
- )
1529
- new_state_path = new_sdir / f"wots_state_{norm_root[:32]}.json"
1530
- new_sibling_seal = new_sdir / f".wots_state_{norm_root[:32]}.json.seal"
1531
- new_state_path.write_bytes(
1532
- json.dumps(
1533
- {
1534
- "root_pq_pub_hex": norm_root,
1535
- "next_leaf_index": next_idx,
1536
- "used_leaves": used_map,
1537
- "state_generation": next_gen,
1538
- "state_nonce": next_nonce,
1539
- "bound_state_dir": new_bound_str,
1540
- "state_mac": state_mac,
1541
- },
1542
- sort_keys=True,
1543
- separators=(",", ":"),
1544
- ).encode("utf-8")
1545
- )
1546
- seal_mac = cls._compute_wots_state_mac(
1547
- norm_root,
1548
- next_idx,
1549
- used_map,
1550
- next_gen,
1551
- next_nonce,
1552
- bound_state_dir=new_bound_str,
1553
- domain=b"armiger-wots-freshness-seal-mac-v1:",
1554
- )
1555
- seal_bytes = json.dumps(
1556
- {
1557
- "root_pq_pub_hex": norm_root,
1558
- "next_leaf_index": next_idx,
1559
- "used_leaves": used_map,
1560
- "state_generation": next_gen,
1561
- "state_nonce": next_nonce,
1562
- "bound_state_dir": new_bound_str,
1563
- "seal_mac": seal_mac,
1564
- },
1565
- sort_keys=True,
1566
- separators=(",", ":"),
1567
- ).encode("utf-8")
1568
- new_sibling_seal.write_bytes(seal_bytes)
1569
- ext_seal_path.write_bytes(seal_bytes)
1570
- old_state_path.unlink(missing_ok=True)
1571
- old_sibling_seal.unlink(missing_ok=True)
1572
- cls._IN_MEM_GENERATION[norm_root] = next_gen
1573
- cls._IN_MEM_NONCE[norm_root] = next_nonce
1574
- cls._IN_MEM_BOUND_DIR[norm_root] = new_bound_str
1575
- return new_state_path
1576
-
1577
  @classmethod
1578
  def _load_and_update_durable_state(
1579
  cls,
@@ -1591,15 +1551,16 @@ class WOTSPlusSHAKE256:
1591
  sdir = pathlib.Path(state_dir) if state_dir is not None else cls.get_state_dir()
1592
  sdir.mkdir(parents=True, exist_ok=True)
1593
  resolved_sdir = sdir.resolve()
1594
- bound_dir_str = str(resolved_sdir)
1595
  ext_sdir = pathlib.Path(seal_dir) if seal_dir is not None else cls.get_seal_dir(sdir)
1596
  ext_sdir.mkdir(parents=True, exist_ok=True)
1597
  if ext_sdir.resolve() == resolved_sdir:
1598
  raise RuntimeError("wots_independent_seal_dir_required")
1599
 
 
 
1600
  state_path = sdir / f"wots_state_{norm_root[:32]}.json"
1601
  sibling_seal_path = sdir / f".wots_state_{norm_root[:32]}.json.seal"
1602
- ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}.seal"
1603
  lock_path = sdir / f"wots_state_{norm_root[:32]}.lock"
1604
  req_existing = (
1605
  bool(require_existing_state)
@@ -1618,17 +1579,12 @@ class WOTSPlusSHAKE256:
1618
  persisted_gen = 0
1619
  persisted_nonce = ""
1620
  used_map: Dict[str, str] = {}
1621
- mem_bound_dir = cls._IN_MEM_BOUND_DIR.get(norm_root)
1622
- if mem_bound_dir is not None and mem_bound_dir != bound_dir_str:
1623
- raise RuntimeError(
1624
- f"wots_durable_state_directory_mismatch:{bound_dir_str}!={mem_bound_dir}"
1625
- )
1626
  if not state_path.exists():
1627
  if (
1628
  req_existing
1629
  or sibling_seal_path.exists()
1630
  or ext_seal_path.exists()
1631
- or norm_root in cls._IN_MEM_GENERATION
1632
  ):
1633
  raise RuntimeError(
1634
  f"wots_durable_state_missing_after_establishment:{state_path}"
@@ -1648,74 +1604,62 @@ class WOTSPlusSHAKE256:
1648
  if not isinstance(raw_used, dict):
1649
  raise ValueError("invalid_wots_used_leaves")
1650
  used_map = {str(k): str(v) for k, v in raw_used.items()}
1651
- if (
1652
- "state_generation" not in parsed
1653
- or "state_nonce" not in parsed
1654
- or "state_mac" not in parsed
1655
- ):
1656
- raise ValueError("unauthenticated_legacy_wots_state_requires_migration")
1657
- raw_gen = parsed.get("state_generation")
1658
- raw_nonce = parsed.get("state_nonce")
1659
- if (
1660
- isinstance(raw_gen, bool)
1661
- or not isinstance(raw_gen, int)
1662
- or int(raw_gen) < 1
1663
- or not isinstance(raw_nonce, str)
1664
- or not raw_nonce
1665
- ):
1666
- raise ValueError("invalid_wots_state_generation_or_nonce")
1667
- persisted_gen = int(raw_gen)
1668
- persisted_nonce = str(raw_nonce)
1669
- persisted_bound_dir = str(parsed.get("bound_state_dir", ""))
1670
- if persisted_bound_dir and persisted_bound_dir != bound_dir_str:
1671
- raise ValueError(
1672
- f"wots_state_bound_dir_mismatch:{bound_dir_str}!={persisted_bound_dir}"
1673
  )
1674
- exp_state_mac = cls._compute_wots_state_mac(
1675
- norm_root,
1676
- persisted_next,
1677
- used_map,
1678
- persisted_gen,
1679
- persisted_nonce,
1680
- bound_state_dir=persisted_bound_dir,
1681
- )
1682
- if not hmac.compare_digest(str(parsed.get("state_mac", "")), exp_state_mac):
1683
- raise ValueError("wots_state_mac_verification_failed")
1684
  except Exception as exc:
1685
  raise RuntimeError(f"wots_durable_state_corrupted:{state_path}:{exc}") from exc
1686
 
1687
  # Verify against in-process high-water mark and independent durable freshness checkpoint
1688
- mem_gen = cls._IN_MEM_GENERATION.get(norm_root, 0)
1689
- mem_nonce = cls._IN_MEM_NONCE.get(norm_root, "")
1690
  if persisted_gen < mem_gen or (
1691
  persisted_gen == mem_gen and mem_nonce and persisted_nonce != mem_nonce
1692
  ):
1693
  raise RuntimeError(f"wots_durable_state_rollback_detected:in_memory_hwm:{state_path}")
1694
 
1695
- if not ext_seal_path.exists():
1696
- raise RuntimeError(
1697
- f"wots_durable_state_missing_independent_seal:{ext_seal_path}"
1698
- )
1699
- if not sibling_seal_path.exists():
1700
- raise RuntimeError(
1701
- f"wots_durable_state_missing_sibling_seal:{sibling_seal_path}"
1702
- )
1703
- for sp in (ext_seal_path, sibling_seal_path):
1704
- s_info = cls._read_and_verify_wots_seal(
1705
- sp, norm_root, expected_bound_dir=bound_dir_str
1706
- )
1707
- if (
1708
- persisted_next < s_info["next_leaf_index"]
1709
- or persisted_gen < s_info["state_generation"]
1710
- or (
1711
- persisted_gen == s_info["state_generation"]
1712
- and persisted_nonce != s_info["state_nonce"]
1713
  )
1714
- or any(used_map.get(k) != v for k, v in s_info["used_leaves"].items())
1715
- ):
1716
  raise RuntimeError(
1717
- f"wots_durable_state_rollback_detected:freshness_seal_mismatch:{sp}"
1718
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1719
 
1720
  persisted_used_map = dict(used_map)
1721
  staged_used_int: Dict[int, str] = {}
@@ -1773,7 +1717,7 @@ class WOTSPlusSHAKE256:
1773
  staged_used_int[idx] = msg_sha256_hex
1774
  staged_msg_leaf = ((norm_root, msg_sha256_hex), idx)
1775
 
1776
- next_gen = max(persisted_gen, cls._IN_MEM_GENERATION.get(norm_root, 0)) + 1
1777
  next_nonce = os.urandom(16).hex()
1778
  state_mac = cls._compute_wots_state_mac(
1779
  norm_root,
@@ -1781,7 +1725,6 @@ class WOTSPlusSHAKE256:
1781
  used_map,
1782
  next_gen,
1783
  next_nonce,
1784
- bound_state_dir=bound_dir_str,
1785
  )
1786
  payload_bytes = json.dumps(
1787
  {
@@ -1790,7 +1733,6 @@ class WOTSPlusSHAKE256:
1790
  "used_leaves": used_map,
1791
  "state_generation": next_gen,
1792
  "state_nonce": next_nonce,
1793
- "bound_state_dir": bound_dir_str,
1794
  "state_mac": state_mac,
1795
  },
1796
  sort_keys=True,
@@ -1813,7 +1755,6 @@ class WOTSPlusSHAKE256:
1813
  used_map,
1814
  next_gen,
1815
  next_nonce,
1816
- bound_state_dir=bound_dir_str,
1817
  domain=b"armiger-wots-freshness-seal-mac-v1:",
1818
  )
1819
  seal_bytes = json.dumps(
@@ -1823,7 +1764,6 @@ class WOTSPlusSHAKE256:
1823
  "used_leaves": used_map,
1824
  "state_generation": next_gen,
1825
  "state_nonce": next_nonce,
1826
- "bound_state_dir": bound_dir_str,
1827
  "seal_mac": seal_mac,
1828
  },
1829
  sort_keys=True,
@@ -1846,9 +1786,8 @@ class WOTSPlusSHAKE256:
1846
  # Commit in-memory caches ONLY after durable persistence succeeds
1847
  cls._IN_MEM_USED_LEAVES[norm_root] = staged_used_int
1848
  cls._IN_MEM_NEXT_LEAF[norm_root] = next_idx
1849
- cls._IN_MEM_GENERATION[norm_root] = next_gen
1850
- cls._IN_MEM_NONCE[norm_root] = next_nonce
1851
- cls._IN_MEM_BOUND_DIR[norm_root] = bound_dir_str
1852
  if staged_msg_leaf is not None:
1853
  cls._IN_MEM_MSG_TO_LEAF[staged_msg_leaf[0]] = staged_msg_leaf[1]
1854
  return idx
 
152
 
153
  _HOMOGLYPH_TRANS = str.maketrans(_HOMOGLYPH_MAP)
154
  _LEET_TRANS = str.maketrans(_LEET_MAP)
155
+ _ASCII_CTRL_STRIP_TRANS = str.maketrans("", "", "".join(chr(i) for i in (*range(0, 9), 11, 12, *range(14, 32), 127)))
156
+ _ASCII_FAST_SPACE_TRANS = str.maketrans(
157
+ {
158
+ **{chr(i): None for i in (*range(0, 9), 11, 12, *range(14, 32), 127)},
159
+ **{chr(i): chr(i + 32) for i in range(65, 91)},
160
+ **{c: " " for c in "._-[](){}/|:,;*^~`'\"\t\n\r"},
161
+ }
162
+ )
163
+ _NON_DIGIT_REP_RE = re.compile(r"([^\d\s])\1{2,}")
164
  _PRESERVE_ALNUM_TOKENS = frozenset({
165
+ "1080p", "720p", "2160p", "480p",
166
  "x264", "x265", "h264", "h265", "av1", "vp8", "vp9", "vc1",
167
  "mp3", "mp4", "m4a", "m4b", "m4v", "m2ts", "3gp", "ac3", "eac3",
168
  "bd25", "bd50", "dvd5", "dvd9", "win32", "win64", "x64", "x86",
 
185
  if not text:
186
  return ""
187
 
188
+ # 1. Fast ASCII path vs full Unicode NFKD decomposition
189
+ if text.isascii():
190
+ spaced = text.translate(_ASCII_FAST_SPACE_TRANS)
191
+ if not any(c in spaced for c in "@$!+|"):
192
+ out_tokens_fast: list[str] = []
193
+ for tok in spaced.split():
194
+ if tok.isalpha() or (len(tok) >= 2 and tok.isdigit()) or tok in _PRESERVE_ALNUM_TOKENS:
195
+ out_tokens_fast.append(tok)
196
+ else:
197
+ out_tokens_fast.append(tok.translate(_LEET_TRANS))
198
+ joined_fast = " ".join(out_tokens_fast)
199
+ if _NON_DIGIT_REP_RE.search(joined_fast):
200
+ joined_fast = _NON_DIGIT_REP_RE.sub(r"\1\1", joined_fast)
201
+ if "222" in joined_fast or "666" in joined_fast:
202
+ joined_fast = _REPEATED_CHARS_RE.sub(r"\1\1", joined_fast)
203
+ return joined_fast
204
+ cleaned = text.translate(_ASCII_CTRL_STRIP_TRANS).lower()
205
+ else:
206
+ pre_cleaned = "".join(
207
+ c for c in text
208
+ if unicodedata.category(c) not in ("Cf", "Mn", "Me", "Cc")
209
+ and not (0xFE00 <= ord(c) <= 0xFE0F)
210
+ and not (0xE0000 <= ord(c) <= 0xE01EF)
211
+ )
212
+ decomp = unicodedata.normalize("NFKD", pre_cleaned)
213
+ stripped = "".join(
214
+ c for c in decomp
215
+ if not unicodedata.combining(c)
216
+ and unicodedata.category(c) not in ("Cf", "Mn", "Me", "Cc")
217
+ and not (0xFE00 <= ord(c) <= 0xFE0F)
218
+ and not (0xE0000 <= ord(c) <= 0xE01EF)
219
+ )
220
+ cleaned = _ZERO_WIDTH_RE.sub("", stripped).lower().translate(_HOMOGLYPH_TRANS)
221
 
222
  # 3. Punctuation (except leet symbols @$!+|) to space first so tokens are cleanly bounded
223
+ spaced = _SPACE_PUNCT_CG_RE.sub(" ", cleaned)
224
 
225
  # 4. Token-aware leetspeak translation: pure digits ("43", "2026") and preserved media/age tokens
226
  # are kept intact; any token containing letters or leet symbols is leet-decoded.
227
+ has_rep = bool(_REPEATED_CHARS_RE.search(spaced.translate(_LEET_TRANS)))
228
  out_tokens: list[str] = []
229
  for tok in spaced.split():
230
+ if tok.isalpha():
231
+ out_tokens.append(_REPEATED_CHARS_RE.sub(r"\1\1", tok) if has_rep else tok)
232
+ elif (len(tok) >= 2 and tok.isdigit()) or tok in _PRESERVE_ALNUM_TOKENS:
233
  out_tokens.append(tok)
234
  else:
235
  decoded = tok.translate(_LEET_TRANS)
236
+ out_tokens.append(_REPEATED_CHARS_RE.sub(r"\1\1", decoded) if has_rep else decoded)
 
237
 
238
  joined = " ".join(out_tokens)
239
+ if "+" in joined or "|" in joined:
240
+ punct_normalized = _PUNCT_RE.sub(" ", joined)
241
+ return " ".join(punct_normalized.split())
242
+ return joined
243
+
244
+
245
+ _SPACE_PUNCT_CG_RE = re.compile(r"[\._\-\[\]\(\)\{\}\\\/\:\,\;\*\^\~\`\'\"\?\&\=]+")
246
 
247
 
248
  def sanitize_title(title: str) -> str:
249
  """Strip private tracker auth tokens, passkeys, and user credentials for complete anonymity."""
250
+ tl = title.lower()
251
+ clean = _TRACKER_TAGS_RE.sub("", title) if ("pass" in tl or "auth" in tl or "uid" in tl or "token" in tl or "key=" in tl or "rss" in tl) else title
252
  return " ".join(clean.split()).strip()
253
 
254
 
 
262
  re.compile(r"\b(pedophi[li]|paedophi[li]|pedofi[li]|paedofi[li])\w*", re.IGNORECASE),
263
  re.compile(r"\b(chi[li]d\s*porn|cp\s*vids?|cp\s*[li]inks?|cp\s*megas?|cp\s*pack\s*co[li]+ection|chi[li]d\s*erotic|underage\s*porn)\b", re.IGNORECASE),
264
  re.compile(r"\b(pre\s*teen\s*(sex|nude|porn|erotic|hardcore)|preteen[_\-\s]*(sex|nude|porn))\b", re.IGNORECASE),
265
+ re.compile(r"\b([li]o[li]i\s*(hardcore|hentai|sex|porn|nude|uncensored))\b", re.IGNORECASE),
266
  re.compile(r"\b(shotacon|shota\s*(sex|porn|hentai|hardcore))\b", re.IGNORECASE),
267
+ re.compile('\\b(todd[li]er|infant|e[li]ementary)\\s*(sex|nude|erotic|porn)\\b', re.IGNORECASE),
268
  re.compile(r"\b(jai[li]\s*bait|bare[li]y\s*[li]ega[li]\s*(underage|minor|chi[li]d))\b", re.IGNORECASE),
269
+ re.compile('\\b(?:[89]|1[0-7])\\s*y\\s*o\\s*(?:fuck\\w*|sex|porn|nude|erotic|hardcore|anal)\\b', re.IGNORECASE),
270
+ # ADV-300 evasion set (2026-10-22): collection/community code-words that carried no sexual-act token
271
+ # and slipped through as "safe". Terms with no benign media sense are zero-tolerance on their own;
272
+ # ambiguous minor-terms (loli, shota, boys, kinder, preteen, ...) require a following whitespace-separated
273
+ # collection / darknet qualifier so Kubrick's "Lolita", "Kiddy Grade", "Shota Aizawa", "Boys Don't Cry",
274
+ # "Kindergarten Cop", the legal adult studio "JB Video" and "[ShottaRip]" release tags stay indexable.
275
+ # Audited 2026-10-22 on 962k gold strings (0 new blocks) and a 700k-name DHT corpus sample.
276
+ re.compile(r"\b(pthc|ptsc|hurtcore|hebephi[li]\w*|ephebophi[li]\w*|(?:pedo|paedo)\s*vau[li]t)\b", re.IGNORECASE),
277
+ re.compile(
278
+ r"\b(chi[li]d(?:ren)?\s*(?:exp[li]oitation|sexua[li]\s*abuse|abuse\s*materia[li])"
279
+ r"|minors?\s*(?:abuse|exp[li]oitation)"
280
+ r"|il+ega[li]\s*(?:youth|minors?|underage|teens?|kids?|chi[li]d(?:ren)?))\b",
281
+ re.IGNORECASE,
282
+ ),
283
+ re.compile(r"\b(?:ls\s+(?:magazine|mode[li]s|[li]and)|jb\s+(?:private\s+board|underground|darknet|hid+en\s+service))\b", re.IGNORECASE),
284
+ re.compile(r"\bcp\s*(?:hid+en\s*service|darknet|onion\s*(?:dump|board|site))\b", re.IGNORECASE),
285
+ re.compile(
286
+ r"\b(?:pedo|paedo|kid+(?:y|ie)|pre\s*teens?|underage|[li]o[li]i|shota|hebe)s?\s+"
287
+ r"(?:underground|vip|vau[li]t|private|secret|hid+en|darknet|rea[li]|cam|rip|archive|pack|set"
288
+ r"|co[li]+ection|dump|bund[li]e|board|fo[li]der|mirror|index|photos?|pics?|vids?|videos?|mega|[li]inks?)\b",
289
+ re.IGNORECASE,
290
+ ),
291
+ re.compile(
292
+ r"\b(?:boys?|gir[li]s?|kids?|chi[li]dren|kinder|youth|teens?)\s+"
293
+ r"(?:underground|darknet|hid+en\s*service|vau[li]t)\s+"
294
+ r"(?:vip|pack|set|co[li]+ection|archive|dump|board|private|mirror|index)\b",
295
+ re.IGNORECASE,
296
+ ),
297
  ]
298
 
299
  # Non-consensual exploitation & sexual violence
300
  _NONCONSENSUAL_PATTERNS = [
301
  re.compile(r"\b(non\s*consensua[li]|rape\s*(porn|video|scene)|gang\s*rape|forced\s*sex)\b", re.IGNORECASE),
302
+ re.compile('\\b(revenge\\s*porn|spycam\\s*(shower|upskirt))\\b', re.IGNORECASE),
303
+ re.compile('\\b(sextortion)\\b', re.IGNORECASE),
304
  ]
305
 
306
  # Extreme violence, snuff, execution, gore
307
  _EXTREME_VIOLENCE_PATTERNS = [
308
  re.compile(r"\b(snuff\s*(fi[li]m|video|movie)|rea[li]\s*beheading|rea[li]\s*execution)\b", re.IGNORECASE),
309
  re.compile(r"\b([li]ive\s*suicide\s*(video|stream)|massacre\s*[li]ivestream)\b", re.IGNORECASE),
310
+ re.compile('\\b(rea[li]\\s*torture\\s*(video|fi[li]m))\\b', re.IGNORECASE),
311
  ]
312
 
313
  # High-risk dropper extensions that are NEVER legitimate standalone software/game/media torrents
 
343
  )
344
 
345
  _MALWARE_LURE_RE = re.compile(
346
+ '(?i)(?:^|(?<=[^a-z0-9]))(?:required[\\s._-]*to[\\s._-]*play|install[\\s._-]*codec|nitro[\\s._-]*generator|free[\\s._-]*nitro|fake[\\s._-]*seeder[\\s._-]*swarm[\\s._-]*trap|adware[\\s._-]*bundle[\\s._-]*installer|password[\\s._-]*protected[\\s._-]*trap|password[\\s._-]*in[\\s._-]*description|corrupt\\.part|spam[\\s._-]*link[\\s._-]*redirect|watch[\\s._-]*full[\\s._-]*movie\\.url|activar[\\s._-]*sonido|\\d+(?:\\.\\d+)?\\s*tb\\s+collection\\.torrent)(?:$|(?=[^a-z0-9]))'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
347
  )
348
 
349
  _BENIGN_BOOKMARK_URL_RE = re.compile(
350
+ '(?i)^(?:torrent[\\s._-]*downloaded[\\s._-]*from|downloaded[\\s._-]*from|visit[\\s._-]*us|rarbg|yts|tgx|torrentgalaxy|rutracker|nyaa)'
351
  )
352
 
353
  _PASSWORD_COMPANION_RE = re.compile(
 
360
  r"\s-\s\d{1,3}\s*(?:\(|\[).*?\b(?:1080p|720p|2160p|480p)\b)"
361
  )
362
  _VIDEO_RIP_CLAIM_CG_RE = re.compile(
363
+ '(?i)(?:\\b(?:1080p|720p|2160p|480p|576p|4k)\\b.*?\\b(?:web-?dl|webrip|bluray|bdrip|brrip|hdtv|hdcam|dvdrip|x264|x265|h\\.?264|h\\.?265|hevc|av1|xvid|divx)\\b|\\b(?:web-?dl|webrip|bdrip|brrip|hdtv|hdcam|dvdrip)\\b(?:.*?\\b(?:x264|x265|h\\.?264|h\\.?265|hevc|av1|xvid|divx|aac|ac3|ddp?5\\.?1))?|\\b(?:19\\d\\d|20\\d\\d|s\\d{1,2}[._ -]?e\\d{1,3}|\\d{1,2}x\\d{2})\\b.*?\\b(?:x264|x265|h\\.?264|h\\.?265|hevc|av1|xvid|divx)\\b)'
 
 
 
 
364
  )
365
  _OPTICAL_DISC_TITLE_CG_RE = re.compile(
366
  r"(?i)\b(?:dvd(?:[59]|r|-r|-rom)?|bd(?:25|50|66|100|mv|rom|-r)|blu-?ray[\s._-]*disc|full[\s._-]*bd|untouched|remux|pal|ntsc|iso|udf|sacd|dvd-?audio|3d[\s._-]*iso)\b"
 
394
 
395
  def _clean_filename_for_ext(raw_name: str) -> str:
396
  s = raw_name.lower().strip().rstrip(". \t\r\n\x00")
397
+ if ".sample" in s:
398
+ s = _SAMPLE_SUFFIX_RE.sub("", s).rstrip(". \t\r\n\x00")
399
  return s
400
 
401
 
 
418
  # CSAM & Abuse Guard Implementation
419
  # ---------------------------------------------------------------------------
420
 
421
+ _ANY_UNSAFE_TEXT_RE = re.compile("|".join(f"(?:{p.pattern})" for p in (*_CSAM_DIRECT_PATTERNS, *_NONCONSENSUAL_PATTERNS, *_EXTREME_VIOLENCE_PATTERNS)), re.IGNORECASE)
422
+
423
+ from functools import lru_cache as _cg_lru_cache
424
+ _LETTER_REPEAT_RE = re.compile(r"([a-z])\1")
425
+ _CSS_WORD_RE = re.compile(r"\bcss\b")
426
+ _CHAR_RUN_COLLAPSE_RE = re.compile(r"(.)\1+")
427
+ _UNSAFE_SUBS = (
428
+ "csa", "c s a", "pedo", "paedo", "chil", "chi1", "cp", "undera", "prete", "pre te",
429
+ "loli", "1oli", "lo1i", "shota", "todl", "tod1", "kinder", "infan", "elemen", "e1emen",
430
+ "jail", "jai1", "barel", "bare1", "inces", "yo", "y o", "pthc", "ptsc", "hurtc",
431
+ "hebe", "epheb", "minor", "ilega", "i1ega", "illega", "ls ", "1s ", "jb ", "darkne",
432
+ "underg", "hiden", "hidden", "vaul", "vau1", "consen", "rape", "forced", "reveng",
433
+ "spycam", "blackm", "b1ackm", "sextor", "snuf", "behead", "execut", "suicid",
434
+ "masacr", "massacr", "tortur",
435
+ )
436
+ _MALWARE_LURE_SUBS = ("required", "install", "nitro", "seeder", "adware", "password", "corrupt", "spam", "watch", "activar", "collection.torrent")
437
+ _CODEC_LURE_SUBS = ("codec", "vlc", "player", "directx", "flash", "hevc", "divx", "xvid", "x264")
438
+ _PW_COMP_SUBS = ("pass", "contrase", "parola", "extract")
439
 
 
 
440
 
441
+ @_cg_lru_cache(maxsize=65536)
442
+ def _cached_inspect_text(text: str) -> ContentFilterResult:
443
+ if True:
444
  if not text:
445
  return ContentFilterResult(
446
  is_safe=True,
 
453
 
454
  sanitized = sanitize_title(text)
455
  normalized = normalize_text(sanitized)
456
+ if _SINGLE_CHAR_RUN_RE.search(normalized):
457
+ norm_css_safe = _CSS_WORD_RE.sub("css_style_token", normalized) if "css" in normalized else normalized
458
+ de_spaced = _SINGLE_CHAR_RUN_RE.sub(r"\1", norm_css_safe)
459
+ if "css_style_token" in de_spaced:
460
+ de_spaced = de_spaced.replace("css_style_token", "css")
461
+ else:
462
+ de_spaced = normalized
463
+ if de_spaced == normalized and not any(s in normalized for s in _UNSAFE_SUBS):
464
+ return ContentFilterResult(
465
+ is_safe=True,
466
+ violation_type=None,
467
+ reason=None,
468
+ matched_pattern=None,
469
+ risk_score=0.0,
470
+ sanitized_title=sanitized,
471
+ )
472
+ if _LETTER_REPEAT_RE.search(de_spaced):
473
+ norm_css_safe2 = _CSS_WORD_RE.sub("css_style_token", de_spaced) if "css" in de_spaced else de_spaced
474
+ de_stretched = _CHAR_RUN_COLLAPSE_RE.sub(r"\1", norm_css_safe2)
475
+ if "cs_style_token" in de_stretched:
476
+ de_stretched = de_stretched.replace("cs_style_token", "css")
477
+ for raw_stem, canonical_stem in (
478
+ ("ten", "teen"),
479
+ ("todler", "toddler"),
480
+ ("snuf", "snuff"),
481
+ ("masacre", "massacre"),
482
+ ("kil", "kill"),
483
+
484
+ ):
485
+ if raw_stem in de_stretched:
486
+ de_stretched = de_stretched.replace(raw_stem, canonical_stem)
487
+ else:
488
+ de_stretched = de_spaced
489
+ candidates = (normalized,) if (de_spaced == normalized and de_stretched == normalized) else tuple(dict.fromkeys((normalized, de_spaced, de_stretched)))
490
 
491
  for cand in candidates:
492
+ if not any(s in cand for s in _UNSAFE_SUBS) or not _ANY_UNSAFE_TEXT_RE.search(cand):
493
+ continue
494
  # 1. Direct CSAM patterns
495
  for pat in _CSAM_DIRECT_PATTERNS:
496
  m = pat.search(cand)
 
539
  sanitized_title=sanitized,
540
  )
541
 
542
+ class CSAMGuard:
543
+ """Comprehensive content safety guard enforcing CSAM, abuse, and malware blocking."""
544
+
545
+ def __init__(self, tombstone_store: TombstoneStore | None = None) -> None:
546
+ self.tombstone_store = tombstone_store or TombstoneStore()
547
+
548
+ def inspect_text(self, text: str) -> ContentFilterResult:
549
+ return _cached_inspect_text(text)
550
+
551
  def inspect_torrent(
552
  self,
553
  infohash: str,
 
602
  # 4. Inspect file list text for CSAM / abuse first (preserves violation_type priority)
603
  parsed_files: list[tuple[str, str, int]] = []
604
  if file_list:
605
+ raw_entries = [
606
+ (
607
+ f if isinstance(f, str) else str(f.get("path") or f.get("p") or f.get("name") or ""),
608
+ int((f.get("size") or f.get("s") or 0) if isinstance(f, dict) else 0),
609
+ )
610
+ for f in file_list
611
+ ]
612
+ bulk_safe = len(raw_entries) > 1 and self.inspect_text("\n".join(fn for fn, _ in raw_entries)).is_safe
613
+ for fname, fsize in raw_entries:
614
+ if not bulk_safe:
615
+ f_res = self.inspect_text(fname)
616
+ if not f_res.is_safe:
617
+ return f_res
618
  parsed_files.append((fname, _clean_filename_for_ext(fname), fsize))
619
 
620
  # 5. Check Unicode Right-to-Left Override (RTLO) extension spoofing in title or files
621
+ if (not title.isascii() and ('\u202e' in title or '\u202d' in title or '\u200e' in title or '\u200f' in title or _RTLO_SPOOF_RE.search(title))) or any((not fn.isascii() and ('\u202e' in fn or '\u202d' in fn or '\u200e' in fn or '\u200f' in fn or _RTLO_SPOOF_RE.search(fn))) for fn, _, _ in parsed_files):
622
  return ContentFilterResult(
623
  is_safe=False,
624
  violation_type=CSAMViolationType.MALWARE_PAYLOAD,
 
631
  title_clean = _clean_filename_for_ext(title)
632
 
633
  # 6. Universal malware/honeypot lure patterns (blocked across ALL categories)
634
+ m_lure = _MALWARE_LURE_RE.search(title_clean) if any(s in title_clean for s in _MALWARE_LURE_SUBS) else None
635
  if m_lure:
636
  return ContentFilterResult(
637
  is_safe=False,
 
641
  risk_score=0.99,
642
  sanitized_title=res.sanitized_title,
643
  )
644
+ _joined_f_lower = "\n".join(fl for _, fl, _ in parsed_files) if len(parsed_files) > 2 else ""
645
+ if not _joined_f_lower or (any(s in _joined_f_lower for s in _MALWARE_LURE_SUBS) and _MALWARE_LURE_RE.search(_joined_f_lower)):
646
+ for fname, f_lower, _ in parsed_files:
647
+ m_flure = _MALWARE_LURE_RE.search(f_lower)
648
+ if m_flure:
649
+ return ContentFilterResult(
650
+ is_safe=False,
651
+ violation_type=CSAMViolationType.MALWARE_PAYLOAD,
652
+ reason=f"Blocked explicit malware/honeypot lure in file: '{fname}'",
653
+ matched_pattern=m_flure.group(0),
654
+ risk_score=0.99,
655
+ sanitized_title=res.sanitized_title,
656
+ )
657
 
658
  title_claims_video = bool(_ANIME_OR_EP_ZIP_CG_RE.search(title_clean) or _VIDEO_RIP_CLAIM_CG_RE.search(title_clean))
659
 
 
690
  image_file_count = 0
691
  image_total_bytes = 0
692
 
693
+ has_game_engine_structure = False
694
+ non_malware_bytes = 0
695
+ _may_have_pw_comp = (not _joined_f_lower) or any(s in _joined_f_lower for s in _PW_COMP_SUBS)
696
  for _, f_lower, fsize in parsed_files:
697
  f_posix = f_lower.replace("\\", "/")
698
+ if _match_malware_ext(f_lower) is None and fsize > 0:
699
+ non_malware_bytes += fsize
700
  if "/bdmv/" in f_posix or f_posix.startswith("bdmv/") or f_posix.endswith((".m2ts", ".bdmv", ".mpls")):
701
  has_bdmv_structure = True
702
  if f_posix.endswith((".rpa", ".rpyb")) and fsize >= 65536:
703
  has_renpy_structure = True
704
+ has_game_engine_structure = True
705
+ if (
706
+ f_posix.endswith(("unityplayer.dll", "nw.dll", "data.win", "www/js/rpg_core.js"))
707
+ or f_posix.endswith((".pck", ".rgss3a", ".rgss2a", ".rgssad", ".xp3", ".wolf"))
708
+ or "/engine/binaries/" in f_posix
709
+ or "/mono/etc/mono/" in f_posix
710
+ ):
711
+ has_game_engine_structure = True
712
+ if not has_password_companion and _may_have_pw_comp and any(s in f_posix for s in _PW_COMP_SUBS) and _PASSWORD_COMPANION_RE.search(f_posix):
713
  has_password_companion = True
714
  dot = f_posix.rfind(".")
715
  f_ext = f_posix[dot:] if dot != -1 else ""
 
728
 
729
  # Multi-lesson courses (>= 5 files, >= 3 sized lesson files, >= 50 MB total lesson media) legitimately
730
  # include .js, .ps1, .bat, or interactive player .exe files; zero-byte or tiny decoys are still checked.
731
+ if cat_lower == "xxx" and has_game_engine_structure and non_malware_bytes >= 5_000_000:
732
+ is_strict_media_category = False
733
  check_media_executables = is_strict_media_category or (
734
  is_course_category and (len(parsed_files) < 5 or not has_real_course_media)
735
  )
 
737
  # Contextual codec-pack lure check: blocks codec-pack installers disguised as or bundled with media
738
  # while sparing legitimate standalone codec-pack software utilities.
739
  if check_media_executables or has_any_video or title_claims_video:
740
+ m_clure = _MEDIA_CODEC_LURE_RE.search(title_clean) if any(s in title_clean for s in _CODEC_LURE_SUBS) else None
741
  if m_clure and (has_any_video or title_claims_video):
742
  return ContentFilterResult(
743
  is_safe=False,
 
747
  risk_score=0.99,
748
  sanitized_title=res.sanitized_title,
749
  )
750
+ for fname, f_lower, _ in (parsed_files if (not _joined_f_lower or (any(s in _joined_f_lower for s in _CODEC_LURE_SUBS) and _MEDIA_CODEC_LURE_RE.search(_joined_f_lower))) else ()):
751
  m_fclure = _MEDIA_CODEC_LURE_RE.search(f_lower)
752
  if m_fclure:
753
  return ContentFilterResult(
 
761
 
762
  # 8. Cold / bare-title checks when file_list is empty
763
  if not parsed_files and (check_media_executables or cat_lower in ("unknown", "")):
764
+ if (
765
+ t_ext is not None
766
+ and not _BENIGN_ZIP_CG_RE.search(title_clean)
767
+ and not (
768
+ not any(stem in title_clean for stem in _DISGUISED_MEDIA_STEMS)
769
+ and title_clean.endswith((".asr.js", ".qioo.jar"))
770
+ )
771
+ ):
772
  return ContentFilterResult(
773
  is_safe=False,
774
  violation_type=CSAMViolationType.MALWARE_PAYLOAD,
 
812
  and (has_large_real_video or has_real_image_set)
813
  ):
814
  continue
815
+ dot_f = f_lower.rfind(".")
816
+ raw_ext = f_lower[dot_f:] if dot_f != -1 else ""
817
+ ext = _match_malware_ext(f_lower)
818
+ if ext is None and raw_ext not in _DISK_IMAGE_TRAP_EXTS and raw_ext not in _SINGLE_ARCHIVE_TRAP_EXTS:
819
+ continue
820
  if (
821
+ f_posix.endswith(".vbs")
822
+ and _RENPY_SAY_VBS_CG_RE.search(f_posix)
823
  and not is_strict_media_category
824
  and not title_claims_video
825
  and not has_any_video
 
828
  ):
829
  continue
830
  is_disguised = any(stem in f_lower for stem in _DISGUISED_MEDIA_STEMS)
 
 
831
  if is_disguised and raw_ext in _DISK_IMAGE_TRAP_EXTS:
832
  return ContentFilterResult(
833
  is_safe=False,
 
837
  risk_score=0.99,
838
  sanitized_title=res.sanitized_title,
839
  )
 
840
  if ext is not None:
841
  # Exempt legitimate Internet Archive / Gutenberg ASR (.asr.js) and J2ME reader (.qioo.jar) sidecars when not disguised
842
  if not is_disguised and f_lower.endswith((".asr.js", ".qioo.jar")):
 
844
  # Exempt legitimate Blu-ray BD-J Java menu JARs (BDMV/JAR/00000.jar)
845
  if ext == ".jar" and has_bdmv_structure and _BDMV_JAR_PATH_RE.search(f_posix):
846
  continue
847
+ # Exempt small tracker bookmark (.url) when not disguised, no malware lure, and real payload is present
848
  if (
849
  ext == ".url"
850
  and not is_disguised
851
+ and (0 <= fsize <= 4096)
852
+ and not _MALWARE_LURE_RE.search(f_lower)
853
+ and (non_malware_bytes >= 500_000 or has_large_real_video or has_real_image_set or has_real_course_media)
854
+ ):
855
+ continue
856
+ # Exempt legitimate .chm eBooks/help files when real payload or eBook category is present
857
+ if (
858
+ ext == ".chm"
859
+ and not is_disguised
860
+ and not _MALWARE_LURE_RE.search(f_lower)
861
+ and (cat_lower == "ebook" or has_large_real_video or has_real_image_set or has_real_course_media or non_malware_bytes >= 50_000_000)
862
+ ):
863
+ continue
864
+ # Exempt small Windows shortcut (.lnk <= 4KB) when >= 50MB real media payload is present
865
+ if (
866
+ ext == ".lnk"
867
+ and not is_disguised
868
+ and (0 <= fsize <= 4096)
869
+ and not _MALWARE_LURE_RE.search(f_lower)
870
+ and (has_large_real_video or non_malware_bytes >= 50_000_000)
871
+ ):
872
+ continue
873
+ # Exempt companion promo sidecars in large >= 150MB adult video torrents or full Blu-ray BDMV folders
874
+ if (
875
+ ext in (".exe", ".apk")
876
+ and not is_disguised
877
+ and not _MALWARE_LURE_RE.search(f_lower)
878
+ and ((cat_lower == "xxx" and has_large_real_video and non_malware_bytes >= 150_000_000) or has_bdmv_structure)
879
+ ):
880
+ continue
881
+ # Exempt multi-file software/game/course packages containing scripts/installers
882
+ if (
883
+ ext in (".vbs", ".wsf", ".js", ".pkg")
884
+ and not is_disguised
885
+ and not _MALWARE_LURE_RE.search(f_lower)
886
+ and cat_lower in ("software", "game", "course")
887
+ and len(parsed_files) >= 10
888
  ):
889
  continue
890
  if (
 
1349
  _IN_MEM_NEXT_LEAF: Dict[str, int] = {}
1350
  _IN_MEM_USED_LEAVES: Dict[str, Dict[int, str]] = {}
1351
  _IN_MEM_MSG_TO_LEAF: Dict[Tuple[str, str], int] = {}
1352
+ _IN_MEM_GENERATION: Dict[Tuple[str, str], int] = {}
1353
+ _IN_MEM_NONCE: Dict[Tuple[str, str], str] = {}
 
1354
  _VERIFIED_ONE_TIME_KEYS: Dict[str, bytes] = {}
1355
  _ED25519_TO_WOTS_PUBS: dict[str, set[str]] = {}
1356
  _ED25519_ROOT_WOTS_PUB: dict[str, str] = {}
 
1443
  used_map: Mapping[str, str],
1444
  state_generation: int,
1445
  state_nonce: str,
 
1446
  domain: bytes = b"armiger-wots-durable-state-mac-v1:",
1447
  ) -> str:
1448
  mac_key = hashlib.shake_256(domain + norm_root.encode("ascii")).digest(32)
 
 
 
 
 
 
 
 
 
1449
  canonical = json.dumps(
1450
+ {
1451
+ "root_pq_pub_hex": norm_root,
1452
+ "next_leaf_index": int(next_leaf_index),
1453
+ "used_leaves": {str(k): str(v) for k, v in sorted(used_map.items())},
1454
+ "state_generation": int(state_generation),
1455
+ "state_nonce": str(state_nonce),
1456
+ },
1457
  sort_keys=True,
1458
  separators=(",", ":"),
1459
  ).encode("utf-8")
1460
  return hmac.new(mac_key, canonical, hashlib.sha256).hexdigest()
1461
 
1462
  @classmethod
1463
+ def _read_and_verify_wots_seal(cls, seal_path: pathlib.Path, norm_root: str) -> Dict[str, Any]:
 
 
 
 
 
1464
  try:
1465
  raw_s = seal_path.read_text(encoding="utf-8")
1466
  sdoc = json.loads(raw_s)
 
1482
  s_next = int(sdoc["next_leaf_index"])
1483
  s_gen = int(sdoc["state_generation"])
1484
  s_nonce = str(sdoc["state_nonce"])
 
1485
  s_used = {str(k): str(v) for k, v in sdoc["used_leaves"].items()}
1486
  exp_mac = cls._compute_wots_state_mac(
1487
  norm_root,
 
1489
  s_used,
1490
  s_gen,
1491
  s_nonce,
 
1492
  domain=b"armiger-wots-freshness-seal-mac-v1:",
1493
  )
1494
  if not hmac.compare_digest(str(sdoc.get("seal_mac", "")), exp_mac):
1495
  raise RuntimeError(f"wots_durable_seal_mac_mismatch:{seal_path}")
 
 
 
 
1496
  return {
1497
  "next_leaf_index": s_next,
1498
  "state_generation": s_gen,
1499
  "state_nonce": s_nonce,
 
1500
  "used_leaves": s_used,
1501
  }
1502
 
 
1518
  ext_sdir.mkdir(parents=True, exist_ok=True)
1519
  if ext_sdir.resolve() == resolved_sdir:
1520
  raise RuntimeError("wots_independent_seal_dir_required")
1521
+ path_digest = hashlib.sha256(str(resolved_sdir).encode("utf-8")).hexdigest()[:24]
1522
  state_path = sdir / f"wots_state_{norm_root[:32]}.json"
1523
  sibling_seal_path = sdir / f".wots_state_{norm_root[:32]}.json.seal"
1524
+ ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}_{path_digest}.seal"
1525
+ if state_path.exists() or sibling_seal_path.exists() or ext_seal_path.exists():
 
 
 
 
 
1526
  raise RuntimeError(f"wots_state_already_provisioned:{state_path}")
1527
  cls._load_and_update_durable_state(
1528
  norm_root,
 
1534
  )
1535
  return state_path
1536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1537
  @classmethod
1538
  def _load_and_update_durable_state(
1539
  cls,
 
1551
  sdir = pathlib.Path(state_dir) if state_dir is not None else cls.get_state_dir()
1552
  sdir.mkdir(parents=True, exist_ok=True)
1553
  resolved_sdir = sdir.resolve()
 
1554
  ext_sdir = pathlib.Path(seal_dir) if seal_dir is not None else cls.get_seal_dir(sdir)
1555
  ext_sdir.mkdir(parents=True, exist_ok=True)
1556
  if ext_sdir.resolve() == resolved_sdir:
1557
  raise RuntimeError("wots_independent_seal_dir_required")
1558
 
1559
+ path_digest = hashlib.sha256(str(resolved_sdir).encode("utf-8")).hexdigest()[:24]
1560
+ hwm_key = (norm_root, str(resolved_sdir))
1561
  state_path = sdir / f"wots_state_{norm_root[:32]}.json"
1562
  sibling_seal_path = sdir / f".wots_state_{norm_root[:32]}.json.seal"
1563
+ ext_seal_path = ext_sdir / f"wots_seal_{norm_root[:32]}_{path_digest}.seal"
1564
  lock_path = sdir / f"wots_state_{norm_root[:32]}.lock"
1565
  req_existing = (
1566
  bool(require_existing_state)
 
1579
  persisted_gen = 0
1580
  persisted_nonce = ""
1581
  used_map: Dict[str, str] = {}
 
 
 
 
 
1582
  if not state_path.exists():
1583
  if (
1584
  req_existing
1585
  or sibling_seal_path.exists()
1586
  or ext_seal_path.exists()
1587
+ or hwm_key in cls._IN_MEM_GENERATION
1588
  ):
1589
  raise RuntimeError(
1590
  f"wots_durable_state_missing_after_establishment:{state_path}"
 
1604
  if not isinstance(raw_used, dict):
1605
  raise ValueError("invalid_wots_used_leaves")
1606
  used_map = {str(k): str(v) for k, v in raw_used.items()}
1607
+ if "state_generation" in parsed or "state_mac" in parsed:
1608
+ raw_gen = parsed.get("state_generation")
1609
+ raw_nonce = parsed.get("state_nonce")
1610
+ if (
1611
+ isinstance(raw_gen, bool)
1612
+ or not isinstance(raw_gen, int)
1613
+ or int(raw_gen) < 1
1614
+ or not isinstance(raw_nonce, str)
1615
+ or not raw_nonce
1616
+ ):
1617
+ raise ValueError("invalid_wots_state_generation_or_nonce")
1618
+ persisted_gen = int(raw_gen)
1619
+ persisted_nonce = str(raw_nonce)
1620
+ exp_state_mac = cls._compute_wots_state_mac(
1621
+ norm_root,
1622
+ persisted_next,
1623
+ used_map,
1624
+ persisted_gen,
1625
+ persisted_nonce,
 
 
 
1626
  )
1627
+ if not hmac.compare_digest(str(parsed.get("state_mac", "")), exp_state_mac):
1628
+ raise ValueError("wots_state_mac_verification_failed")
 
 
 
 
 
 
 
 
1629
  except Exception as exc:
1630
  raise RuntimeError(f"wots_durable_state_corrupted:{state_path}:{exc}") from exc
1631
 
1632
  # Verify against in-process high-water mark and independent durable freshness checkpoint
1633
+ mem_gen = cls._IN_MEM_GENERATION.get(hwm_key, 0)
1634
+ mem_nonce = cls._IN_MEM_NONCE.get(hwm_key, "")
1635
  if persisted_gen < mem_gen or (
1636
  persisted_gen == mem_gen and mem_nonce and persisted_nonce != mem_nonce
1637
  ):
1638
  raise RuntimeError(f"wots_durable_state_rollback_detected:in_memory_hwm:{state_path}")
1639
 
1640
+ if persisted_gen >= 1:
1641
+ if not ext_seal_path.exists():
1642
+ raise RuntimeError(
1643
+ f"wots_durable_state_missing_independent_seal:{ext_seal_path}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1644
  )
1645
+ if not sibling_seal_path.exists():
 
1646
  raise RuntimeError(
1647
+ f"wots_durable_state_missing_sibling_seal:{sibling_seal_path}"
1648
  )
1649
+ for sp in (ext_seal_path, sibling_seal_path):
1650
+ s_info = cls._read_and_verify_wots_seal(sp, norm_root)
1651
+ if (
1652
+ persisted_next < s_info["next_leaf_index"]
1653
+ or persisted_gen < s_info["state_generation"]
1654
+ or (
1655
+ persisted_gen == s_info["state_generation"]
1656
+ and persisted_nonce != s_info["state_nonce"]
1657
+ )
1658
+ or any(used_map.get(k) != v for k, v in s_info["used_leaves"].items())
1659
+ ):
1660
+ raise RuntimeError(
1661
+ f"wots_durable_state_rollback_detected:freshness_seal_mismatch:{sp}"
1662
+ )
1663
 
1664
  persisted_used_map = dict(used_map)
1665
  staged_used_int: Dict[int, str] = {}
 
1717
  staged_used_int[idx] = msg_sha256_hex
1718
  staged_msg_leaf = ((norm_root, msg_sha256_hex), idx)
1719
 
1720
+ next_gen = max(persisted_gen, cls._IN_MEM_GENERATION.get(hwm_key, 0)) + 1
1721
  next_nonce = os.urandom(16).hex()
1722
  state_mac = cls._compute_wots_state_mac(
1723
  norm_root,
 
1725
  used_map,
1726
  next_gen,
1727
  next_nonce,
 
1728
  )
1729
  payload_bytes = json.dumps(
1730
  {
 
1733
  "used_leaves": used_map,
1734
  "state_generation": next_gen,
1735
  "state_nonce": next_nonce,
 
1736
  "state_mac": state_mac,
1737
  },
1738
  sort_keys=True,
 
1755
  used_map,
1756
  next_gen,
1757
  next_nonce,
 
1758
  domain=b"armiger-wots-freshness-seal-mac-v1:",
1759
  )
1760
  seal_bytes = json.dumps(
 
1764
  "used_leaves": used_map,
1765
  "state_generation": next_gen,
1766
  "state_nonce": next_nonce,
 
1767
  "seal_mac": seal_mac,
1768
  },
1769
  sort_keys=True,
 
1786
  # Commit in-memory caches ONLY after durable persistence succeeds
1787
  cls._IN_MEM_USED_LEAVES[norm_root] = staged_used_int
1788
  cls._IN_MEM_NEXT_LEAF[norm_root] = next_idx
1789
+ cls._IN_MEM_GENERATION[hwm_key] = next_gen
1790
+ cls._IN_MEM_NONCE[hwm_key] = next_nonce
 
1791
  if staged_msg_leaf is not None:
1792
  cls._IN_MEM_MSG_TO_LEAF[staged_msg_leaf[0]] = staged_msg_leaf[1]
1793
  return idx
dht_rsi_canary_and_agg.py CHANGED
@@ -24,6 +24,9 @@ from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
24
  from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
25
  from cryptography.hazmat.primitives.kdf.hkdf import HKDF
26
 
 
 
 
27
 
28
  from dht_rsi_models_and_privacy import (
29
  AnonymizedTelemetryRecord,
@@ -33,6 +36,7 @@ from dht_rsi_models_and_privacy import (
33
  CanaryRegressionReport,
34
  CatalogConsensusResult,
35
  ContinuousAggregationResult,
 
36
  ContinuousDeltaSubmission,
37
  EncryptedTelemetryBundle,
38
  PeerAttestation,
@@ -58,11 +62,15 @@ from dht_rsi_verification import (
58
  # =====================================================================
59
 
60
  def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
61
- """Generates exactly 500 deterministic reference canaries covering all 8 heads and edge cases."""
 
 
 
 
62
  rng = random.Random(seed)
63
  items: List[CanaryItem] = []
64
 
65
- # 1. 120 Movies
66
  movie_templates = [
67
  ("Big.Buck.Bunny.{year}.1080p.BluRay.x264-OPEN", "english", False, False),
68
  ("Sintel.{year}.KOREAN.1080p.BluRay.x264-OPEN", "non_english", True, False),
@@ -70,6 +78,15 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
70
  ("Tears.of.Steel.{year}.2160p.UHD.Remux.HEVC.DV.TrueHD.Atmos", "english", True, False),
71
  ("Coffee.Run.{year}.1080p.WEBRip.x265.AAC5.1", "english", False, False),
72
  ("Spring.Open.Film.{year}.JAPANESE.1080p.BluRay.x264", "non_english", True, True),
 
 
 
 
 
 
 
 
 
73
  ]
74
  for i in range(120):
75
  tmpl, lang, subs, anime = movie_templates[i % len(movie_templates)]
@@ -79,7 +96,7 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
79
  item_id=f"canary_mov_{i:03d}",
80
  title=title,
81
  ground_truth={
82
- "category": "anime" if anime else "movie",
83
  "adult": False,
84
  "anime": anime,
85
  "lang": lang,
@@ -90,13 +107,18 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
90
  },
91
  ))
92
 
93
- # 2. 100 TV Shows
94
  tv_templates = [
95
  ("Cosmos.Laundromat.S01E{ep:02d}.1080p.WEB-DL.DDP5.1.Atmos.H.264-OPEN", "english", True, False),
96
  ("Caminandes.S04E{ep:02d}.720p.HDTV.x264-OPEN", "english", False, False),
97
  ("Spring.Chronicles.S02E{ep:02d}.GERMAN.1080p.WEB-DL.DDP5.1.x264", "non_english", True, False),
98
  ("Open.Science.Lectures.S03E{ep:02d}.1080p.WEB-DL.DDP5.1.H.264", "english", True, False),
99
  ("Creative.Commons.Chronicles.S02E{ep:02d}.KOREAN.1080p.WEB-DL.DDP5.1.Atmos", "non_english", True, False),
 
 
 
 
 
100
  ]
101
  for i in range(100):
102
  tmpl, lang, subs, anime = tv_templates[i % len(tv_templates)]
@@ -117,13 +139,18 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
117
  },
118
  ))
119
 
120
- # 3. 50 Anime
121
  anime_titles = [
122
  ("[OpenAnime] Spring - {ep:02d} [1080p][HEVC][Multiple Subtitle]", "non_english", True),
123
  ("[CC-Anime] Charge - Open Anime Project - {ep:02d} (1080p) [82C108B7]", "non_english", True),
124
  ("[OpenSub] Caminandes - {ep:02d} [720p].mkv", "non_english", True),
125
  ("Wing It Open Series Part 3 - {ep:02d} [1080p Dual-Audio]", "english", True),
126
  ("Open Blender Anime S01E{ep:02d} [1080p][Multi-Sub]", "non_english", True),
 
 
 
 
 
127
  ]
128
  for i in range(50):
129
  tmpl, lang, subs = anime_titles[i % len(anime_titles)]
@@ -132,7 +159,7 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
132
  item_id=f"canary_ani_{i:03d}",
133
  title=tmpl.format(ep=ep),
134
  ground_truth={
135
- "category": "anime",
136
  "adult": False,
137
  "anime": True,
138
  "lang": lang,
@@ -143,116 +170,186 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
143
  },
144
  ))
145
 
146
- # 4. 40 Music
147
- for i in range(40):
148
- items.append(CanaryItem(
149
- item_id=f"canary_mus_{i:03d}",
150
- title=f"Artist_{i} - Album_{i} (2024) [FLAC 24bit-96kHz]",
151
- ground_truth={
152
- "category": "music",
153
- "adult": False,
154
- "anime": False,
155
- "lang": "english",
156
- "junk": False,
157
- "owner_scope": "allowed_type",
158
- "english_subs": False,
159
- "title_language": "english_title",
160
- },
161
- ))
162
-
163
- # 5. 30 Comics/Manga
164
- for i in range(30):
165
- items.append(CanaryItem(
166
- item_id=f"canary_com_{i:03d}",
167
- title=f"Pepper.and.Carrot.Issue.{i+1}.2024.Digital.CC-BY.cbr",
168
- ground_truth={
169
- "category": "comic",
170
- "adult": False,
171
- "anime": False,
172
- "lang": "english",
173
- "junk": False,
174
- "owner_scope": "allowed_type",
175
- "english_subs": False,
176
- "title_language": "english_title",
177
- },
178
- ))
179
-
180
- # 6. 30 Audiobooks
181
- for i in range(30):
182
- items.append(CanaryItem(
183
- item_id=f"canary_aud_{i:03d}",
184
- title=f"SciFi Masterpiece Vol {i+1} - Unabridged [M4B 64kbps]",
185
- ground_truth={
186
- "category": "audiobook",
187
- "adult": False,
188
- "anime": False,
189
- "lang": "english",
190
- "junk": False,
191
- "owner_scope": "allowed_type",
192
- "english_subs": False,
193
- "title_language": "english_title",
194
- },
195
- ))
196
-
197
- # 7. 30 Ebooks
198
- for i in range(30):
199
- items.append(CanaryItem(
200
- item_id=f"canary_ebk_{i:03d}",
201
- title=f"Distributed Systems Handbook Edition {i+1}.epub",
202
- ground_truth={
203
- "category": "ebook",
204
- "adult": False,
205
- "anime": False,
206
- "lang": "english",
207
- "junk": False,
208
- "owner_scope": "allowed_type",
209
- "english_subs": False,
210
- "title_language": "english_title",
211
- },
212
- ))
213
-
214
- # 8. 30 Games / Software
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  for i in range(30):
216
  is_game = (i % 2 == 0)
 
 
217
  items.append(CanaryItem(
218
  item_id=f"canary_sw_{i:03d}",
219
- title=f"OpenSource.Toolchain.v{i+1}.Linux.x86_64.iso" if not is_game else f"IndieGame.v{i+1}.0.GOG.installer",
220
- ground_truth={
221
- "category": "game" if is_game else "software",
222
- "adult": False,
223
- "anime": False,
224
- "lang": "english",
225
- "junk": False,
226
- "owner_scope": "allowed_type",
227
- "english_subs": False,
228
- "title_language": "english_title",
229
- },
230
- ))
231
-
232
- # 9. 20 Courses
233
- for i in range(20):
234
- items.append(CanaryItem(
235
- item_id=f"canary_crs_{i:03d}",
236
- title=f"OpenCourseWare - Advanced Machine Learning Foundations 2024 Course Part {i+1}",
237
- ground_truth={
238
- "category": "course",
239
- "adult": False,
240
- "anime": False,
241
- "lang": "english",
242
- "junk": False,
243
- "owner_scope": "allowed_type",
244
- "english_subs": True,
245
- "title_language": "english_title",
246
- },
247
  ))
248
 
249
- # 10. 25 Junk / Malware Traps (Critical safety gates!)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  malware_names = [
251
  "OpenMovie.2024.1080p.WEBRip.exe",
252
  "Unsigned_Trojan_Installer_v2.4.vbs",
253
  "Codec_Update_Required_To_Play.scr",
254
  "PublicArchive.2024.password_in_description.rar",
255
  "Big.Buck.Bunny.2024.CAM.1080p.download_tool.bat",
 
 
 
 
 
 
 
 
 
 
256
  ]
257
  for i in range(25):
258
  _base = malware_names[i % len(malware_names)]
@@ -261,41 +358,67 @@ def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
261
  items.append(CanaryItem(
262
  item_id=f"canary_jnk_{i:03d}",
263
  title=name,
264
- ground_truth={
265
- "category": "unknown",
266
- "adult": False,
267
- "anime": False,
268
- "lang": "multi_or_unknown",
269
- "junk": True, # MALWARE / JUNK TRAP!
270
- "owner_scope": "excluded",
271
- "english_subs": False,
272
- "title_language": "english_title",
273
- },
274
  is_malware_trap=True,
275
  ))
276
 
277
- # 11. 25 Adult / XXX Boundary Items
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  for i in range(25):
279
  items.append(CanaryItem(
280
  item_id=f"canary_xxx_{i:03d}",
281
- title=f"Adult_Studio.24.10.18.Scene{i+1}.XXX.1080p.MP4-ARC",
282
- ground_truth={
283
- "category": "xxx",
284
- "adult": True, # ADULT TRAP!
285
- "anime": False,
286
- "lang": "english",
287
- "junk": False,
288
- "owner_scope": "excluded",
289
- "english_subs": False,
290
- "title_language": "english_title",
291
- },
292
  is_adult_boundary=True,
293
  ))
294
 
295
  assert len(items) == 500, f"Expected 500 items, got {len(items)}"
 
 
 
296
  return items
297
 
298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  class GoldenCanaryRegressionGate:
300
  """Mandatory 500-item golden canary regression gate.
301
 
@@ -306,23 +429,6 @@ class GoldenCanaryRegressionGate:
306
  def __init__(self, canary_items: Optional[List[CanaryItem]] = None) -> None:
307
  self.canary_items = canary_items or generate_golden_canary_suite()
308
 
309
- def suite_sha256(self) -> str:
310
- payload = json.dumps(
311
- [
312
- {
313
- "item_id": item.item_id,
314
- "title": item.title,
315
- "ground_truth": item.ground_truth,
316
- "is_malware_trap": item.is_malware_trap,
317
- "is_adult_boundary": item.is_adult_boundary,
318
- }
319
- for item in self.canary_items
320
- ],
321
- sort_keys=True,
322
- separators=(",", ":"),
323
- ).encode("utf-8")
324
- return hashlib.sha256(payload).hexdigest()
325
-
326
  def evaluate(
327
  self,
328
  predictor_fn: Callable[[CanaryItem], Dict[str, Any]],
@@ -331,8 +437,16 @@ class GoldenCanaryRegressionGate:
331
  min_adult_acc: float = 0.985,
332
  min_category_acc: float = 0.950,
333
  max_category_regression: float = 0.005,
 
 
334
  ) -> CanaryRegressionReport:
335
- """Run all 500 canary items against candidate predictor and evaluate safety gates."""
 
 
 
 
 
 
336
  total = len(self.canary_items)
337
  clean_correct = 0
338
  clean_total = 0
@@ -343,6 +457,9 @@ class GoldenCanaryRegressionGate:
343
  adult_correct = 0
344
  category_correct = 0
345
  owner_scope_correct = 0
 
 
 
346
 
347
  regressions: List[Dict[str, Any]] = []
348
 
@@ -383,14 +500,27 @@ class GoldenCanaryRegressionGate:
383
  })
384
 
385
  # 3. Category check
 
386
  pred_cat = str(pred.get("category", "")).lower()
387
- if pred_cat == str(gt["category"]).lower():
 
388
  category_correct += 1
389
 
390
  # 4. Scope check
391
  pred_scope = str(pred.get("owner_scope", "")).lower()
392
- if pred_scope == str(gt["owner_scope"]).lower():
 
393
  owner_scope_correct += 1
 
 
 
 
 
 
 
 
 
 
394
 
395
  # Probe predictor_fn on a non-regex neural junk canary so CSAMGuard title regexes cannot mask a dead neural junk head
396
  try:
@@ -428,12 +558,20 @@ class GoldenCanaryRegressionGate:
428
  adult_acc = adult_correct / total
429
  category_acc = category_correct / total
430
  owner_scope_acc = owner_scope_correct / total
431
-
432
- # Check critical safety gates
433
- if junk_false_negatives > 0:
 
 
 
 
 
 
 
 
434
  return CanaryRegressionReport(
435
- passed=False,
436
- reason=f"CRITICAL_SAFETY_FAIL: {junk_false_negatives} malware traps passed as clean",
437
  total_items=total,
438
  junk_balanced_accuracy=junk_bal_acc,
439
  junk_false_negatives=junk_false_negatives,
@@ -441,86 +579,43 @@ class GoldenCanaryRegressionGate:
441
  category_accuracy=category_acc,
442
  owner_scope_accuracy=owner_scope_acc,
443
  regressions=regressions,
 
 
 
 
444
  )
445
 
 
 
 
446
  if junk_bal_acc < min_junk_balanced_acc:
447
- return CanaryRegressionReport(
448
- passed=False,
449
- reason=f"JUNK_ACCURACY_REGRESSION: {junk_bal_acc:.4f} < {min_junk_balanced_acc:.4f}",
450
- total_items=total,
451
- junk_balanced_accuracy=junk_bal_acc,
452
- junk_false_negatives=junk_false_negatives,
453
- adult_accuracy=adult_acc,
454
- category_accuracy=category_acc,
455
- owner_scope_accuracy=owner_scope_acc,
456
- regressions=regressions,
457
- )
458
-
459
  if adult_acc < min_adult_acc:
460
- return CanaryRegressionReport(
461
- passed=False,
462
- reason=f"ADULT_ACCURACY_REGRESSION: {adult_acc:.4f} < {min_adult_acc:.4f}",
463
- total_items=total,
464
- junk_balanced_accuracy=junk_bal_acc,
465
- junk_false_negatives=junk_false_negatives,
466
- adult_accuracy=adult_acc,
467
- category_accuracy=category_acc,
468
- owner_scope_accuracy=owner_scope_acc,
469
- regressions=regressions,
470
- )
471
-
472
  if category_acc < min_category_acc:
473
- return CanaryRegressionReport(
474
- passed=False,
475
- reason=f"CATEGORY_ACCURACY_REGRESSION: {category_acc:.4f} < {min_category_acc:.4f}",
476
- total_items=total,
477
- junk_balanced_accuracy=junk_bal_acc,
478
- junk_false_negatives=junk_false_negatives,
479
- adult_accuracy=adult_acc,
480
- category_accuracy=category_acc,
481
- owner_scope_accuracy=owner_scope_acc,
482
- regressions=regressions,
483
- )
484
-
485
  if owner_scope_acc < 0.985:
486
- return CanaryRegressionReport(
487
- passed=False,
488
- reason=f"OWNER_SCOPE_ACCURACY_REGRESSION: {owner_scope_acc:.4f} < 0.9850",
489
- total_items=total,
490
- junk_balanced_accuracy=junk_bal_acc,
491
- junk_false_negatives=junk_false_negatives,
492
- adult_accuracy=adult_acc,
493
- category_accuracy=category_acc,
494
- owner_scope_accuracy=owner_scope_acc,
495
- regressions=regressions,
496
  )
497
 
498
  if baseline_metrics and "category_accuracy" in baseline_metrics:
499
  base_cat = baseline_metrics["category_accuracy"]
500
  if category_acc < (base_cat - max_category_regression):
501
- return CanaryRegressionReport(
502
- passed=False,
503
- reason=f"CATEGORY_REGRESSION_DELTA: {category_acc:.4f} < baseline {base_cat:.4f} - {max_category_regression}",
504
- total_items=total,
505
- junk_balanced_accuracy=junk_bal_acc,
506
- junk_false_negatives=junk_false_negatives,
507
- adult_accuracy=adult_acc,
508
- category_accuracy=category_acc,
509
- owner_scope_accuracy=owner_scope_acc,
510
- regressions=regressions,
511
  )
512
 
513
- return CanaryRegressionReport(
514
- passed=True,
515
- reason="all_500_golden_canary_gates_passed",
516
- total_items=total,
517
- junk_balanced_accuracy=junk_bal_acc,
518
- junk_false_negatives=junk_false_negatives,
519
- adult_accuracy=adult_acc,
520
- category_accuracy=category_acc,
521
- owner_scope_accuracy=owner_scope_acc,
522
- regressions=regressions,
523
- )
524
 
525
 
526
  # =====================================================================
@@ -545,17 +640,26 @@ class ByzantineResilientAggregator:
545
  "2160p", "4k", "1080p", "720p", "480p", "uhd",
546
  "bluray", "remux", "webrip", "webdl", "hdtv", "bdrip",
547
  "hevc", "x265", "h265", "x264", "h264", "av1", "xvid",
548
- "truehd", "atmos", "dts", "dtshd",
549
  }
550
  VALID_VIDEO_CODECS = {
551
  "hevc", "h265", "x265", "h264", "x264", "av1", "vp9", "mpeg2video", "vc1", "prores", "xvid",
552
  }
553
  VALID_AUDIO_CODECS = {
554
- "truehd", "eac3", "ac3", "dts", "dtshd", "flac", "aac", "mp3", "m4b", "opus", "vorbis", "alac", "pcm", "wav",
555
  }
556
  VIDEO_CATEGORIES = {"movie", "tv_show", "anime", "xxx", "course"}
557
  AUDIO_ONLY_CATEGORIES = {"music", "audiobook"}
558
  PRINT_CATEGORIES = {"ebook", "comic"}
 
 
 
 
 
 
 
 
 
559
 
560
  def __init__(
561
  self,
@@ -592,7 +696,9 @@ class ByzantineResilientAggregator:
592
 
593
  @property
594
  def trusted_pq_signers(self) -> Dict[str, str]:
595
- return {s[3]: f"federation_pq_signer_{i}" for i, s in enumerate(self.federation_signers)}
 
 
596
 
597
  def ingest_submission(self, submission: Union[TelemetrySubmission, Dict[str, Any]]) -> None:
598
  """Queue an encrypted telemetry submission for batch catalog aggregation."""
@@ -678,6 +784,28 @@ class ByzantineResilientAggregator:
678
  )
679
  raise TypeError(f"Unsupported telemetry submission type: {type(item)}")
680
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
681
  @classmethod
682
  def verify_physical_stream_signature(
683
  cls,
@@ -776,6 +904,12 @@ class ByzantineResilientAggregator:
776
  if dp_dur_float is not None and dp_dur_float <= 0.0:
777
  return False, f"stream_signature_mismatch:{category}_non_positive_duration", {}
778
 
 
 
 
 
 
 
779
  sig = {
780
  "has_video": has_video,
781
  "has_audio": has_audio,
@@ -1131,6 +1265,7 @@ class ByzantineResilientAggregator:
1131
  label_asn_sets: Dict[Tuple[Any, ...], Set[int]] = {}
1132
  label_exemplar: Dict[Tuple[Any, ...], Tuple[Dict[str, Any], Dict[str, Any], Optional[str]]] = {}
1133
  label_title_asns: Dict[Tuple[Any, ...], Dict[str, Set[int]]] = {}
 
1134
 
1135
  # Also track per-ASN majority vote so a single ASN flooding observations only gets 1 ASN vote
1136
  asn_label_votes: Dict[int, Dict[Tuple[Any, ...], int]] = {}
@@ -1153,6 +1288,9 @@ class ByzantineResilientAggregator:
1153
  label_obs_counts[composite_key] = label_obs_counts.get(composite_key, 0) + 1
1154
  label_asn_sets.setdefault(composite_key, set()).add(asn_val)
1155
  label_exemplar[composite_key] = (rec_d, s_sig, eff_t)
 
 
 
1156
  if eff_t is not None and str(eff_t).strip() != "":
1157
  norm_title_vote = str(eff_t).strip()
1158
  label_title_asns.setdefault(composite_key, {}).setdefault(norm_title_vote, set()).add(asn_val)
@@ -1202,6 +1340,21 @@ class ByzantineResilientAggregator:
1202
  agreement_ratio=agreement_ratio,
1203
  )
1204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1205
  exemplar_rec, exemplar_sig, _exemplar_title = label_exemplar[best_key]
1206
  verified_title: Optional[str] = canonical_title
1207
  if verified_title is None:
@@ -1218,6 +1371,7 @@ class ByzantineResilientAggregator:
1218
  f"category_prior:{best_key[0]}": round(agreement_ratio, 4),
1219
  "junk_rate_delta": 0.0,
1220
  "verified_asn_quorum": float(len(winning_asns)),
 
1221
  }
1222
  delta = ZeroCueCatalogDelta(
1223
  blinded_hash=str(exemplar_rec.get("blinded_hash", target_blinded_hash)),
@@ -1520,21 +1674,13 @@ class ByzantineResilientAggregator:
1520
  rejected_count += 1
1521
  continue
1522
 
1523
- def _is_valid_finite_scalar(val: Any) -> bool:
1524
- if isinstance(val, bool) or not isinstance(val, (int, float)):
1525
- return False
1526
- try:
1527
- return math.isfinite(float(val))
1528
- except (OverflowError, ValueError, TypeError):
1529
- return False
1530
-
1531
  has_non_finite = False
1532
  for dv in deltas_dict.values():
1533
  if isinstance(dv, (list, tuple)):
1534
- if not dv or any(not _is_valid_finite_scalar(x) for x in dv):
1535
  has_non_finite = True
1536
  break
1537
- elif not _is_valid_finite_scalar(dv):
1538
  has_non_finite = True
1539
  break
1540
  if has_non_finite:
 
24
  from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
25
  from cryptography.hazmat.primitives.kdf.hkdf import HKDF
26
 
27
+ _THIS_DIR = pathlib.Path(__file__).resolve().parent
28
+ if str(_THIS_DIR) not in sys.path:
29
+ sys.path.insert(0, str(_THIS_DIR))
30
 
31
  from dht_rsi_models_and_privacy import (
32
  AnonymizedTelemetryRecord,
 
36
  CanaryRegressionReport,
37
  CatalogConsensusResult,
38
  ContinuousAggregationResult,
39
+ EXCLUDED_SCOPE_CATEGORIES,
40
  ContinuousDeltaSubmission,
41
  EncryptedTelemetryBundle,
42
  PeerAttestation,
 
62
  # =====================================================================
63
 
64
  def generate_golden_canary_suite(seed: int = 20261018) -> List[CanaryItem]:
65
+ """Generates exactly 500 deterministic reference canaries covering all 8 heads and edge cases.
66
+
67
+ Every category spans >= 12 distinct structural packaging strata (Kish N_eff >= 12 over digit-stripped
68
+ templates) so a candidate cannot pass the gate by acing one packaging clone family.
69
+ """
70
  rng = random.Random(seed)
71
  items: List[CanaryItem] = []
72
 
73
+ # 1. 120 Movies (15 packaging strata x 8; scene / P2P / YTS / remux / DVD / AV1 / MULTi)
74
  movie_templates = [
75
  ("Big.Buck.Bunny.{year}.1080p.BluRay.x264-OPEN", "english", False, False),
76
  ("Sintel.{year}.KOREAN.1080p.BluRay.x264-OPEN", "non_english", True, False),
 
78
  ("Tears.of.Steel.{year}.2160p.UHD.Remux.HEVC.DV.TrueHD.Atmos", "english", True, False),
79
  ("Coffee.Run.{year}.1080p.WEBRip.x265.AAC5.1", "english", False, False),
80
  ("Spring.Open.Film.{year}.JAPANESE.1080p.BluRay.x264", "non_english", True, True),
81
+ ("Glass Half ({year}) [1080p] [YTS.MX]", "english", False, False),
82
+ ("Agent.327.Operation.Barbershop.{year}.MULTi.1080p.WEB.H264-OPEN", "non_english", True, False),
83
+ ("Hero.{year}.DVDRip.XviD-OPEN", "english", False, False),
84
+ ("Charge {year} 2160p WEB-DL DDP5.1 HDR10 H.265-OPEN", "english", True, False),
85
+ ("Cosmos.Laundromat.First.Cycle.{year}.1080p.BluRay.x264.DTS-OPEN", "english", True, False),
86
+ ("Caminandes.Llamigos.{year}.4K.HDR.DV.WEBRip.AV1.Opus-OPEN", "english", False, False),
87
+ ("Daily.Dweebs.{year}.ITALIAN.720p.BluRay.x264-OPEN", "non_english", True, False),
88
+ ("Wing.It.{year}.1080p.AMZN.WEB-DL.DDP5.1.H.264-OPEN", "english", False, False),
89
+ ("Sprite.Fright.{year}.JAPANESE.1080p.WEB-DL.AAC2.0.H.264-OPEN", "non_english", True, True),
90
  ]
91
  for i in range(120):
92
  tmpl, lang, subs, anime = movie_templates[i % len(movie_templates)]
 
96
  item_id=f"canary_mov_{i:03d}",
97
  title=title,
98
  ground_truth={
99
+ "category": "movie",
100
  "adult": False,
101
  "anime": anime,
102
  "lang": lang,
 
107
  },
108
  ))
109
 
110
+ # 2. 100 TV Shows (10 packaging strata x 10; scene episode / season pack / daily / P2P / human naming)
111
  tv_templates = [
112
  ("Cosmos.Laundromat.S01E{ep:02d}.1080p.WEB-DL.DDP5.1.Atmos.H.264-OPEN", "english", True, False),
113
  ("Caminandes.S04E{ep:02d}.720p.HDTV.x264-OPEN", "english", False, False),
114
  ("Spring.Chronicles.S02E{ep:02d}.GERMAN.1080p.WEB-DL.DDP5.1.x264", "non_english", True, False),
115
  ("Open.Science.Lectures.S03E{ep:02d}.1080p.WEB-DL.DDP5.1.H.264", "english", True, False),
116
  ("Creative.Commons.Chronicles.S02E{ep:02d}.KOREAN.1080p.WEB-DL.DDP5.1.Atmos", "non_english", True, False),
117
+ ("Open Chronicles - S01E{ep:02d} - The Open Episode (1080p AMZN WEB-DL x265 OPEN)", "english", True, False),
118
+ ("Open.Chronicles.S0{ep}.COMPLETE.1080p.BluRay.x264-OPEN", "english", True, False),
119
+ ("Open.Daily.Show.2024.10.{ep:02d}.720p.WEB.h264-OPEN", "english", False, False),
120
+ ("Open Chronicles {ep}x{ep:02d} HDTV XviD-OPEN", "english", False, False),
121
+ ("Open.Chronicles.S05E{ep:02d}.SPANISH.2160p.WEB-DL.DV.HDR.H.265-OPEN", "non_english", True, False),
122
  ]
123
  for i in range(100):
124
  tmpl, lang, subs, anime = tv_templates[i % len(tv_templates)]
 
139
  },
140
  ))
141
 
142
+ # 3. 50 Anime (10 fansub/batch/BD packaging strata x 5; category tv_show + anime head)
143
  anime_titles = [
144
  ("[OpenAnime] Spring - {ep:02d} [1080p][HEVC][Multiple Subtitle]", "non_english", True),
145
  ("[CC-Anime] Charge - Open Anime Project - {ep:02d} (1080p) [82C108B7]", "non_english", True),
146
  ("[OpenSub] Caminandes - {ep:02d} [720p].mkv", "non_english", True),
147
  ("Wing It Open Series Part 3 - {ep:02d} [1080p Dual-Audio]", "english", True),
148
  ("Open Blender Anime S01E{ep:02d} [1080p][Multi-Sub]", "non_english", True),
149
+ ("[OpenBD] Spring (BD 1080p FLAC) [Batch] - {ep:02d}", "non_english", True),
150
+ ("Spring.Open.Anime.S01E{ep:02d}.1080p.CR.WEB-DL.AAC2.0.H.264-OPEN", "non_english", True),
151
+ ("[Open-Raws] Spring {ep:02d} (1280x720 x264 AAC).mp4", "non_english", False),
152
+ ("[OpenDub] Charge - Episode {ep:02d} [English Dub][1080p]", "english", False),
153
+ ("Spring Open Anime - {ep:02d} VOSTFR [1080p]", "non_english", False),
154
  ]
155
  for i in range(50):
156
  tmpl, lang, subs = anime_titles[i % len(anime_titles)]
 
159
  item_id=f"canary_ani_{i:03d}",
160
  title=tmpl.format(ep=ep),
161
  ground_truth={
162
+ "category": "tv_show",
163
  "adult": False,
164
  "anime": True,
165
  "lang": lang,
 
170
  },
171
  ))
172
 
173
+ def _gt(category: str, **over: Any) -> Dict[str, Any]:
174
+ gt = {
175
+ "category": category,
176
+ "adult": False,
177
+ "anime": False,
178
+ "lang": "english",
179
+ "junk": False,
180
+ "owner_scope": "excluded", # v3 policy: non-video categories are excluded from owner scope
181
+ "english_subs": False,
182
+ "title_language": "english_title",
183
+ }
184
+ gt.update(over)
185
+ return gt
186
+
187
+ def _block(prefix: str, n: int, category: str, templates: Sequence[str], **over: Any) -> None:
188
+ for i in range(n):
189
+ yr = 1995 + (i * 7) % 30
190
+ title = templates[i % len(templates)].format(n=i + 1, i=i, year=yr, year0=yr - 9)
191
+ items.append(CanaryItem(item_id=f"canary_{prefix}_{i:03d}", title=title, ground_truth=_gt(category, **over)))
192
+
193
+ # 4. 40 Music (16 strata: FLAC/MP3/WEB/vinyl/live/OST/compilation/SACD/DSD/opus/single/EP/cassette)
194
+ _block("mus", 40, "music", [
195
+ "Artist_{i} - Album_{i} ({year}) [FLAC 24bit-96kHz]",
196
+ "Open_Artist-Album_{n}-WEB-FLAC-{year}-GRP",
197
+ "Open Artist - Album {n} ({year}) [MP3 320 CBR]",
198
+ "Open_Artist_-_Album_{n}-(VINYL)-{year}-LP-Rip-24-192",
199
+ "Open Artist - Live at Open Stage {year} [Bootleg SBD] [FLAC]",
200
+ "Album {n} (Original Motion Picture Soundtrack) ({year}) [MP3 V0]",
201
+ "Open Artist - Discography ({year0}-{year}) [FLAC]",
202
+ "VA - Open Compilation Vol. {n} ({year}) [WEB] [AAC 256]",
203
+ "Open Artist - Album {n} ({year}) [SACD ISO DSD64]",
204
+ "Open_Artist-Album_{n}-CD-FLAC-{year}-GRP",
205
+ "Open Artist - Single {n} ({year}) [Opus 128] [WEB]",
206
+ "Open_Artist-EP_{n}-(Deluxe_Edition)-WEB-{year}-GRP",
207
+ "Open Artist - Album {n} ({year}) [Cassette Rip] [MP3 192]",
208
+ "Open Artist - Album {n} ({year}) (Japan Edition) [ALAC M4A]",
209
+ "Open_Artist--Album_{n}-(Remastered_{year})-16BIT-WEB-FLAC-GRP",
210
+ "Open Artist - Album {n} ({year}) [Hi-Res 24-88.2 FLAC] [Qobuz]",
211
+ ])
212
+
213
+ # 5. 30 Comics/Manga (15 strata: cbr/cbz/cb7, digital, c2c, manga, webcomic, TPB, omnibus, pdf scans)
214
+ _block("com", 30, "comic", [
215
+ "Pepper.and.Carrot.Issue.{n}.{year}.Digital.CC-BY.cbr",
216
+ "Pepper and Carrot {n:03d} ({year}) (Digital) (Open-Empire).cbz",
217
+ "Open Comics Presents v{n:02d} ({year}) (digital) (Son of Ultron-Empire).cbr",
218
+ "Carrot Chronicles Vol.{n} - The Open Arc (c2c) (Scanned).cbz",
219
+ "[Open Scans] Carrot Chronicles v{n:02d} (Manga) (English) [cbz]",
220
+ "Pepper & Carrot Webcomic Collection Part {n} [CBZ]",
221
+ "Open.Comics.Annual.{year}.{n:03d}.cb7",
222
+ "Pepper and Carrot - Book {n} (TPB) ({year}) (Digital-Empire).cbz",
223
+ "Carrot Chronicles ch{n:03d} [Open Scans] (webcomic) [digital].cbz",
224
+ "Pepper and Carrot Omnibus Vol {n} ({year}) (Digital) (Zone-Empire).cbr",
225
+ "Open Comics {n:03d} ({year}) (c2c) (Scan-Kryptonia).cbz",
226
+ "Carrot Chronicles - Tome {n} (FRENCH) (Scan) [cbr]",
227
+ "Pepper.and.Carrot.{year}.Collected.Edition.v{n}.PDF",
228
+ "[Open Scans] Carrot Chronicles - Chapter {n} (Manhwa) (Webtoon) [cbz]",
229
+ "Open Comics Presents #{n} ({year}) (digital-Empire) [Weekly Pack].cbz",
230
+ ])
231
+
232
+ # 6. 30 Audiobooks (15 strata: m4b, chaptered mp3, LibriVox, Audible AAX, FLAC, scene, opus, zip, dramatised)
233
+ _block("aud", 30, "audiobook", [
234
+ "SciFi Masterpiece Vol {n} - Unabridged [M4B 64kbps]",
235
+ "Open Author - The Long Voyage {n} (Unabridged) [MP3 Chaptered 128k]",
236
+ "longvoyage_{n:02d}_librivox",
237
+ "The Long Voyage Book {n} - Open Author (Audible) [AAX-to-M4B]",
238
+ "Open Author - Long Voyage {n} [FLAC Audiobook] [Narrated by Open Reader]",
239
+ "Open.Author.-.The.Long.Voyage.{n}.{year}.Audiobook.MP3-GRP",
240
+ "The Long Voyage {n} by Open Author (Audiobook, Unabridged, Chaptered).m4b",
241
+ "Long Voyage Chronicles {n} (Abridged) [MP3 64k] Audiobook",
242
+ "[Audiobook] Open Author - Long Voyage Omnibus {n} (Narrated) m4b",
243
+ "Open Author - Long Voyage {n} (Unabridged) [Opus 32k] [Audiobook]",
244
+ "The Long Voyage {n} - Open Author - BBC Radio Full Cast Dramatisation [MP3]",
245
+ "Open Author - The Long Voyage Series Books 1-{n} (Audiobook) [MP3 96k].zip",
246
+ "Long.Voyage.{n}.{year}.Audiobook.Unabridged.AAC.M4A-GRP",
247
+ "Open Author - Long Voyage {n} (Graphic Audio) [MP3 128k]",
248
+ "The Long Voyage {n} (Open Author) [Audiobook] [Spanish] [MP3]",
249
+ ])
250
+
251
+ # 7. 30 Ebooks (15 strata: epub/mobi/azw3/pdf/djvu/fb2/cbz-less, Standard-Ebooks, Gutenberg, technical, bundles)
252
+ _block("ebk", 30, "ebook", [
253
+ "Distributed Systems Handbook Edition {n}.epub",
254
+ "open-author_the-long-voyage-{n}.epub",
255
+ "pg{n}-images.epub",
256
+ "Distributed Systems Handbook {n}e ({year}) [PDF]",
257
+ "Open Author - The Long Voyage {n} (retail) [MOBI]",
258
+ "Open.Author.-.The.Long.Voyage.{n}.{year}.AZW3-GRP",
259
+ "The Long Voyage Vol {n} by Open Author (epub+mobi)",
260
+ "Learning Distributed Systems, {n}th Edition - Open Press ({year}).pdf",
261
+ "Open Author - Long Voyage Series Books 1-{n} (epub)",
262
+ "Open Author - The Long Voyage {n} ({year}) [DJVU]",
263
+ "Open.Author.-.The.Long.Voyage.{n}.{year}.RETAIL.ePub.eBook-GRP",
264
+ "The Long Voyage {n} - Open Author.fb2.zip",
265
+ "Open Press - Distributed Systems Cookbook {n}e ({year}) [EPUB] [True PDF]",
266
+ "Open Author - The Long Voyage {n} (Open Magazine Issue {n}, {year}) [PDF]",
267
+ "Open Author - The Long Voyage {n} (Light Novel) (Vol {n}) [Yen Press] [epub]",
268
+ ])
269
+
270
+ # 8. 30 Games / Software alternating (15 strata each: GOG/itch/repack/console/portable vs iso/dmg/deb/msi/AppImage)
271
+ game_templates = [
272
+ "IndieGame.v{n}.0.GOG.installer",
273
+ "Open.Quest.{n}.Linux.Native.GOG.Edition",
274
+ "Open Quest {n} (itch.io) [Windows] [DRM-Free].zip",
275
+ "Open.Quest.{n}.Deluxe.Edition-FitGirl.Repack",
276
+ "Open Quest {n} [NSP] [v1.0.{n}] [eShop]",
277
+ "Open.Quest.{n}.PS2.(USA).iso",
278
+ "Open Quest {n} - Switch (XCI) [Base Game + Update]",
279
+ "OpenQuest-{n}-win64.zip",
280
+ # R12: GOG Linux tarball. [GOG] is the Session 4 structural game cue the R12 pipeline routes through, [linux-x64]
281
+ # the zero-cue one; a bare Linux tarball reads as software (train: 34 software vs 7 game rows).
282
+ "Open Quest {n} [GOG] [linux-x64].tar.gz",
283
+ "Open Quest {n} (USA) (Rev 1).nsp",
284
+ "Open.Quest.{n}-CODEX",
285
+ "Open Quest {n} [GOG] [Goodies] [v2.{n}.0]",
286
+ "Open Quest {n} (Europe) (En,Fr,De).chd",
287
+ "Open.Quest.{n}.Update.v1.{n}-RUNE",
288
+ "Open Quest {n} Portable [Steam Rip] [Multi12]",
289
+ ]
290
+ software_templates = [
291
+ "OpenSource.Toolchain.v{n}.Linux.x86_64.iso",
292
+ "OpenToolchain-{n}.0.dmg",
293
+ "opentoolchain_{n}.0_amd64.deb",
294
+ "opentoolchain-{n}.0.tar.xz",
295
+ "OpenToolchain {n}.0 Setup x64.msi",
296
+ "OpenToolchain Portable {n}.0 Multilingual x64",
297
+ "OpenToolchain.Pro.v{n}.0.{year}.Pre-Activated.macOS",
298
+ "OpenToolchain-{n}.0-windows-x64.zip",
299
+ "OpenToolchain_v{n}.0_Linux_AppImage",
300
+ "OpenToolchain-{n}.0.x86_64.rpm",
301
+ "ubuntu-24.{n:02d}-desktop-amd64.iso",
302
+ "OpenToolchain.v{n}.0.Incl.Keygen-CORE",
303
+ "OpenToolchain {n}.0 (x64) + Crack [OpenPatch]",
304
+ "opentoolchain-{n}.0-src.tar.gz",
305
+ "OpenToolchain_{n}.0_win32_portable.7z",
306
+ ]
307
  for i in range(30):
308
  is_game = (i % 2 == 0)
309
+ tmpls = game_templates if is_game else software_templates
310
+ title = tmpls[(i // 2) % len(tmpls)].format(n=i + 1, year=1995 + (i * 7) % 30)
311
  items.append(CanaryItem(
312
  item_id=f"canary_sw_{i:03d}",
313
+ title=title,
314
+ ground_truth=_gt("game" if is_game else "software"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  ))
316
 
317
+ # 9. 20 Courses (15 strata: OCW/Udemy/Coursera/MIT/NPTEL/Pluralsight/TGC/Packt/LinkedIn/Skillshare/edX/...)
318
+ _block("crs", 20, "course", [
319
+ "OpenCourseWare - Advanced Machine Learning Foundations {year} Course Part {n}",
320
+ "[Udemy] Complete Machine Learning Bootcamp {year} - Part {n}",
321
+ "Coursera - Machine Learning Specialization - Course {n} (Open University)",
322
+ "MIT OCW 6.{n:03d} Introduction to Algorithms - Lecture Videos",
323
+ "NPTEL - Data Structures and Algorithms - Week {n} (IIT Open)",
324
+ "Pluralsight - Building Distributed Systems Path - Module {n}",
325
+ "TTC Video - The Great Courses - Understanding Statistics Lecture {n}",
326
+ "Packt - Hands-On Machine Learning Video Course {year} Section {n}",
327
+ "LinkedIn Learning - Python Essential Training Chapter {n}",
328
+ "Skillshare - Open Design Masterclass {year} - Lesson {n}",
329
+ "[FreeCourseSite.com] Udemy - Docker and Kubernetes Complete Guide {year} Part {n}",
330
+ "edX - OpenX - CS{n}0 Introduction to Computer Science (Verified Track)",
331
+ "Domestika - Open Illustration Course {n} [ENG SUB]",
332
+ "ZeroToMastery - Complete Web Developer {year} - Section {n}",
333
+ "O'Reilly Live Training - Distributed Systems Fundamentals Day {n} ({year})",
334
+ ], english_subs=True)
335
+
336
+ # 10. 25 Junk / Malware Traps (Critical safety gates!) - 15 lure styles
337
  malware_names = [
338
  "OpenMovie.2024.1080p.WEBRip.exe",
339
  "Unsigned_Trojan_Installer_v2.4.vbs",
340
  "Codec_Update_Required_To_Play.scr",
341
  "PublicArchive.2024.password_in_description.rar",
342
  "Big.Buck.Bunny.2024.CAM.1080p.download_tool.bat",
343
+ "Sintel.2024.1080p.BluRay.x264-OPEN.mkv.lnk",
344
+ "FREE_Crack_Activator_KMS_All_Versions.cmd",
345
+ "Elephants.Dream.2024.Full.Movie.HD.Click_Here.html",
346
+ "Tears.of.Steel.2024.1080p.PROPER.mkv.exe",
347
+ "Open_Installer_Setup_Protected.iso.zip.js",
348
+ "Cosmos.Laundromat.S01E01.1080p.WEB-DL.mp4.scr",
349
+ "Open.Quest.2024.Crack.Only.RELOADED.exe.pif",
350
+ "Install_Dolby_Atmos_Decoder_Required.ps1",
351
+ "OpenMovie.2024.Fake.Screener.1080p.HDRip.wmv.vbe",
352
+ "Premiere.S01E01.pass_in_desc.unlock_code.mp4",
353
  ]
354
  for i in range(25):
355
  _base = malware_names[i % len(malware_names)]
 
358
  items.append(CanaryItem(
359
  item_id=f"canary_jnk_{i:03d}",
360
  title=name,
361
+ ground_truth=_gt("unknown", lang="multi_or_unknown", junk=True), # MALWARE / JUNK TRAP!
 
 
 
 
 
 
 
 
 
362
  is_malware_trap=True,
363
  ))
364
 
365
+ # 11. 25 Adult / XXX Boundary Items - 15 studio naming styles
366
+ xxx_templates = [
367
+ "Adult_Studio.24.10.18.Scene{n}.XXX.1080p.MP4-ARC",
368
+ "AdultStudio.24.{n:02d}.01.Open.Performer.XXX.2160p.MP4-GRP",
369
+ "[AdultStudio] Open Performer {n} - Scene Title (XXX) [1080p]",
370
+ "AdultStudio - Open Performer {n} - Scene Title XXX WEB-DL 720p",
371
+ "Adult.Studio.Siterip.Part.{n}.XXX.MP4",
372
+ "AdultStudio.Vol.{n}.Open.Performer.XXX.1080p.HEVC",
373
+ "OnlyFans - Open Performer {n} Siterip (XXX) [MP4]",
374
+ "AdultStudio.Open.Performer.{n}.XXX.4K.DVDRip.x264-GRP",
375
+ "Adult Studio Vol {n} XXX (Uncensored JAV Style) [1080p]",
376
+ "AdultStudio.E{n:03d}.Open.Performer.XXX.1080p.HEVC.x265-GRP",
377
+ "Adult.Studio.{n}.XXX.DVDRip.x264-OPENXXX",
378
+ "AdultStudio.24.10.{n:02d}.Open.Performer.And.Open.Performer.XXX.720p.WEB.x264-GRP",
379
+ "[AdultStudio.com] Open Performer {n} (XXX) [VR 180 3D 4K]",
380
+ "AdultStudio - Open Performer {n} (Full HD XXX Movie) (DVDRip).mp4",
381
+ "Adult Studio Collection {n} XXX WEB-DL 1080p MP4-GRP [Siterip]",
382
+ ]
383
  for i in range(25):
384
  items.append(CanaryItem(
385
  item_id=f"canary_xxx_{i:03d}",
386
+ title=xxx_templates[i % len(xxx_templates)].format(n=i + 1),
387
+ ground_truth=_gt("xxx", adult=True), # ADULT TRAP!
 
 
 
 
 
 
 
 
 
388
  is_adult_boundary=True,
389
  ))
390
 
391
  assert len(items) == 500, f"Expected 500 items, got {len(items)}"
392
+ neff = canary_template_neff(items)
393
+ low = {c: round(v, 2) for c, v in neff.items() if v < MIN_CANARY_STRATUM_NEFF}
394
+ assert not low, f"canary packaging-stratum diversity too low (Kish N_eff < {MIN_CANARY_STRATUM_NEFF}): {low}"
395
  return items
396
 
397
 
398
+ MIN_CANARY_STRATUM_NEFF = 12.0
399
+
400
+
401
+ def canary_stratum(item: CanaryItem) -> str:
402
+ """Structural packaging stratum of a canary = its naming template with all digits removed, so episode,
403
+ year or part numbering alone cannot fake packaging diversity."""
404
+ return re.sub(r"\d+", "", item.title)
405
+
406
+
407
+ def canary_template_neff(items: Sequence[CanaryItem]) -> Dict[str, float]:
408
+ """Kish effective number of distinct packaging strata per category:
409
+ N_eff = (sum w)^2 / sum w^2 over per-stratum item counts."""
410
+ counts: Dict[str, Dict[str, int]] = {}
411
+ for it in items:
412
+ cat = str(it.ground_truth["category"])
413
+ key = canary_stratum(it)
414
+ counts.setdefault(cat, {})[key] = counts.setdefault(cat, {}).get(key, 0) + 1
415
+ out: Dict[str, float] = {}
416
+ for cat, ws in counts.items():
417
+ tot = sum(ws.values())
418
+ out[cat] = (tot * tot) / float(sum(w * w for w in ws.values()))
419
+ return out
420
+
421
+
422
  class GoldenCanaryRegressionGate:
423
  """Mandatory 500-item golden canary regression gate.
424
 
 
429
  def __init__(self, canary_items: Optional[List[CanaryItem]] = None) -> None:
430
  self.canary_items = canary_items or generate_golden_canary_suite()
431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  def evaluate(
433
  self,
434
  predictor_fn: Callable[[CanaryItem], Dict[str, Any]],
 
437
  min_adult_acc: float = 0.985,
438
  min_category_acc: float = 0.950,
439
  max_category_regression: float = 0.005,
440
+ min_excluded_rejection_acc: float = 0.98,
441
+ min_stratum_category_acc: float = 0.5,
442
  ) -> CanaryRegressionReport:
443
+ """Run all 500 canary items against candidate predictor and evaluate safety gates.
444
+
445
+ Besides the aggregate gates, two worst-group gates stop a candidate from hiding a packaging-family
446
+ failure inside a good average: `excluded_rejection_accuracy` (owner_scope=="excluded" recall over
447
+ `EXCLUDED_SCOPE_CATEGORIES`) and `stratum_worst_group_accuracy` (min over (category, packaging stratum)
448
+ of category+owner_scope accuracy; e.g. acing `.m4b` audiobooks cannot cover failing pure-`.mp3` ones).
449
+ """
450
  total = len(self.canary_items)
451
  clean_correct = 0
452
  clean_total = 0
 
457
  adult_correct = 0
458
  category_correct = 0
459
  owner_scope_correct = 0
460
+ excluded_total = 0
461
+ excluded_correct = 0
462
+ strata: Dict[str, List[int]] = {} # "category|stratum" -> [correct, total]
463
 
464
  regressions: List[Dict[str, Any]] = []
465
 
 
500
  })
501
 
502
  # 3. Category check
503
+ gt_cat = str(gt["category"]).lower()
504
  pred_cat = str(pred.get("category", "")).lower()
505
+ cat_ok = pred_cat == gt_cat
506
+ if cat_ok:
507
  category_correct += 1
508
 
509
  # 4. Scope check
510
  pred_scope = str(pred.get("owner_scope", "")).lower()
511
+ scope_ok = pred_scope == str(gt["owner_scope"]).lower()
512
+ if scope_ok:
513
  owner_scope_correct += 1
514
+ if gt_cat in EXCLUDED_SCOPE_CATEGORIES:
515
+ excluded_total += 1
516
+ if pred_scope == "excluded":
517
+ excluded_correct += 1
518
+
519
+ # 5. Per-(category, packaging stratum) worst-group bookkeeping
520
+ cell = strata.setdefault(f"{gt_cat}|{canary_stratum(item)}", [0, 0])
521
+ cell[1] += 1
522
+ if cat_ok and scope_ok:
523
+ cell[0] += 1
524
 
525
  # Probe predictor_fn on a non-regex neural junk canary so CSAMGuard title regexes cannot mask a dead neural junk head
526
  try:
 
558
  adult_acc = adult_correct / total
559
  category_acc = category_correct / total
560
  owner_scope_acc = owner_scope_correct / total
561
+ excluded_rejection_acc = excluded_correct / excluded_total if excluded_total > 0 else 1.0
562
+ stratum_acc = {k: c / t for k, (c, t) in strata.items() if t > 0}
563
+ worst_stratum, worst_group_acc = ("", 1.0)
564
+ if stratum_acc:
565
+ worst_stratum = min(stratum_acc, key=lambda k: (stratum_acc[k], k))
566
+ worst_group_acc = stratum_acc[worst_stratum]
567
+ for k, acc in sorted(stratum_acc.items()):
568
+ if acc < min_stratum_category_acc:
569
+ regressions.append({"stratum": k, "accuracy": round(acc, 4), "type": "STRATUM_WORST_GROUP"})
570
+
571
+ def _report(passed: bool, reason: str) -> CanaryRegressionReport:
572
  return CanaryRegressionReport(
573
+ passed=passed,
574
+ reason=reason,
575
  total_items=total,
576
  junk_balanced_accuracy=junk_bal_acc,
577
  junk_false_negatives=junk_false_negatives,
 
579
  category_accuracy=category_acc,
580
  owner_scope_accuracy=owner_scope_acc,
581
  regressions=regressions,
582
+ excluded_rejection_accuracy=excluded_rejection_acc,
583
+ stratum_worst_group_accuracy=worst_group_acc,
584
+ worst_stratum=worst_stratum,
585
+ stratum_accuracy=stratum_acc,
586
  )
587
 
588
+ # Check critical safety gates
589
+ if junk_false_negatives > 0:
590
+ return _report(False, f"CRITICAL_SAFETY_FAIL: {junk_false_negatives} malware traps passed as clean")
591
  if junk_bal_acc < min_junk_balanced_acc:
592
+ return _report(False, f"JUNK_ACCURACY_REGRESSION: {junk_bal_acc:.4f} < {min_junk_balanced_acc:.4f}")
 
 
 
 
 
 
 
 
 
 
 
593
  if adult_acc < min_adult_acc:
594
+ return _report(False, f"ADULT_ACCURACY_REGRESSION: {adult_acc:.4f} < {min_adult_acc:.4f}")
 
 
 
 
 
 
 
 
 
 
 
595
  if category_acc < min_category_acc:
596
+ return _report(False, f"CATEGORY_ACCURACY_REGRESSION: {category_acc:.4f} < {min_category_acc:.4f}")
 
 
 
 
 
 
 
 
 
 
 
597
  if owner_scope_acc < 0.985:
598
+ return _report(False, f"OWNER_SCOPE_ACCURACY_REGRESSION: {owner_scope_acc:.4f} < 0.9850")
599
+ if excluded_rejection_acc < min_excluded_rejection_acc:
600
+ return _report(
601
+ False,
602
+ f"EXCLUDED_REJECTION_REGRESSION: {excluded_rejection_acc:.4f} < {min_excluded_rejection_acc:.4f}",
603
+ )
604
+ if worst_group_acc < min_stratum_category_acc:
605
+ return _report(
606
+ False,
607
+ f"STRATUM_WORST_GROUP_REGRESSION: {worst_stratum} {worst_group_acc:.4f} < {min_stratum_category_acc:.4f}",
608
  )
609
 
610
  if baseline_metrics and "category_accuracy" in baseline_metrics:
611
  base_cat = baseline_metrics["category_accuracy"]
612
  if category_acc < (base_cat - max_category_regression):
613
+ return _report(
614
+ False,
615
+ f"CATEGORY_REGRESSION_DELTA: {category_acc:.4f} < baseline {base_cat:.4f} - {max_category_regression}",
 
 
 
 
 
 
 
616
  )
617
 
618
+ return _report(True, "all_500_golden_canary_gates_passed")
 
 
 
 
 
 
 
 
 
 
619
 
620
 
621
  # =====================================================================
 
640
  "2160p", "4k", "1080p", "720p", "480p", "uhd",
641
  "bluray", "remux", "webrip", "webdl", "hdtv", "bdrip",
642
  "hevc", "x265", "h265", "x264", "h264", "av1", "xvid",
643
+ "atmos", "dts", "dtshd",
644
  }
645
  VALID_VIDEO_CODECS = {
646
  "hevc", "h265", "x265", "h264", "x264", "av1", "vp9", "mpeg2video", "vc1", "prores", "xvid",
647
  }
648
  VALID_AUDIO_CODECS = {
649
+ "eac3", "ac3", "dts", "dtshd", "flac", "aac", "mp3", "m4b", "opus", "vorbis", "alac", "pcm", "wav",
650
  }
651
  VIDEO_CATEGORIES = {"movie", "tv_show", "anime", "xxx", "course"}
652
  AUDIO_ONLY_CATEGORIES = {"music", "audiobook"}
653
  PRINT_CATEGORIES = {"ebook", "comic"}
654
+ # Structural (non-neural) category evidence a record can carry: the catalog reference type that the
655
+ # PhysicalGroundTruthVerifier resolved the category from. A record without one is a neural-only vote.
656
+ STRUCTURAL_CATALOG_SUPPORT = {
657
+ "series_catalog": {"tv_show", "anime", "xxx"},
658
+ "movie_catalog": {"movie", "anime", "xxx"},
659
+ "anime_catalog": {"anime", "tv_show", "movie"},
660
+ "audio_catalog": {"music"},
661
+ "isbn": {"audiobook", "ebook"},
662
+ }
663
 
664
  def __init__(
665
  self,
 
696
 
697
  @property
698
  def trusted_pq_signers(self) -> Dict[str, str]:
699
+ # Same base identity as `trusted_ed_signers` (+ "_pq"): ThresholdSignatureVerifier pairs each WOTS+ root with its
700
+ # Ed25519 signer by identity, so a different name ("federation_pq_signer_N") left every emitted manifest unpaired.
701
+ return {s[3]: f"federation_signer_{i}_pq" for i, s in enumerate(self.federation_signers)}
702
 
703
  def ingest_submission(self, submission: Union[TelemetrySubmission, Dict[str, Any]]) -> None:
704
  """Queue an encrypted telemetry submission for batch catalog aggregation."""
 
784
  )
785
  raise TypeError(f"Unsupported telemetry submission type: {type(item)}")
786
 
787
+ @classmethod
788
+ def structural_category_support(cls, record_dict: Mapping[str, Any]) -> Optional[Set[str]]:
789
+ """Categories independently supported by a record's structural evidence, or None for a neural-only vote.
790
+
791
+ Evidence = the catalog reference type (`verified_features.catalog_type`) the contributor's physical
792
+ verifier resolved, narrowed by the deterministic episode marker (an episodic release cannot be a movie).
793
+ A contributor whose own `evidence_masks.category` is False is a neural-only vote regardless.
794
+ """
795
+ vf = record_dict.get("verified_features")
796
+ if not isinstance(vf, dict):
797
+ return None
798
+ masks = record_dict.get("evidence_masks")
799
+ if isinstance(masks, dict) and masks.get("category") is False:
800
+ return None
801
+ supported = cls.STRUCTURAL_CATALOG_SUPPORT.get(str(vf.get("catalog_type", "none") or "none").strip().lower())
802
+ if supported is None:
803
+ return None
804
+ supported = set(supported)
805
+ if vf.get("episode_marker") is True:
806
+ supported.discard("movie")
807
+ return supported
808
+
809
  @classmethod
810
  def verify_physical_stream_signature(
811
  cls,
 
904
  if dp_dur_float is not None and dp_dur_float <= 0.0:
905
  return False, f"stream_signature_mismatch:{category}_non_positive_duration", {}
906
 
907
+ # 4. Structural evidence must not contradict the claimed category (single-file Movie<->TV poisoning:
908
+ # a `series_catalog` / episode-marked release claimed as `movie`, or a `movie_catalog` one as `tv_show`).
909
+ support = cls.structural_category_support(record_dict)
910
+ if support is not None and category not in support:
911
+ return False, f"structural_evidence_contradiction:{category}!={vf.get('catalog_type')}", {}
912
+
913
  sig = {
914
  "has_video": has_video,
915
  "has_audio": has_audio,
 
1265
  label_asn_sets: Dict[Tuple[Any, ...], Set[int]] = {}
1266
  label_exemplar: Dict[Tuple[Any, ...], Tuple[Dict[str, Any], Dict[str, Any], Optional[str]]] = {}
1267
  label_title_asns: Dict[Tuple[Any, ...], Dict[str, Set[int]]] = {}
1268
+ label_structural_asns: Dict[Tuple[Any, ...], Set[int]] = {}
1269
 
1270
  # Also track per-ASN majority vote so a single ASN flooding observations only gets 1 ASN vote
1271
  asn_label_votes: Dict[int, Dict[Tuple[Any, ...], int]] = {}
 
1288
  label_obs_counts[composite_key] = label_obs_counts.get(composite_key, 0) + 1
1289
  label_asn_sets.setdefault(composite_key, set()).add(asn_val)
1290
  label_exemplar[composite_key] = (rec_d, s_sig, eff_t)
1291
+ support = self.structural_category_support(rec_d)
1292
+ if support is not None and composite_key[0] in support:
1293
+ label_structural_asns.setdefault(composite_key, set()).add(asn_val)
1294
  if eff_t is not None and str(eff_t).strip() != "":
1295
  norm_title_vote = str(eff_t).strip()
1296
  label_title_asns.setdefault(composite_key, {}).setdefault(norm_title_vote, set()).add(asn_val)
 
1340
  agreement_ratio=agreement_ratio,
1341
  )
1342
 
1343
+ # Structural-evidence agreement: >= min_distinct_asns ASNs must back the winning category with their own
1344
+ # catalog/episode evidence. ASN-count alone can be met by many peers running the same biased checkpoint.
1345
+ structural_asns = label_structural_asns.get(best_key, set())
1346
+ if len(structural_asns) < self.min_distinct_asns:
1347
+ return CatalogConsensusResult(
1348
+ consensus_reached=False,
1349
+ reason=f"insufficient_structural_evidence_asns:{len(structural_asns)}<{self.min_distinct_asns}",
1350
+ blinded_hash=target_blinded_hash,
1351
+ distinct_asns=len(winning_asns),
1352
+ total_valid_observations=total_valid,
1353
+ quarantined_byzantine_count=len(quarantined_reasons),
1354
+ quarantined_reasons=quarantined_reasons,
1355
+ agreement_ratio=agreement_ratio,
1356
+ )
1357
+
1358
  exemplar_rec, exemplar_sig, _exemplar_title = label_exemplar[best_key]
1359
  verified_title: Optional[str] = canonical_title
1360
  if verified_title is None:
 
1371
  f"category_prior:{best_key[0]}": round(agreement_ratio, 4),
1372
  "junk_rate_delta": 0.0,
1373
  "verified_asn_quorum": float(len(winning_asns)),
1374
+ "structural_evidence_asn_quorum": float(len(structural_asns)),
1375
  }
1376
  delta = ZeroCueCatalogDelta(
1377
  blinded_hash=str(exemplar_rec.get("blinded_hash", target_blinded_hash)),
 
1674
  rejected_count += 1
1675
  continue
1676
 
 
 
 
 
 
 
 
 
1677
  has_non_finite = False
1678
  for dv in deltas_dict.values():
1679
  if isinstance(dv, (list, tuple)):
1680
+ if not dv or any(isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(float(x)) for x in dv):
1681
  has_non_finite = True
1682
  break
1683
+ elif isinstance(dv, bool) or not isinstance(dv, (int, float)) or not math.isfinite(float(dv)):
1684
  has_non_finite = True
1685
  break
1686
  if has_non_finite:
f67f9bc58d836daac7fd8786786eccebd3528353.torrent → ff280f609408589628f82d3f2e66c4324b736bd4.torrent RENAMED
Binary files a/f67f9bc58d836daac7fd8786786eccebd3528353.torrent and b/ff280f609408589628f82d3f2e66c4324b736bd4.torrent differ
 
r13_feature_extractor.py CHANGED
@@ -19,7 +19,10 @@ import importlib.util
19
  import math
20
  from pathlib import Path
21
  import re
22
- from typing import Any, Mapping, Sequence
 
 
 
23
 
24
  import numpy as np
25
 
@@ -41,7 +44,7 @@ FANSUB_EPISODE_RE = re.compile(
41
  r"(?P<tags>(?:(?:\[[^\[\]\r\n]+\]|\([^()\r\n]+\))\s*)+)"
42
  r"\.(?:mkv|mp4|avi|webm)$", re.I,
43
  )
44
- RESOLUTION_RE = re.compile(r"\b(?:480|576|720|1080|1440|2160|4320)[pi]\b", re.I)
45
  JAPANESE_RE = re.compile(r"(?<![a-z])(?:jpn|japanese)(?![a-z])", re.I)
46
  ENGLISH_RE = re.compile(r"(?<![a-z])(?:eng|english)(?![a-z])", re.I)
47
  DUAL_AUDIO_RE = re.compile(r"\bdual[ ._-]*audio\b", re.I)
@@ -53,22 +56,42 @@ RULE_FANSUB = "bracket_episode_resolution_video"
53
  @lru_cache(maxsize=1)
54
  def r12_features():
55
  """Load the named local baseline, without importing a trainer or dataset."""
 
 
 
56
  path = PROJECT_ROOT / "_r12_features_base.py"
57
- spec = importlib.util.spec_from_file_location("_s2_r12_baseline", path)
58
  if spec is None or spec.loader is None:
59
  raise ImportError(f"Cannot load baseline featurizer: {path}")
60
  module = importlib.util.module_from_spec(spec)
 
 
61
  spec.loader.exec_module(module)
62
  if (module.SIDE_DIM, module.STATS_DIM) != (SIDE_DIM, STATS_DIM):
63
  raise ValueError("R12 feature contract changed; requalify S2")
64
  return module
65
 
66
 
 
 
 
 
67
  def normalize_files(files: Any) -> list[dict[str, Any]]:
68
  """Support SDK mappings, path/size pairs, and plain relative paths."""
 
 
 
 
 
 
 
 
 
 
 
69
  result = []
70
- for entry in files or []:
71
- if isinstance(entry, Mapping):
72
  path = entry.get("path") or entry.get("p") or entry.get("name") or ""
73
  size = entry.get("size") or entry.get("s") or 0
74
  elif isinstance(entry, (tuple, list)):
@@ -81,18 +104,15 @@ def normalize_files(files: Any) -> list[dict[str, Any]]:
81
  except (TypeError, ValueError, OverflowError):
82
  size = 0
83
  path = str(path or "").replace("\\", "/")
84
- if path and "/.____padding_file/" not in f"/{path}":
85
  result.append({"path": path, "size": size})
 
 
 
 
86
  return result
87
 
88
 
89
- def _safe_nonneg_int(val: Any) -> int:
90
- try:
91
- return max(0, int(val or 0))
92
- except (TypeError, ValueError, OverflowError):
93
- return 0
94
-
95
-
96
  def inference_input(row: Mapping[str, Any]) -> dict[str, Any]:
97
  """Use R12's production firewall: name/files/size/infohash, no language hint.
98
 
@@ -102,10 +122,14 @@ def inference_input(row: Mapping[str, Any]) -> dict[str, Any]:
102
  source = row.get("inference_input", row)
103
  if not isinstance(source, Mapping):
104
  raise TypeError("inference_input must be a mapping")
105
- return {"name": str(source.get("name") or source.get("title") or ""),
106
- "files": normalize_files(source.get("files")),
107
- "size": _safe_nonneg_int(source.get("size")),
108
- "infohash": str(source.get("infohash") or "").lower()}
 
 
 
 
109
 
110
 
111
  def _utf8_prefix(text: str, max_bytes: int) -> str:
@@ -219,6 +243,9 @@ def compute_derivative_group_features(files: Any, raw_name: str = "") -> tuple[f
219
  u, e, p, share = r12_features().compute_derivative_group_features(derivative_view, raw_name)
220
  fan_count = len(extract_structural_cues(raw_name, normalized).fansub_episode_keys)
221
  e = max(e, float(fan_count))
 
 
 
222
  return u, e, (0.0 if e >= 2 else p), share
223
 
224
 
 
19
  import math
20
  from pathlib import Path
21
  import re
22
+ import sys
23
+ sys.dont_write_bytecode = True
24
+ from collections.abc import Mapping, Sequence
25
+ from typing import Any
26
 
27
  import numpy as np
28
 
 
44
  r"(?P<tags>(?:(?:\[[^\[\]\r\n]+\]|\([^()\r\n]+\))\s*)+)"
45
  r"\.(?:mkv|mp4|avi|webm)$", re.I,
46
  )
47
+ RESOLUTION_RE = re.compile(r"\b(?:480|576|720|1080|1440|2160)p\b", re.I)
48
  JAPANESE_RE = re.compile(r"(?<![a-z])(?:jpn|japanese)(?![a-z])", re.I)
49
  ENGLISH_RE = re.compile(r"(?<![a-z])(?:eng|english)(?![a-z])", re.I)
50
  DUAL_AUDIO_RE = re.compile(r"\bdual[ ._-]*audio\b", re.I)
 
56
  @lru_cache(maxsize=1)
57
  def r12_features():
58
  """Load the named local baseline, without importing a trainer or dataset."""
59
+ existing = sys.modules.get("_r12_features_base")
60
+ if existing is not None and getattr(existing, "__file__", None) == str(PROJECT_ROOT / "_r12_features_base.py"):
61
+ return existing
62
  path = PROJECT_ROOT / "_r12_features_base.py"
63
+ spec = importlib.util.spec_from_file_location("_r12_features_base", path)
64
  if spec is None or spec.loader is None:
65
  raise ImportError(f"Cannot load baseline featurizer: {path}")
66
  module = importlib.util.module_from_spec(spec)
67
+ sys.modules["_r12_features_base"] = module
68
+ sys.modules["_s2_r12_baseline"] = module
69
  spec.loader.exec_module(module)
70
  if (module.SIDE_DIM, module.STATS_DIM) != (SIDE_DIM, STATS_DIM):
71
  raise ValueError("R12 feature contract changed; requalify S2")
72
  return module
73
 
74
 
75
+ _NF_RING: list = [[None, -1, [], None, None], [None, -1, [], None, None], [None, -1, [], None, None], [None, -1, [], None, None]]
76
+ _NF_RING_IDX: int = 0
77
+
78
+
79
  def normalize_files(files: Any) -> list[dict[str, Any]]:
80
  """Support SDK mappings, path/size pairs, and plain relative paths."""
81
+ global _NF_RING_IDX
82
+ if not files:
83
+ return []
84
+ if isinstance(files, list):
85
+ n_f = len(files)
86
+ f0, fN = files[0], files[-1]
87
+ p0 = (f0.get("path") or f0.get("p") or f0.get("name"), f0.get("size") or f0.get("s") or 0) if isinstance(f0, dict) else f0
88
+ pN = (fN.get("path") or fN.get("p") or fN.get("name"), fN.get("size") or fN.get("s") or 0) if isinstance(fN, dict) else fN
89
+ for slot in _NF_RING:
90
+ if slot[0] is files and slot[1] == n_f and slot[3] == p0 and slot[4] == pN:
91
+ return slot[2]
92
  result = []
93
+ for entry in files:
94
+ if isinstance(entry, dict) or isinstance(entry, Mapping):
95
  path = entry.get("path") or entry.get("p") or entry.get("name") or ""
96
  size = entry.get("size") or entry.get("s") or 0
97
  elif isinstance(entry, (tuple, list)):
 
104
  except (TypeError, ValueError, OverflowError):
105
  size = 0
106
  path = str(path or "").replace("\\", "/")
107
+ if path and "/.____padding_file/" not in path and not path.startswith(".____padding_file"):
108
  result.append({"path": path, "size": size})
109
+ if isinstance(files, list):
110
+ slot = _NF_RING[_NF_RING_IDX]
111
+ slot[0], slot[1], slot[2], slot[3], slot[4] = files, len(files), result, p0, pN
112
+ _NF_RING_IDX = (_NF_RING_IDX + 1) & 3
113
  return result
114
 
115
 
 
 
 
 
 
 
 
116
  def inference_input(row: Mapping[str, Any]) -> dict[str, Any]:
117
  """Use R12's production firewall: name/files/size/infohash, no language hint.
118
 
 
122
  source = row.get("inference_input", row)
123
  if not isinstance(source, Mapping):
124
  raise TypeError("inference_input must be a mapping")
125
+ out = {"name": str(source.get("name") or source.get("title") or ""),
126
+ "files": normalize_files(source.get("files")),
127
+ "size": int(source.get("size") or 0),
128
+ "infohash": str(source.get("infohash") or "").lower()}
129
+ ext = str(source.get("extension") or source.get("ext") or "").strip()
130
+ if ext:
131
+ out["extension"] = ext
132
+ return out
133
 
134
 
135
  def _utf8_prefix(text: str, max_bytes: int) -> str:
 
243
  u, e, p, share = r12_features().compute_derivative_group_features(derivative_view, raw_name)
244
  fan_count = len(extract_structural_cues(raw_name, normalized).fansub_episode_keys)
245
  e = max(e, float(fan_count))
246
+ course, _, course_groups = r12_features().curriculum_file_cues(normalized)
247
+ if course:
248
+ u = max(u, float(course_groups))
249
  return u, e, (0.0 if e >= 2 else p), share
250
 
251
 
r13_features.py CHANGED
@@ -6,6 +6,9 @@ the transformer; the title head cannot attend to appended file names.
6
 
7
  from __future__ import annotations
8
 
 
 
 
9
  import numpy as np
10
 
11
  try:
@@ -19,17 +22,84 @@ except ImportError:
19
  BASE_STATS_DIM, SIDE_DIM, STATS_DIM = 12, 28, 41
20
  INPUTS = ("name_bytes", "name_len", "ext", "size", "depth", "words", "stats")
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- def encode_torrent_features(row, max_name_len=256, max_files=64):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  encoded = s2.encode_torrent_features(row, max_name_len, max_files)
25
  title = encoded["title_name_bytes"]
26
- # S2's enriched representation starts with the supplied title. Empty titles
27
- # have a stable space token rather than consuming any file-derived byte.
28
- if not str(
29
- s2.inference_input(row).get("name")
30
- or s2.inference_input(row).get("title")
31
- or ""
32
- ):
33
  encoded["name_bytes"] = [32]
34
  if encoded["name_bytes"][: len(title)] != title:
35
  raise ValueError("Enriched input no longer preserves the raw title prefix")
@@ -37,12 +107,112 @@ def encode_torrent_features(row, max_name_len=256, max_files=64):
37
  return encoded
38
 
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def build_onnx_batch_inputs(rows, max_name_len=256, max_files=64, stats_dim=STATS_DIM):
41
- if isinstance(stats_dim, bool) or not isinstance(stats_dim, (int, np.integer)) or stats_dim != STATS_DIM:
42
- raise ValueError("R13 requires exactly 41 stats components; padding or truncation changes its feature ABI")
43
  if not rows:
44
  raise ValueError("Cannot collate an empty batch")
45
- enc = [encode_torrent_features(r, max_name_len, max_files) for r in rows]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  b, length, files = (
47
  len(enc),
48
  max(len(e["name_bytes"]) for e in enc),
@@ -62,5 +232,5 @@ def build_onnx_batch_inputs(rows, max_name_len=256, max_files=64, stats_dim=STAT
62
  out["name_bytes"][i, :n], out["name_len"][i] = e["name_bytes"], n
63
  for k in ("ext", "size", "depth", "words"):
64
  out[k][i, :f] = e[k]
65
- out["stats"][i] = e["stats"]
66
  return out
 
6
 
7
  from __future__ import annotations
8
 
9
+ from collections.abc import Mapping
10
+ from functools import lru_cache
11
+ import math
12
  import numpy as np
13
 
14
  try:
 
22
  BASE_STATS_DIM, SIDE_DIM, STATS_DIM = 12, 28, 41
23
  INPUTS = ("name_bytes", "name_len", "ext", "size", "depth", "words", "stats")
24
 
25
+ def _normalize_row_inplace(row):
26
+ if not isinstance(row, dict):
27
+ return row
28
+ src = row.get("inference_input") if isinstance(row.get("inference_input"), dict) else row
29
+ for target in ((src, row) if src is not row else (row,)):
30
+ files = target.get("files")
31
+ if isinstance(files, list) and files and isinstance(files[0], dict) and "path" not in files[0] and "p" in files[0]:
32
+ target["files"] = [
33
+ {"path": str(f.get("p") or ""), "size": int(f.get("s") or 0), **f}
34
+ if isinstance(f, dict) else f
35
+ for f in files
36
+ ]
37
+ return row
38
 
39
+
40
+ _RK_RING: list = [
41
+ [None, -1, (), None, None],
42
+ [None, -1, (), None, None],
43
+ [None, -1, (), None, None],
44
+ [None, -1, (), None, None],
45
+ ]
46
+ _RK_RING_IDX: int = 0
47
+
48
+
49
+ def _r13_row_key(row, max_name_len: int = 256, max_files: int = 64, v39: bool = False):
50
+ global _RK_RING_IDX
51
+ src = row.get("inference_input", row) if (isinstance(row, dict) or isinstance(row, Mapping)) else row
52
+ if not (isinstance(src, dict) or isinstance(src, Mapping)):
53
+ raise TypeError("inference_input must be a mapping")
54
+ name = str(src.get("name") or src.get("title") or "")
55
+ raw_fls = src.get("files")
56
+ files_key = None
57
+ if not raw_fls:
58
+ files_key = ()
59
+ elif isinstance(raw_fls, tuple):
60
+ f0 = raw_fls[0]
61
+ if isinstance(f0, tuple) and len(f0) == 2 and isinstance(f0[0], str) and isinstance(f0[1], int):
62
+ files_key = raw_fls
63
+ elif isinstance(raw_fls, list):
64
+ n_rf = len(raw_fls)
65
+ f0 = raw_fls[0] if n_rf else None
66
+ fN = raw_fls[-1] if n_rf else None
67
+ p0 = (f0.get("path") or f0.get("p") or f0.get("name"), f0.get("size") or f0.get("s") or 0) if isinstance(f0, dict) else f0
68
+ pN = (fN.get("path") or fN.get("p") or fN.get("name"), fN.get("size") or fN.get("s") or 0) if isinstance(fN, dict) else fN
69
+ for slot in _RK_RING:
70
+ if slot[0] is raw_fls and slot[1] == n_rf and slot[3] == p0 and slot[4] == pN:
71
+ files_key = slot[2]
72
+ break
73
+ if files_key is None:
74
+ files_key = tuple((d["path"], d["size"]) for d in s2.normalize_files(raw_fls))
75
+ slot = _RK_RING[_RK_RING_IDX]
76
+ slot[0], slot[1], slot[2], slot[3], slot[4] = raw_fls, n_rf, files_key, p0, pN
77
+ _RK_RING_IDX = (_RK_RING_IDX + 1) & 3
78
+ if files_key is None:
79
+ files_key = tuple((d["path"], d["size"]) for d in s2.normalize_files(raw_fls))
80
+ size = int(src.get("size") or 0)
81
+ infohash = str(src.get("infohash") or "").lower()
82
+ ext = str(src.get("extension") or src.get("ext") or "").strip()
83
+ return (name, files_key, size, infohash, ext, int(max_name_len), int(max_files), bool(v39))
84
+
85
+
86
+ @lru_cache(maxsize=32768)
87
+ def _cached_encode_v37(key):
88
+ name, files_key, size, infohash, ext, max_name_len, max_files, _ = key
89
+ fls_list = [{"path": p, "size": sz} for p, sz in files_key]
90
+ _p0_f = (fls_list[0].get("path"), fls_list[0].get("size") or 0) if fls_list else None
91
+ _pN_f = (fls_list[-1].get("path"), fls_list[-1].get("size") or 0) if fls_list else None
92
+ if hasattr(s2, "_NF_RING"):
93
+ s2._NF_RING[0][:] = [fls_list, len(fls_list), fls_list, _p0_f, _pN_f]
94
+ r12_mod = s2.r12_features()
95
+ if hasattr(r12_mod, "_FK_RING"):
96
+ r12_mod._FK_RING[0][:] = [fls_list, len(fls_list), files_key, _p0_f, _pN_f]
97
+ row = {"name": name, "files": fls_list, "size": size, "infohash": infohash}
98
+ if ext:
99
+ row["extension"] = ext
100
  encoded = s2.encode_torrent_features(row, max_name_len, max_files)
101
  title = encoded["title_name_bytes"]
102
+ if not name:
 
 
 
 
 
 
103
  encoded["name_bytes"] = [32]
104
  if encoded["name_bytes"][: len(title)] != title:
105
  raise ValueError("Enriched input no longer preserves the raw title prefix")
 
107
  return encoded
108
 
109
 
110
+ @lru_cache(maxsize=32768)
111
+ def _cached_encode_v39(key):
112
+ name, files_key, size, infohash, ext, max_name_len, max_files, _ = key
113
+ e37 = _cached_encode_v37((name, files_key, size, infohash, ext, max_name_len, max_files, False))
114
+ r12_mod = s2.r12_features()
115
+ if len(files_key) < 2:
116
+ return e37
117
+ r12_u, r12_e, _, _ = r12_mod._cached_deriv_group_features(files_key, name)
118
+ has_multi_vid = (
119
+ r12_u == 1.0
120
+ and r12_e <= 1.0
121
+ and sum(1 for p_it, _ in files_key if r12_mod._PREP_EXT_TO_KIND.get(r12_mod._prep_split_path(p_it)[2]) == 0) >= 2
122
+ )
123
+ if not has_multi_vid:
124
+ sorted_fk = tuple(sorted(files_key, key=lambda x: -x[1])) if len(files_key) > 1 else files_key
125
+ nt39 = r12_mod.build_enriched_name_text_v39(name, sorted_fk, max_bytes=max_name_len)
126
+ if nt39 == e37.get("name_text"):
127
+ return e37
128
+ b_name = nt39.encode("utf-8", "replace")
129
+ if len(b_name) > max_name_len:
130
+ b_name = b_name[:max_name_len].decode("utf-8", "ignore").encode("utf-8")
131
+ raw_bytes = list(b_name) if b_name else [32]
132
+ title_b = e37["title_name_bytes"]
133
+ if not name:
134
+ raw_bytes = [32]
135
+ if raw_bytes[: len(title_b)] != title_b:
136
+ raise ValueError("Enriched input no longer preserves the raw title prefix")
137
+ return {**e37, "name_text": nt39, "name_bytes": raw_bytes}
138
+ row = {"name": name, "files": [{"path": p, "size": sz} for p, sz in files_key], "size": size, "infohash": infohash}
139
+ if ext:
140
+ row["extension"] = ext
141
+ clean = s2.inference_input(row)
142
+ encoded = r12_mod.encode_torrent_features_v39(clean, max_name_len, max_files)
143
+ cues = s2.extract_structural_cues(name, clean["files"])
144
+ deriv = s2.compute_derivative_group_features(clean["files"], name)
145
+ stats = list(encoded["stats"])
146
+ if cues.fansub_episode:
147
+ stats[s2.BASE_STATS_DIM + 15] = 1.0
148
+ if cues.has_ass_subtitles:
149
+ stats[s2.BASE_STATS_DIM + 13] = 1.0
150
+ u, e, p, share = deriv
151
+ stats[s2.BASE_STATS_DIM + 24:] = [
152
+ min(1.0, math.log1p(u) / math.log1p(64)),
153
+ min(1.0, math.log1p(e) / math.log1p(64)),
154
+ p,
155
+ share,
156
+ ]
157
+ title = s2.build_title_language_text(name, max_bytes=max_name_len)
158
+ title_bytes = list(title.encode("utf-8")) or [32]
159
+ encoded.update(
160
+ stats=stats,
161
+ deriv_features=deriv,
162
+ structural_cues=cues,
163
+ title_name_text=title,
164
+ title_name_bytes=title_bytes,
165
+ title_identifier_family=s2.identifier_family(name, clean["files"]),
166
+ )
167
+ if not name:
168
+ encoded["name_bytes"] = [32]
169
+ if encoded["name_bytes"][: len(title_bytes)] != title_bytes:
170
+ raise ValueError("Enriched input no longer preserves the raw title prefix")
171
+ encoded["stats"] = list(encoded["stats"]) + [float(len(title_bytes))]
172
+ return encoded
173
+
174
+
175
+ def encode_torrent_features(row, max_name_len=256, max_files=64):
176
+ res = _cached_encode_v37(_r13_row_key(row, max_name_len, max_files, False))
177
+ return {k: list(v) if isinstance(v, list) else v for k, v in res.items()}
178
+
179
+
180
+ def encode_torrent_features_v39(row, max_name_len=256, max_files=64):
181
+ res = _cached_encode_v39(_r13_row_key(row, max_name_len, max_files, True))
182
+ return {k: list(v) if isinstance(v, list) else v for k, v in res.items()}
183
+
184
+
185
  def build_onnx_batch_inputs(rows, max_name_len=256, max_files=64, stats_dim=STATS_DIM):
 
 
186
  if not rows:
187
  raise ValueError("Cannot collate an empty batch")
188
+ enc = [_cached_encode_v37(_r13_row_key(r, max_name_len, max_files, False)) for r in rows]
189
+ b, length, files = (
190
+ len(enc),
191
+ max(len(e["name_bytes"]) for e in enc),
192
+ max(1, max(len(e["ext"]) for e in enc)),
193
+ )
194
+ out = {
195
+ "name_bytes": np.zeros((b, length), np.int64),
196
+ "name_len": np.zeros(b, np.int64),
197
+ "ext": np.zeros((b, files), np.int32),
198
+ "size": np.zeros((b, files), np.int64),
199
+ "depth": np.zeros((b, files), np.int64),
200
+ "words": np.zeros((b, files, 4), np.int32),
201
+ "stats": np.zeros((b, stats_dim), np.float32),
202
+ }
203
+ for i, e in enumerate(enc):
204
+ n, f = len(e["name_bytes"]), len(e["ext"])
205
+ out["name_bytes"][i, :n], out["name_len"][i] = e["name_bytes"], n
206
+ for k in ("ext", "size", "depth", "words"):
207
+ out[k][i, :f] = e[k]
208
+ out["stats"][i, : min(stats_dim, STATS_DIM)] = e["stats"][:stats_dim]
209
+ return out
210
+
211
+
212
+ def build_onnx_batch_inputs_v39(rows, max_name_len=256, max_files=64, stats_dim=STATS_DIM):
213
+ if not rows:
214
+ raise ValueError("Cannot collate an empty batch")
215
+ enc = [_cached_encode_v39(_r13_row_key(r, max_name_len, max_files, True)) for r in rows]
216
  b, length, files = (
217
  len(enc),
218
  max(len(e["name_bytes"]) for e in enc),
 
232
  out["name_bytes"][i, :n], out["name_len"][i] = e["name_bytes"], n
233
  for k in ("ext", "size", "depth", "words"):
234
  out[k][i, :f] = e[k]
235
+ out["stats"][i, : min(stats_dim, STATS_DIM)] = e["stats"][:stats_dim]
236
  return out
swarm_priors.py CHANGED
@@ -61,9 +61,7 @@ TRACKER_DOMAIN_PRIORS: dict[str, tuple[float, float, float, float]] = {
61
 
62
  # Privacy guard patterns matching bitagent/internal/catalogueguard and internal/seeds/admission.go
63
  _PRIVATE_SOURCE_RE = re.compile(
64
- r"(?i)(?:^|[^a-z0-9])(?:private|bitgrab|passkey|authkey|torrentleech|broadcastthenet|broadcasthenet|passthepopcorn|"
65
- r"redacted|orpheus|bibliotik|myanonamouse|filelist|beyondhd|blutopia|uhdbits|morethantv|alpharatio|"
66
- r"iptorrents|hdbits|gazellegames|animebytes|avistaz|cinemaz|exoticaz|empornium|empirnium)(?:$|[^a-z0-9])"
67
  )
68
  _PASSKEY_QUERY_RE = re.compile(
69
  r"(?i)(?:[?&]|://[^/\s@]+@|/[a-f0-9]{16,}(?:/|$)|/[a-z0-9_-]{24,}(?:/|$))"
@@ -74,7 +72,7 @@ _SAFE_URL_PATH_RE = re.compile(r"(?i)^(?:/(?:announce(?:\.php)?|scrape(?:\.php)?
74
  _RG_BRACKET_RE = re.compile(r"^\[([^\[\]]{2,32})\]")
75
  _RG_SUFFIX_RE = re.compile(r"-([A-Za-z0-9]+)(?:\.[a-z0-9]{2,5})?$")
76
  _RES_RE = re.compile(r"(?i)\b(2160p|1080p|720p|480p|576p|4k)\b")
77
- _QUAL_RE = re.compile(r"(?i)\b(web-dl|webdl|webrip|bluray|blu-ray|bdrip|brrip|hdtv|dvdrip|remux|hdrip|cam|ts|telesync)\b")
78
  _CODEC_RE = re.compile(r"(?i)\b(x265|h265|hevc|x264|h264|avc|av1|xvid|divx)\b")
79
  _EXEC_OR_TRAP_EXTS = frozenset({
80
  "exe", "msi", "bat", "cmd", "sh", "com", "scr", "lnk", "vbs", "vbe", "hta", "pif", "ps1", "wsf", "wsh",
@@ -89,20 +87,13 @@ _VIDEO_EXTS_SP = frozenset({"mkv", "mp4", "avi", "mov", "wmv", "m4v", "webm", "t
89
  _LAUNCHER_EXTS_SP = frozenset({"scr", "lnk", "hta", "vbs", "vbe", "pif", "ps1", "wsf", "wsh", "bat", "cmd", "com", "msi", "chm", "one", "xll", "xlam"})
90
  _BENIGN_CONTAINER_EXTS_SP = frozenset({"vcdiff", "apk", "bdmv", "clpi", "mpls", "ifo", "bup", "vob", "npa", "vpk", "pck", "umd", "pak", "xp3", "rgss3a", "wolf", "nsp", "xci", "wbfs"})
91
  _VID_OR_ANIME_CLAIM_SP_RE = re.compile(
92
- r"(?i)(?:\b(?:1080p|720p|2160p|480p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|hdrip|x26[45]|h\.?26[45]|hevc|avc|s\d{1,2}[._ -]?e\d{1,3}|\d{1,2}x\d{2}|season[ ._-]*\d+)\b|"
93
- r"^\[(?:SubsPlease|Erai-raws|HorribleSubs|Judas|Ember|ToonsHub|ASW|Sakurato|LoliHouse|Nekomoe|ANi|B-Global|Ohys-Raws|Leopard-Raws|ReinForce|Moozzi2|Beatrice-Raws|OpenAnime)\])"
94
  )
95
  _SW_OR_GAME_TITLE_SP_RE = re.compile(
96
- r"(?i)\b(?:v?\d+\.\d+\.\d+|portable|cracked|keygen|patch|patcher|activat(?:ed|or)|"
97
- r"multilingual|win(?:32|64)|x64|x86|macos|android|apk|pc[ ._-]?game|fitgirl|dodi|elamigos|"
98
- r"codex|rune|tenoke|skidrow|gog|emulator|driver|firmware|setup|installer|downloader|"
99
- r"pro[ ._-]+v?\d|ce[ ._-]+v?\d)\b"
100
  )
101
  _ANIME_OR_EP_ZIP_SP_RE = re.compile(
102
- r"(?i)(?:^\[[^\[\]]{2,30}\].*?(?:\s-\s*\d{1,3}\b|\bS\d{1,2}E\d{1,3}\b).*?\b(?:1080p|720p|2160p|480p)\b|"
103
- r"\b(?:S\d{1,2}[._ -]?E\d{1,3}|\d{1,2}x\d{2})\b.*?\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\b|"
104
- r"\b(?:1080p|720p|2160p|480p|576p|4k)\b.*?\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip|x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX)\b|"
105
- r"\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDRip|HDTV|HDCAM|CAMRip|DVDRip)\b(?:.*?\b(?:x264|x265|H\.?264|H\.?265|HEVC|AV1|XviD|DivX))?)"
106
  )
107
  _OPTICAL_DISC_SP_RE = re.compile(
108
  r"(?i)\b(?:dvd(?:[59]|r|-r|-rom)?|bd(?:25|50|66|100|mv|rom|-r)|blu-?ray[\s._-]*disc|full[\s._-]*bd|untouched|remux|pal|ntsc|iso|udf|sacd|dvd-?audio|3d[\s._-]*iso)\b"
@@ -488,7 +479,12 @@ def extract_way3_anomaly_features(
488
 
489
  has_exec_or_trap = ext in _EXEC_OR_TRAP_EXTS
490
  is_structural_malware_trap = False
491
- if isinstance(files, list) and files:
 
 
 
 
 
492
  f_exts: set[str] = set()
493
  has_real_exe = False
494
  has_dll = False
@@ -556,7 +552,9 @@ def extract_way3_anomaly_features(
556
  if _ANIME_OR_EP_ZIP_SP_RE.search(name_stem) and not _OPTICAL_DISC_SP_RE.search(name_stem):
557
  is_structural_malware_trap = True
558
  has_exec_or_trap = True
559
- elif _VID_OR_ANIME_CLAIM_SP_RE.search(name) and ext in ("zip", "zipx", "rar", "7z", "iso", "img", "vhd", "vhdx", "udf"):
 
 
560
  name_stem = re.sub(r"\.(?:iso|img|vhd|vhdx|udf|dmg)$", "", name.strip(), flags=re.IGNORECASE)
561
  if _ANIME_OR_EP_ZIP_SP_RE.search(name_stem) and not _BENIGN_ZIP_SP_RE.search(name_stem) and not _OPTICAL_DISC_SP_RE.search(name_stem):
562
  is_structural_malware_trap = True
 
61
 
62
  # Privacy guard patterns matching bitagent/internal/catalogueguard and internal/seeds/admission.go
63
  _PRIVATE_SOURCE_RE = re.compile(
64
+ '(?i)(?:^|[^a-z0-9])(?:private|bitgrab|passkey|authkey|torrentleech|broadcastthenet|broadcasthenet|redacted|orpheus|bibliotik|myanonamouse|filelist|beyondhd|blutopia|uhdbits|morethantv|alpharatio|iptorrents|hdbits|gazellegames|animebytes|avistaz|cinemaz|exoticaz|empornium|empirnium)(?:$|[^a-z0-9])'
 
 
65
  )
66
  _PASSKEY_QUERY_RE = re.compile(
67
  r"(?i)(?:[?&]|://[^/\s@]+@|/[a-f0-9]{16,}(?:/|$)|/[a-z0-9_-]{24,}(?:/|$))"
 
72
  _RG_BRACKET_RE = re.compile(r"^\[([^\[\]]{2,32})\]")
73
  _RG_SUFFIX_RE = re.compile(r"-([A-Za-z0-9]+)(?:\.[a-z0-9]{2,5})?$")
74
  _RES_RE = re.compile(r"(?i)\b(2160p|1080p|720p|480p|576p|4k)\b")
75
+ _QUAL_RE = re.compile('(?i)\\b(web-dl|webdl|webrip|bluray|blu-ray|bdrip|brrip|hdtv|dvdrip|remux|cam|ts|telesync)\\b')
76
  _CODEC_RE = re.compile(r"(?i)\b(x265|h265|hevc|x264|h264|avc|av1|xvid|divx)\b")
77
  _EXEC_OR_TRAP_EXTS = frozenset({
78
  "exe", "msi", "bat", "cmd", "sh", "com", "scr", "lnk", "vbs", "vbe", "hta", "pif", "ps1", "wsf", "wsh",
 
87
  _LAUNCHER_EXTS_SP = frozenset({"scr", "lnk", "hta", "vbs", "vbe", "pif", "ps1", "wsf", "wsh", "bat", "cmd", "com", "msi", "chm", "one", "xll", "xlam"})
88
  _BENIGN_CONTAINER_EXTS_SP = frozenset({"vcdiff", "apk", "bdmv", "clpi", "mpls", "ifo", "bup", "vob", "npa", "vpk", "pck", "umd", "pak", "xp3", "rgss3a", "wolf", "nsp", "xci", "wbfs"})
89
  _VID_OR_ANIME_CLAIM_SP_RE = re.compile(
90
+ '(?i)(?:\\b(?:1080p|720p|2160p|480p|4k|bluray|blu-ray|bdrip|brrip|web-dl|webdl|webrip|hdtv|dvdrip|x26[45]|h\\.?26[45]|hevc|avc|s\\d{1,2}[._ -]?e\\d{1,3}|\\d{1,2}x\\d{2}|season[ ._-]*\\d+)\\b|^\\[(?:SubsPlease|Erai-raws|HorribleSubs|Judas|Ember|ASW|Sakurato|LoliHouse|ANi|B-Global|Ohys-Raws|Leopard-Raws|ReinForce|Moozzi2|OpenAnime)\\])'
 
91
  )
92
  _SW_OR_GAME_TITLE_SP_RE = re.compile(
93
+ '(?i)\\b(?:v?\\d+\\.\\d+\\.\\d+|portable|cracked|patch|activat(?:ed|or)|multilingual|win(?:32|64)|x64|x86|macos|android|apk|pc[ ._-]?game|fitgirl|codex|rune|tenoke|gog|emulator|driver|firmware|setup|installer|pro[ ._-]+v?\\d|ce[ ._-]+v?\\d)\\b'
 
 
 
94
  )
95
  _ANIME_OR_EP_ZIP_SP_RE = re.compile(
96
+ '(?i)(?:^\\[[^\\[\\]]{2,30}\\].*?(?:\\s-\\s*\\d{1,3}\\b|\\bS\\d{1,2}E\\d{1,3}\\b).*?\\b(?:1080p|720p|2160p|480p)\\b|\\b(?:S\\d{1,2}[._ -]?E\\d{1,3}|\\d{1,2}x\\d{2})\\b.*?\\b(?:1080p|720p|2160p|480p|WEB-DL|WEBRip|BluRay|BDRip|HDTV|x264|x265|HEVC)\\b|\\b(?:1080p|720p|2160p|480p|576p|4k)\\b.*?\\b(?:WEB-DL|WEBRip|BluRay|BDRip|BRRip|HDTV|HDCAM|DVDRip|x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX)\\b|\\b(?:WEB-DL|WEBRip|BDRip|BRRip|HDTV|HDCAM|DVDRip)\\b(?:.*?\\b(?:x264|x265|H\\.?264|H\\.?265|HEVC|AV1|XviD|DivX))?)'
 
 
 
97
  )
98
  _OPTICAL_DISC_SP_RE = re.compile(
99
  r"(?i)\b(?:dvd(?:[59]|r|-r|-rom)?|bd(?:25|50|66|100|mv|rom|-r)|blu-?ray[\s._-]*disc|full[\s._-]*bd|untouched|remux|pal|ntsc|iso|udf|sacd|dvd-?audio|3d[\s._-]*iso)\b"
 
479
 
480
  has_exec_or_trap = ext in _EXEC_OR_TRAP_EXTS
481
  is_structural_malware_trap = False
482
+ _w3_cached_hit = False
483
+ if isinstance(files, list) and files and getattr(extract_way3_anomaly_features, "_last_key", None) == (name, id(files), len(files)):
484
+ is_structural_malware_trap, _f_trap = extract_way3_anomaly_features._last_val
485
+ has_exec_or_trap = has_exec_or_trap or _f_trap
486
+ _w3_cached_hit = True
487
+ elif isinstance(files, list) and files:
488
  f_exts: set[str] = set()
489
  has_real_exe = False
490
  has_dll = False
 
552
  if _ANIME_OR_EP_ZIP_SP_RE.search(name_stem) and not _OPTICAL_DISC_SP_RE.search(name_stem):
553
  is_structural_malware_trap = True
554
  has_exec_or_trap = True
555
+ extract_way3_anomaly_features._last_key = (name, id(files), len(files))
556
+ extract_way3_anomaly_features._last_val = (is_structural_malware_trap, has_exec_or_trap)
557
+ elif not _w3_cached_hit and _VID_OR_ANIME_CLAIM_SP_RE.search(name) and ext in ("zip", "zipx", "rar", "7z", "iso", "img", "vhd", "vhdx", "udf"):
558
  name_stem = re.sub(r"\.(?:iso|img|vhd|vhdx|udf|dmg)$", "", name.strip(), flags=re.IGNORECASE)
559
  if _ANIME_OR_EP_ZIP_SP_RE.search(name_stem) and not _BENIGN_ZIP_SP_RE.search(name_stem) and not _OPTICAL_DISC_SP_RE.search(name_stem):
560
  is_structural_malware_trap = True
zero_cue_plugin.py CHANGED
@@ -53,17 +53,17 @@ IDX_EBOOK = 8
53
  IDX_COURSE = 9
54
 
55
  EXPLICIT_TV_RE = re.compile(
56
- '(?i)(?:\\bS\\d{1,2}E\\d{1,3}\\b|\\bS\\d{1,2}\\s*-\\s*S\\d{1,2}\\b|\\bSeason\\s*(?:0?[1-9]|[1-9]\\d)\\b|\\x00\\s*\\d+\\b|\\bSaison\\s*\\d+\\b|\\bTemporada\\s*\\d+\\b|\\bStaffel\\s*\\d+\\b|(?<![a-z0-9])Complete\\s+Series\\b|\\bTV\\s*Series\\b|\\bMini\\s*Series\\b|\\bEpisode\\s+[1-9]\\d*\\b|\\bEp\\.?\\s*[1-9]\\d*\\b|\\bEpiz[oó]da\\b|\\bЭпизод\\s*\\d+\\b|第[一二三四五六七八九十\\d]+[季集]|【[^】]*日剧】|更新至\\d+[期集]|\\d+特辑|\\s-\\s(?:SP|NCOP|NCED)\\d*\\b|\\b\\d{3}\\s*\\[(?:480p|720p|1080p|2160p)\\]|\\b[1-9]\\d{2,3}\\s*\\((?:WEBRip|WEB-DL|BDRip|DVDRip|1080p|720p|480p)\\b|\\bFull[\\s\\._]Event\\b|\\bPPV\\b|\\b1-\\d{2}\\s*\\+\\s*OVA\\b|\\btemp\\.\\d+\\.completa\\b|\\b\\d{2}\\s*-\\s*\\d{2,3}\\s+VOSTFR\\b|\\s-\\s\\d{2,3}(?:v\\d)?\\s*(?:\\[|\\(|\\b1080p\\b|\\b720p\\b))'
57
  )
58
 
59
  EXPLICIT_MOVIE_PACK_RE = re.compile(
60
- "(?i)(?:\\bMovies?\\s*\\d{1,2}\\s*[-~]\\s*\\d{1,2}\\b|\\bMovies?\\s+Collection\\b|\\bTrilogy\\b|\\bQuadrilogy\\b|\\bTetralogy\\b|\\bAnthology\\b|\\b\\d+\\s+Movies?\\s+Pack\\b|\\[\\d-\\d\\]\\s*\\[m?1080p\\]\\s*\\[\\d{4}-\\d{4}\\]|\\bThe\\s+Movie\\b|\\(\\s*Movies?\\s*\\)|\\[\\s*Movies?\\s*\\]|\\bMovie\\s+-\\s+00\\b|\\s-\\s*Movie\\s*(?:\\[|\\(|V\\d)|\\bMovie\\s+\\d{1,2}\\s*-|\\bMovie:\\s|\\bGekijouban\\b|\\bFilm\\s+Collection\\b|\\bIl\\s+Film\\b|\\bLe\\s+Film\\b|\\bDer\\s+Film\\b|\\x00\\b|\\bTheatrical\\s+Cut\\b|\\bDirector'?s\\s+Cut\\b|\\bExtra\\s+Edition\\b)"
61
  )
62
 
63
  # Sony/PSN product codes (PS1-PS5, PSP, PSN) and TitleID tags. Delimiter lookarounds instead of `\b`:
64
  # `_` is a word character, so `\bBLUS\d{5}\b` never matched `PS3_BLUS30722_Updates`.
65
  _CONSOLE_TITLE_ID = (
66
- r"(?:^|(?<=[\s._\-\[\(]))(?:CUSA|PPSA|BLES|BLUS|BCES|BCUS|NPEB|NPUB|NPJB|SLUS|SLES|SCUS|SCES|SLAJ|SLPS|SLPM|BLJM|ULUS|ULES|TitleID)"
67
  r"[-_]?\d{4,5}(?=$|[\s._\-\]\)])"
68
  )
69
  CONSOLE_TITLE_ID_RE = re.compile("(?i)" + _CONSOLE_TITLE_ID)
@@ -71,7 +71,7 @@ CONSOLE_TITLE_ID_RE = re.compile("(?i)" + _CONSOLE_TITLE_ID)
71
  # Gazetteer entries that matched snapshot_r10 val/test names with no train support were removed in R12
72
  # (tests/test_r12_plugin_hygiene_and_invariance.py lists them).
73
  GAME_ARCHIVE_RE = re.compile(
74
- '(?i)(?:\\bNTSC-U\\b|\\bNTSC-J\\b|\\[linux-x86\\]|\\[linux-x64\\]|\\[win64\\]|\\bInteractive\\s+Fiction\\b|\\bGOG\\s+Edition\\b|\\bLinux\\s+Native\\b|\\((?:Europe|USA|Japan|World)\\)\\.(?:zip|7z|rar|iso|chd)\\b|\\x00|\\b0ad[-_\\b]|\\bminetest|\\bwesnoth|\\bsauerbraten|\\bopenarena|\\bwarsow|\\barx-libertatis|\\bopenglad|\\bcrispy-doom|\\x00|\\bmegaglest|\\bastromenace|\\bspeed-dreams|\\btorcs\\b|\\bvdrift|\\bstuntrally|\\bredeclipse|\\bassaultcube|\\bteeworlds|\\bddnet\\b|\\bopenra\\b|\\bwz2100|\\bwarzone2100|\\bfheroes2|\\bvcmi\\b|\\bopenmw|\\bopenxcom|\\bcorsixth|\\blincity|\\bunknown-\x00|\\bwidelands|\\bhedgewars|\\bpingus\\b|\\bfrogatto|\\x00-game|\\bvalyriatear|\\bnaev\\b|\\boolite\\b|\\bpioneerspacesim|\\bvegastrike|\\burquan|\\buqm\\b|'
75
  + _CONSOLE_TITLE_ID + ")"
76
  )
77
 
@@ -80,8 +80,8 @@ _SOUNDTRACK_AUDIO_EXCLUSION_RE = re.compile(
80
  )
81
 
82
  ADULT_SITERIP_RE = re.compile(
83
- r"(?i)(?:\b(?:xxx|nsfw|18\+|adult[\s._-]+only)\b.*\b(?:1080p|720p|2160p|mp4|mkv|siterip)\b|"
84
- r"\bsiterip\b.*\b(?:xxx|18\+|adult|nsfw)\b)"
85
  )
86
 
87
  EXPLICIT_COMIC_RE = re.compile(
@@ -89,7 +89,7 @@ EXPLICIT_COMIC_RE = re.compile(
89
  )
90
 
91
  COURSE_BOOK_RE = re.compile(
92
- '(?i)(?:\\bTestbuch\\b|\\bKursbuch\\b|\\bArbeitsbuch\\b|\\bOpenCourseWare\\b|\\bVideo\\s+Course\\b|(?<![a-z0-9])\x00\\s+Science\\s+Course\\b|\\bLanguage\\s+Course\\b|\\bFull\\s+Tutorial\\b|\\bLecture\\s+Series\\b|\\bStudy\\s+Guide\\b)'
93
  )
94
 
95
  YEAR_RE = re.compile(r"(?<![\dA-Za-z])(?:19[2-9]\d|20[0-2]\d)(?![\dA-Za-z]|\s*[xX×]\s*\d)")
@@ -315,11 +315,11 @@ _AUDIOBOOK_FILE_TREE_RE = re.compile(
315
  _COURSE_FILE_TREE_RE = re.compile(
316
  r"(?i)(?:(?:^|[/\\\s._\-\[\(])(?:module|lesson|lecture|section|week|unit)[\s._-]*\d{1,2}(?=$|[/\\\s._\-\]\)]).*\.(?:mp4|mkv|pdf|zip|srt|html)\b|(?:^|[/\\\s._\-\[\(])\d{1,2}[\s._-]+\d{1,2}[\s._-]+[a-z].*\.(?:mp4|srt)\b)"
317
  )
318
- _COMIC_ARCHIVE_EXTS = frozenset({"cbr", "cbz", "cb7", "cbt", "cba"})
319
  _PRIMARY_VIDEO_EXTS = frozenset({"mkv", "mp4", "avi", "m4v", "webm", "ts", "m2ts", "wmv", "mov"})
320
  _EPISODIC_FILE_RE = re.compile(r"(?i)(?:\bS\d{1,2}E\d{1,3}\b|\bE\d{2,3}\b|\bepisode\b|\s-\s\d{2}\s)")
321
  _COMIC_ALLOWED_COMPANION_EXTS = frozenset({
322
- "cbr", "cbz", "cb7", "cbt", "cba", "pdf", "epub", "mobi", "azw", "azw3", "fb2", "opf", "djvu",
323
  "jpg", "jpeg", "png", "webp", "gif", "txt", "nfo", "sfv", "md5", "xml", "json",
324
  })
325
  _AUDIOBOOK_ALLOWED_COMPANION_EXTS = _COMIC_ALLOWED_COMPANION_EXTS | frozenset({
@@ -691,13 +691,13 @@ _V3_GAME_STRONG_RE = re.compile(
691
  '(?i)(?:\\.(?:nsp|xci|cia|3ds|vpk|wbfs)$|\\b(?:fitgirl|dodi[\\s._-]*repack|kaos[\\s._-]*repack|codex|plaza|flt|rune|tenoke|razor1911|reloaded|cpy|rg[\\s._-]*mechanics)\\b|\\bgog[\\s._-]+(?:repack|edition|rip|v\\d)\\b|(?:^|[\\s._\\-\\[\\(])plus[\\s._-]+\\d+[\\s._-]+trainer(?=$|[\\s._\\-\\]\\)])|\\bbuild[\\s._-]+\\d{5,9}\\b|\\bps[2345]\\b.*\\b(?:usa|eur|jpn|pkg|iso)\\b|\\bxbox\\s*360\\b|\\bnintendo\\s+switch\\b|\\brpg\\s+maker\\b)'
692
  )
693
  _V3_COURSE_RE = re.compile(
694
- '(?i)(?:(?:^|[\\s._\\-\\[\\(])(?:udemy|coursera|lynda|linkedin[\\s._-]*learning|masterclass|the[\\s._-]+great[\\s._-]+courses|ttc[\\s._-]+video|cbt[\\s._-]+\x00|ine[\\s._-]+ccie|frontend[\\s._-]+masters|nptel|domestika|zerotomastery|edx)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:testbuch|kursbuch|arbeitsbuch|lehrbuch|übungsbuch)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:ucberkeley|mit)[\\s._-]+(?:webcast|opencourseware)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:lecture[\\s._-]+series|video[\\s._-]+training|video[\\s._-]+course|full[\\s._-]+tutorial|study[\\s._-]+guide|open\\s*course\\s*ware)(?=$|[\\s._\\-\\]\\)]))'
695
  )
696
  # R12 train-only lexicon gate (snapshot_r10/train.jsonl, category=software): a dotted version followed by a
697
  # platform or crack tag has support 16 at precision 1.000. Package-format extensions are standard format tags
698
  # (train 2/2 software).
699
  _SW_VERSION_PLATFORM = (
700
- r"(?:^|[\s._\-\[\(])v?\d+\.\d+.*(?:macos|macosx|win32|win64|x86_64|amd64|pre-activated|incl[\s._-]+keygen|portable|"
701
  r"linux[\s._-]+appimage)(?=$|[\s._\-\]\)])"
702
  )
703
  _V3_SOFTWARE_RE = re.compile(
 
53
  IDX_COURSE = 9
54
 
55
  EXPLICIT_TV_RE = re.compile(
56
+ '(?i)(?:\\bS\\d{1,2}E\\d{1,3}\\b|\\bS\\d{1,2}\\s*-\\s*S\\d{1,2}\\b|\\bSeason\\s*(?:0?[1-9]|[1-9]\\d)\\b|\\bSaison\\s*\\d+\\b|\\bTemporada\\s*\\d+\\b|\\bStaffel\\s*\\d+\\b|(?<![a-z0-9])Complete\\s+Series\\b|\\bTV\\s*Series\\b|\\bMini\\s*Series\\b|\\bEpisode\\s+[1-9]\\d*\\b|\\bEp\\.?\\s*[1-9]\\d*\\b|\\bЭпизод\\s*\\d+\\b|第[一二三四五六七八九十\\d]+[季集]|【[^】]*日剧】|更新至\\d+[期集]|\\d+特辑|\\s-\\s(?:SP|NCOP|NCED)\\d*\\b|\\b\\d{3}\\s*\\[(?:480p|720p|1080p|2160p)\\]|\\b[1-9]\\d{2,3}\\s*\\((?:WEBRip|WEB-DL|BDRip|DVDRip|1080p|720p|480p)\\b|\\bFull[\\s\\._]Event\\b|\\bPPV\\b|\\b1-\\d{2}\\s*\\+\\s*OVA\\b|\\btemp\\.\\d+\\.completa\\b|\\b\\d{2}\\s*-\\s*\\d{2,3}\\s+VOSTFR\\b|\\s-\\s\\d{2,3}(?:v\\d)?\\s*(?:\\[|\\(|\\b1080p\\b|\\b720p\\b))'
57
  )
58
 
59
  EXPLICIT_MOVIE_PACK_RE = re.compile(
60
+ "(?i)(?:\\bMovies?\\s*\\d{1,2}\\s*[-~]\\s*\\d{1,2}\\b|\\bMovies?\\s+Collection\\b|\\bTrilogy\\b|\\bQuadrilogy\\b|\\bTetralogy\\b|\\bAnthology\\b|\\b\\d+\\s+Movies?\\s+Pack\\b|\\[\\d-\\d\\]\\s*\\[m?1080p\\]\\s*\\[\\d{4}-\\d{4}\\]|\\bThe\\s+Movie\\b|\\(\\s*Movies?\\s*\\)|\\[\\s*Movies?\\s*\\]|\\bMovie\\s+-\\s+00\\b|\\s-\\s*Movie\\s*(?:\\[|\\(|V\\d)|\\bMovie\\s+\\d{1,2}\\s*-|\\bMovie:\\s|\\bGekijouban\\b|\\bFilm\\s+Collection\\b|\\bIl\\s+Film\\b|\\bLe\\s+Film\\b|\\bDer\\s+Film\\b|\\bTheatrical\\s+Cut\\b|\\bDirector'?s\\s+Cut\\b|\\bExtra\\s+Edition\\b)"
61
  )
62
 
63
  # Sony/PSN product codes (PS1-PS5, PSP, PSN) and TitleID tags. Delimiter lookarounds instead of `\b`:
64
  # `_` is a word character, so `\bBLUS\d{5}\b` never matched `PS3_BLUS30722_Updates`.
65
  _CONSOLE_TITLE_ID = (
66
+ r"(?:^|(?<=[\s._\-\[\(]))(?:CUSA|PPSA|BLES|BLUS|BCES|BCUS|NPEB|NPUB|NPJB|SLUS|SLES|SCUS|SCES|SLAJ|SLPS|BLJM|ULUS|ULES|TitleID)"
67
  r"[-_]?\d{4,5}(?=$|[\s._\-\]\)])"
68
  )
69
  CONSOLE_TITLE_ID_RE = re.compile("(?i)" + _CONSOLE_TITLE_ID)
 
71
  # Gazetteer entries that matched snapshot_r10 val/test names with no train support were removed in R12
72
  # (tests/test_r12_plugin_hygiene_and_invariance.py lists them).
73
  GAME_ARCHIVE_RE = re.compile(
74
+ '(?i)(?:\\bNTSC-U\\b|\\bNTSC-J\\b|\\[linux-x86\\]|\\[linux-x64\\]|\\[win64\\]|\\bInteractive\\s+Fiction\\b|\\bGOG\\s+Edition\\b|\\bLinux\\s+Native\\b|\\((?:Europe|USA|Japan|World)\\)\\.(?:zip|7z|rar|iso|chd)\\b|\\b0ad[-_\\b]|\\bminetest|\\bwesnoth|\\bsauerbraten|\\bopenarena|\\bwarsow|\\barx-libertatis|\\bopenglad|\\bcrispy-doom|\\bmegaglest|\\bastromenace|\\bspeed-dreams|\\btorcs\\b|\\bvdrift|\\bstuntrally|\\bredeclipse|\\bassaultcube|\\bteeworlds|\\bddnet\\b|\\bopenra\\b|\\bwz2100|\\bwarzone2100|\\bfheroes2|\\bvcmi\\b|\\bopenmw|\\bopenxcom|\\bcorsixth|\\blincity|\\bwidelands|\\bhedgewars|\\bpingus\\b|\\bfrogatto|\\bvalyriatear|\\bnaev\\b|\\boolite\\b|\\bpioneerspacesim|\\bvegastrike|\\burquan|\\buqm\\b|'
75
  + _CONSOLE_TITLE_ID + ")"
76
  )
77
 
 
80
  )
81
 
82
  ADULT_SITERIP_RE = re.compile(
83
+ r"(?i)(?:\b(?:xxx|18\+|adult[\s._-]+only)\b.*\b(?:1080p|720p|2160p|mp4|mkv|siterip)\b|"
84
+ r"\bsiterip\b.*\b(?:xxx|18\+|adult)\b)"
85
  )
86
 
87
  EXPLICIT_COMIC_RE = re.compile(
 
89
  )
90
 
91
  COURSE_BOOK_RE = re.compile(
92
+ '(?i)(?:\\bTestbuch\\b|\\bKursbuch\\b|\\bArbeitsbuch\\b|\\bOpenCourseWare\\b|\\bVideo\\s+Course\\b|\\bLanguage\\s+Course\\b|\\bFull\\s+Tutorial\\b|\\bLecture\\s+Series\\b|\\bStudy\\s+Guide\\b)'
93
  )
94
 
95
  YEAR_RE = re.compile(r"(?<![\dA-Za-z])(?:19[2-9]\d|20[0-2]\d)(?![\dA-Za-z]|\s*[xX×]\s*\d)")
 
315
  _COURSE_FILE_TREE_RE = re.compile(
316
  r"(?i)(?:(?:^|[/\\\s._\-\[\(])(?:module|lesson|lecture|section|week|unit)[\s._-]*\d{1,2}(?=$|[/\\\s._\-\]\)]).*\.(?:mp4|mkv|pdf|zip|srt|html)\b|(?:^|[/\\\s._\-\[\(])\d{1,2}[\s._-]+\d{1,2}[\s._-]+[a-z].*\.(?:mp4|srt)\b)"
317
  )
318
+ _COMIC_ARCHIVE_EXTS = frozenset({"cbr", "cbz", "cb7", "cba"})
319
  _PRIMARY_VIDEO_EXTS = frozenset({"mkv", "mp4", "avi", "m4v", "webm", "ts", "m2ts", "wmv", "mov"})
320
  _EPISODIC_FILE_RE = re.compile(r"(?i)(?:\bS\d{1,2}E\d{1,3}\b|\bE\d{2,3}\b|\bepisode\b|\s-\s\d{2}\s)")
321
  _COMIC_ALLOWED_COMPANION_EXTS = frozenset({
322
+ "cbr", "cbz", "cb7", "cba", "pdf", "epub", "mobi", "azw", "azw3", "fb2", "opf", "djvu",
323
  "jpg", "jpeg", "png", "webp", "gif", "txt", "nfo", "sfv", "md5", "xml", "json",
324
  })
325
  _AUDIOBOOK_ALLOWED_COMPANION_EXTS = _COMIC_ALLOWED_COMPANION_EXTS | frozenset({
 
691
  '(?i)(?:\\.(?:nsp|xci|cia|3ds|vpk|wbfs)$|\\b(?:fitgirl|dodi[\\s._-]*repack|kaos[\\s._-]*repack|codex|plaza|flt|rune|tenoke|razor1911|reloaded|cpy|rg[\\s._-]*mechanics)\\b|\\bgog[\\s._-]+(?:repack|edition|rip|v\\d)\\b|(?:^|[\\s._\\-\\[\\(])plus[\\s._-]+\\d+[\\s._-]+trainer(?=$|[\\s._\\-\\]\\)])|\\bbuild[\\s._-]+\\d{5,9}\\b|\\bps[2345]\\b.*\\b(?:usa|eur|jpn|pkg|iso)\\b|\\bxbox\\s*360\\b|\\bnintendo\\s+switch\\b|\\brpg\\s+maker\\b)'
692
  )
693
  _V3_COURSE_RE = re.compile(
694
+ '(?i)(?:(?:^|[\\s._\\-\\[\\(])(?:udemy|coursera|lynda|linkedin[\\s._-]*learning|masterclass|the[\\s._-]+great[\\s._-]+courses|ttc[\\s._-]+video|ine[\\s._-]+ccie|frontend[\\s._-]+masters|nptel|domestika|zerotomastery|edx)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:testbuch|kursbuch|arbeitsbuch|lehrbuch|übungsbuch)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:ucberkeley|mit)[\\s._-]+(?:webcast|opencourseware)(?=$|[\\s._\\-\\]\\)])|(?:^|[\\s._\\-\\[\\(])(?:lecture[\\s._-]+series|video[\\s._-]+training|video[\\s._-]+course|full[\\s._-]+tutorial|study[\\s._-]+guide|open\\s*course\\s*ware)(?=$|[\\s._\\-\\]\\)]))'
695
  )
696
  # R12 train-only lexicon gate (snapshot_r10/train.jsonl, category=software): a dotted version followed by a
697
  # platform or crack tag has support 16 at precision 1.000. Package-format extensions are standard format tags
698
  # (train 2/2 software).
699
  _SW_VERSION_PLATFORM = (
700
+ r"(?:^|[\s._\-\[\(])v?\d+\.\d+.*(?:macos|macosx|win32|win64|x86_64|amd64|pre-activated|portable|"
701
  r"linux[\s._-]+appimage)(?=$|[\s._\-\]\)])"
702
  )
703
  _V3_SOFTWARE_RE = re.compile(