Token Classification
Transformers
ONNX
Safetensors
English
Japanese
Chinese
bert
anime
filename-parsing
Eval Results (legacy)
Run this model with HF Jobs
Run ModerRAS/AniFileBERT on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/ModerRAS/AniFileBERT. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ModerRAS/AniFileBERT on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use ModerRAS/AniFileBERT with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ModerRAS/AniFileBERT with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="ModerRAS/AniFileBERT")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("ModerRAS/AniFileBERT") model = AutoModelForTokenClassification.from_pretrained("ModerRAS/AniFileBERT", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Implement schema v2 anime filename labels
Browse filesFiles changed (16)
- anifilebert/config.py+8-13
- anifilebert/dataset.py+2-1
- anifilebert/inference.py+99-35
- anifilebert/label_repairs.py+11-9
- anifilebert/labels.pyAdded+205
- anifilebert/model.py+116
- anifilebert/train.py+54-9
- data/parser_regression_cases.json+21
- label_schema.jsonAdded+80
- tools/build_path_focus_dataset.py+40-12
- tools/build_path_prefix_dataset.py+110-12
- tools/build_repair_focus_dataset.py+29-18
- tools/evaluate_parser_cases.py+15-1
- tools/rust_dmhy_template_apply/src/main.rs+886-235
- tools/virtual_dataset_generator/src/bin/case_combo_generator.rs+129-50
- tools/virtual_dataset_generator/src/main.rs+477-94
3 unmodified lines4567891039 unmodified lines5051525354555657585960616263646566676869707172733 unmodified lines"""from dataclasses import dataclass, field@dataclass39 unmodified linescls_token: str = "[CLS]"sep_token: str = "[SEP]"# BIO label scheme (8 entity types + O)label2id: dict = Noneid2label: dict = Nonedef __post_init__(self):if self.label2id is None:self.label2id = {"O": 0,"B-TITLE": 1, "I-TITLE": 2,"B-SEASON": 3, "I-SEASON": 4,"B-EPISODE": 5, "I-EPISODE": 6,"B-SPECIAL": 7, "I-SPECIAL": 8,"B-GROUP": 9, "I-GROUP": 10,"B-RESOLUTION": 11, "I-RESOLUTION": 12,"B-SOURCE": 13, "I-SOURCE": 14,}if self.id2label is None:self.id2label = {v: k for k, v in self.label2id.items()}@propertydef num_labels(self) -> int:3 unmodified lines45678910111239 unmodified lines52535455565758596061626364656667683 unmodified lines"""from dataclasses import dataclassfrom .labels import LABEL_SCHEMA_VERSION, make_id2label, make_label2id@dataclass39 unmodified linescls_token: str = "[CLS]"sep_token: str = "[SEP]"# BIO label schemelabel_schema_version: int = LABEL_SCHEMA_VERSIONlabel2id: dict = Noneid2label: dict = Nonedef __post_init__(self):using_default_labels = self.label2id is Noneif self.label2id is None:self.label2id = make_label2id()if self.id2label is None:self.id2label = make_id2label() if using_default_labels else {v: k for k, v in self.label2id.items()}@propertydef num_labels(self) -> int:
13 unmodified lines14151617181913 unmodified lines3334353637383913 unmodified linesfrom .config import Configfrom .label_repairs import repair_sequel_season_labelsfrom .tokenizer import AnimeTokenizer13 unmodified linesinput_ids = [tokenizer.cls_token_id] + input_ids + [tokenizer.sep_token_id]label_ids: List[int] = [-100]label_ids.extend(label2id.get(label, 0) for label in labels)label_ids.append(-100)attention_mask = [1] * len(input_ids)13 unmodified lines1415161718192013 unmodified lines3435363738394013 unmodified linesfrom .config import Configfrom .label_repairs import repair_sequel_season_labelsfrom .labels import canonical_bio_labelfrom .tokenizer import AnimeTokenizer13 unmodified linesinput_ids = [tokenizer.cls_token_id] + input_ids + [tokenizer.sep_token_id]label_ids: List[int] = [-100]label_ids.extend(label2id.get(canonical_bio_label(str(label)), 0) for label in labels)label_ids.append(-100)attention_mask = [1] * len(input_ids)
18 unmodified lines192021222324264 unmodified lines2892902912922932945 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513526 unmodified lines35936036136236336410 unmodified lines37537637737837938025 unmodified lines40640740840941041141241341436 unmodified lines45145245345445545645745845918 unmodified linesfrom .config import Configfrom .label_repairs import season_marker_numberfrom .model import load_modelfrom .tokenizer import AnimeTokenizer, load_tokenizer264 unmodified linesreturn decodeddef postprocess(tokens: List[str],labels: List[str],5 unmodified linesMerges consecutive B- / I- tokens of the same entity type,then extracts structured fields."""result: Dict = {"title": None,"season": None,"episode": None,"group": None,"resolution": None,"source": None,"special": None,}entities = labels_to_entities(tokens, labels, tokenizer)grouped_entities: Dict[str, List[str]] = {}for entity_type, text in entities:grouped_entities.setdefault(entity_type, []).append(text)title_fragments = [cleaned for text in grouped_entities.get("TITLE", [])if (cleaned := normalize_field_text(text))]if title_fragments:result["title"] = " ".join(title_fragments)for text in grouped_entities.get("SEASON", []):season_num = extract_season_number(text)if season_num is not None:result["season"] = season_numfor text in grouped_entities.get("EPISODE", []):ep_num = extract_episode_number(text)if ep_num is not None:if result["episode"] is None:result["episode"] = ep_numfor text in grouped_entities.get("GROUP", []):group = normalize_field_text(text)if result["group"] is None:result["group"] = groupfor text in grouped_entities.get("SPECIAL", []):special = normalize_field_text(text)result["special"] = specialfor text in grouped_entities.get("RESOLUTION", []):res = extract_resolution(text)if res:result["resolution"] = resresult["source"] = choose_thin_source(grouped_entities.get("SOURCE", []))6 unmodified linesor "月番" in result["title"]):result["title"] = new_show_titlesearch_special = extract_bracketed_search_special(whole_text)if search_special is not None:10 unmodified lines"resolution": None,"source": None,"special": standalone_special,})25 unmodified lines# Tokenizetokens = tokenizer.tokenize(filename)if not tokens:return {"title": None, "season": None, "episode": None,"group": None, "resolution": None, "source": None,"special": None}# Convert to input IDsinput_ids = tokenizer.convert_tokens_to_ids(tokens)36 unmodified lines# Truncate real tokens if we had to truncateavailable = min(real_token_count, max_length - 2)if available <= 0:return {"title": None, "season": None, "episode": None,"group": None, "resolution": None, "source": None,"special": None}with torch.no_grad():logits = model(input_ids=input_tensor, attention_mask=mask_tensor).logits18 unmodified lines19202122232425264 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433445 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164176 unmodified lines42442542642742842943010 unmodified lines44144244344444544644744825 unmodified lines47447547647747847948036 unmodified lines51751851952052152252318 unmodified linesfrom .config import Configfrom .label_repairs import season_marker_numberfrom .labels import is_file_title_entity, is_path_title_entity, title_entity_priority, title_languagefrom .model import load_modelfrom .tokenizer import AnimeTokenizer, load_tokenizer264 unmodified linesreturn decodeddef empty_parse_result() -> Dict:return {"title": None,"season": None,"episode": None,"group": None,"resolution": None,"source": None,"special": None,"title_candidates": [],"tags": [],}def append_unique(values: List[str], value: str) -> None:if value and value not in values:values.append(value)def infer_title_kind(text: str) -> str:has_latin = any(ch.isascii() and ch.isalpha() for ch in text)has_han = any("\u4e00" <= ch <= "\u9fff" for ch in text)has_kana = any("\u3040" <= ch <= "\u30ff" or "\u31f0" <= ch <= "\u31ff" for ch in text)if has_kana:return "jpn"if has_latin and has_han:return "mixed"if has_han:return "chs"if has_latin:return "latin"return "mixed"def append_title_candidate(result: Dict, text: str, entity: Optional[str], source: str) -> None:if not text:returnkind = title_language(entity).lower() if entity else infer_title_kind(text)candidate = {"text": text, "kind": kind, "source": source}if candidate not in result["title_candidates"]:result["title_candidates"].append(candidate)def choose_title_span(spans: List[Tuple[str, str, int]]) -> Optional[str]:if not spans:return Nonereturn min(spans, key=lambda item: (title_entity_priority(item[0]), item[2]))[1]def postprocess(tokens: List[str],labels: List[str],5 unmodified linesMerges consecutive B- / I- tokens of the same entity type,then extracts structured fields."""result: Dict = empty_parse_result()entities = labels_to_entities(tokens, labels, tokenizer)grouped_entities: Dict[str, List[str]] = {}file_title_spans: List[Tuple[str, str, int]] = []path_title_spans: List[Tuple[str, str, int]] = []for index, (entity_type, text) in enumerate(entities):grouped_entities.setdefault(entity_type, []).append(text)title = normalize_field_text(text)if not title:continueif is_file_title_entity(entity_type):file_title_spans.append((entity_type, title, index))elif is_path_title_entity(entity_type):path_title_spans.append((entity_type, title, index))for entity, title, _index in file_title_spans:append_title_candidate(result, title, entity, "file")for entity, title, _index in path_title_spans:append_title_candidate(result, title, entity, "path")if file_title_spans and all(entity == "TITLE" for entity, _title, _index in file_title_spans):result["title"] = " ".join(title for _entity, title, _index in file_title_spans)else:result["title"] = choose_title_span(file_title_spans) or choose_title_span(path_title_spans)for text in grouped_entities.get("SEASON", []):season_num = extract_season_number(text)if season_num is not None:result["season"] = season_numbreakif result["season"] is None:for text in grouped_entities.get("PATH_SEASON", []):season_num = extract_season_number(text)if season_num is not None:result["season"] = season_numbreakfor text in grouped_entities.get("EPISODE", []):ep_num = extract_episode_number(text)if ep_num is not None:if result["episode"] is None:result["episode"] = ep_numfor text in grouped_entities.get("GROUP", []):group = normalize_field_text(text)if result["group"] is None:result["group"] = groupfor text in grouped_entities.get("SPECIAL", []):special = normalize_field_text(text)result["special"] = specialfor text in grouped_entities.get("RESOLUTION", []):res = extract_resolution(text)if res:result["resolution"] = resfor text in grouped_entities.get("TAG", []):tag = normalize_field_text(text)append_unique(result["tags"], tag)result["source"] = choose_thin_source(grouped_entities.get("SOURCE", []))6 unmodified linesor "月番" in result["title"]):result["title"] = new_show_titleappend_title_candidate(result, new_show_title, None, "file")search_special = extract_bracketed_search_special(whole_text)if search_special is not None:10 unmodified lines"resolution": None,"source": None,"special": standalone_special,"title_candidates": [],"tags": [],})25 unmodified lines# Tokenizetokens = tokenizer.tokenize(filename)if not tokens:return empty_parse_result()# Convert to input IDsinput_ids = tokenizer.convert_tokens_to_ids(tokens)36 unmodified lines# Truncate real tokens if we had to truncateavailable = min(real_token_count, max_length - 2)if available <= 0:return empty_parse_result()with torch.no_grad():logits = model(input_ids=input_tensor, attention_mask=mask_tensor).logits
5 unmodified lines67891011270 unmodified lines2822832842852862872884 unmodified lines2932942952962972982991 unmodified line3013023033043053063076 unmodified lines3143153163173183193207 unmodified lines3283293303313323333343353363373383391 unmodified line341342343344345346347117 unmodified lines4654664674684694704714724734744755 unmodified linesfrom dataclasses import dataclassfrom typing import Dict, Iterable, List, Optional, Sequence, TupleSEPARATOR_CHARS = set(" \t-_.|~~")270 unmodified linesdef labels_have_season_before(labels: Sequence[str], offsets: Sequence[Tuple[int, int]], marker_start: int) -> bool:return any(label.endswith("SEASON") and end <= marker_start for label, (_start, end) in zip(labels, offsets))def token_indices_for_span(offsets: Sequence[Tuple[int, int]], start: int, end: int) -> List[int]:4 unmodified linesdef label_span(labels: List[str], indices: Sequence[int], entity: str) -> None:previous_is_same_entity = bool(indices) and indices[0] > 0 and labels[indices[0] - 1].endswith(entity)first = not previous_is_same_entityfor idx in indices:labels[idx] = f"B-{entity}" if first else f"I-{entity}"1 unmodified linedef label_span_if_changed(labels: List[str], indices: Sequence[int], entity: str) -> bool:previous_is_same_entity = bool(indices) and indices[0] > 0 and labels[indices[0] - 1].endswith(entity)first_label = f"I-{entity}" if previous_is_same_entity else f"B-{entity}"expected = [first_label] + [f"I-{entity}"] * max(0, len(indices) - 1)if [labels[idx] for idx in indices] == expected:6 unmodified linesif not indices:return Falsereturn not any(labels[idx].endswith(("GROUP", "EPISODE", "SEASON"))for idx in indices)7 unmodified linesreturnidx = marker_indices[0] - 1while idx >= 0 and "".join(tokens[idx]).strip() == "" and labels[idx].endswith("TITLE"):labels[idx] = "O"idx -= 1idx = marker_indices[-1] + 1while idx < len(tokens) and tokens[idx] in SEPARATOR_CHARS and labels[idx].endswith("TITLE"):labels[idx] = "O"idx += 11 unmodified linedef first_episode_end(labels: Sequence[str], offsets: Sequence[Tuple[int, int]], text: str) -> int:ends = [end for label, (_start, end) in zip(labels, offsets)if label.endswith("EPISODE")]if ends:return min(ends)117 unmodified linescontinueexisting = [repaired_labels[idx] for idx in indices]if any(label.endswith(("GROUP", "EPISODE", "RESOLUTION", "SOURCE", "SPECIAL"))for label in existing):continueif not any(label.endswith("TITLE") for label in existing):continuelabel_span(repaired_labels, indices, "SEASON")5 unmodified lines678910111213270 unmodified lines2842852862872882892904 unmodified lines2952962972982993003011 unmodified line3033043053063073083096 unmodified lines3163173183193203213227 unmodified lines3303313323333343353363373383393403411 unmodified line343344345346347348349117 unmodified lines4674684694704714724734744754764775 unmodified linesfrom dataclasses import dataclassfrom typing import Dict, Iterable, List, Optional, Sequence, Tuplefrom .labels import is_same_entity_label, is_season_like_label, is_title_like_label, label_entitySEPARATOR_CHARS = set(" \t-_.|~~")270 unmodified linesdef labels_have_season_before(labels: Sequence[str], offsets: Sequence[Tuple[int, int]], marker_start: int) -> bool:return any(is_season_like_label(label) and end <= marker_start for label, (_start, end) in zip(labels, offsets))def token_indices_for_span(offsets: Sequence[Tuple[int, int]], start: int, end: int) -> List[int]:4 unmodified linesdef label_span(labels: List[str], indices: Sequence[int], entity: str) -> None:previous_is_same_entity = bool(indices) and indices[0] > 0 and is_same_entity_label(labels[indices[0] - 1], entity)first = not previous_is_same_entityfor idx in indices:labels[idx] = f"B-{entity}" if first else f"I-{entity}"1 unmodified linedef label_span_if_changed(labels: List[str], indices: Sequence[int], entity: str) -> bool:previous_is_same_entity = bool(indices) and indices[0] > 0 and is_same_entity_label(labels[indices[0] - 1], entity)first_label = f"I-{entity}" if previous_is_same_entity else f"B-{entity}"expected = [first_label] + [f"I-{entity}"] * max(0, len(indices) - 1)if [labels[idx] for idx in indices] == expected:6 unmodified linesif not indices:return Falsereturn not any(label_entity(labels[idx]) in {"GROUP", "EPISODE", "SEASON", "PATH_SEASON"}for idx in indices)7 unmodified linesreturnidx = marker_indices[0] - 1while idx >= 0 and "".join(tokens[idx]).strip() == "" and is_title_like_label(labels[idx]):labels[idx] = "O"idx -= 1idx = marker_indices[-1] + 1while idx < len(tokens) and tokens[idx] in SEPARATOR_CHARS and is_title_like_label(labels[idx]):labels[idx] = "O"idx += 11 unmodified linedef first_episode_end(labels: Sequence[str], offsets: Sequence[Tuple[int, int]], text: str) -> int:ends = [end for label, (_start, end) in zip(labels, offsets)if label_entity(label) == "EPISODE"]if ends:return min(ends)117 unmodified linescontinueexisting = [repaired_labels[idx] for idx in indices]if any(label_entity(label) in {"GROUP", "EPISODE", "RESOLUTION", "SOURCE", "SPECIAL", "TAG", "PATH_SEASON"}for label in existing):continueif not any(is_title_like_label(label) for label in existing):continuelabel_span(repaired_labels, indices, "SEASON")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205"""Shared BIO label schema and helpers."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Dict, Optional, Tuple
LABEL_SCHEMA_VERSION = 2
TITLE_SUFFIXES = ("CHS", "CHT", "JPN", "LATIN", "MIXED")TITLE_PRIORITY = ("CHS", "CHT", "JPN", "MIXED", "LATIN")
FILE_TITLE_ENTITIES = tuple(f"TITLE_{suffix}" for suffix in TITLE_SUFFIXES)PATH_TITLE_ENTITIES = tuple(f"PATH_TITLE_{suffix}" for suffix in TITLE_SUFFIXES)TITLE_ENTITIES = FILE_TITLE_ENTITIES + PATH_TITLE_ENTITIESTITLE_LIKE_ENTITIES = TITLE_ENTITIES + ("TITLE",)SEASON_LIKE_ENTITIES = ("SEASON", "PATH_SEASON")
DEFAULT_TITLE_ENTITY = "TITLE_MIXED"
_FALLBACK_LABELS = ( "O", "B-TITLE_CHS", "I-TITLE_CHS", "B-TITLE_CHT", "I-TITLE_CHT", "B-TITLE_JPN", "I-TITLE_JPN", "B-TITLE_LATIN", "I-TITLE_LATIN", "B-TITLE_MIXED", "I-TITLE_MIXED", "B-PATH_TITLE_CHS", "I-PATH_TITLE_CHS", "B-PATH_TITLE_CHT", "I-PATH_TITLE_CHT", "B-PATH_TITLE_JPN", "I-PATH_TITLE_JPN", "B-PATH_TITLE_LATIN", "I-PATH_TITLE_LATIN", "B-PATH_TITLE_MIXED", "I-PATH_TITLE_MIXED", "B-PATH_SEASON", "I-PATH_SEASON", "B-SEASON", "I-SEASON", "B-EPISODE", "I-EPISODE", "B-SPECIAL", "I-SPECIAL", "B-GROUP", "I-GROUP", "B-RESOLUTION", "I-RESOLUTION", "B-SOURCE", "I-SOURCE", "B-TAG", "I-TAG",)
def _load_schema_labels() -> Tuple[str, ...]: schema_path = Path(__file__).resolve().parents[1] / "label_schema.json" try: with schema_path.open("r", encoding="utf-8") as fh: payload = json.load(fh) except OSError: return _FALLBACK_LABELS
labels = payload.get("labels") if not isinstance(labels, list) or not labels: return _FALLBACK_LABELS if not all(isinstance(label, str) and label for label in labels): return _FALLBACK_LABELS return tuple(labels)
LABELS = _load_schema_labels()
LEGACY_15_LABELS = ( "O", "B-TITLE", "I-TITLE", "B-SEASON", "I-SEASON", "B-EPISODE", "I-EPISODE", "B-SPECIAL", "I-SPECIAL", "B-GROUP", "I-GROUP", "B-RESOLUTION", "I-RESOLUTION", "B-SOURCE", "I-SOURCE",)
LABEL2ID = {label: idx for idx, label in enumerate(LABELS)}ID2LABEL = {idx: label for idx, label in enumerate(LABELS)}
def make_label2id() -> Dict[str, int]: return dict(LABEL2ID)
def make_id2label() -> Dict[int, str]: return dict(ID2LABEL)
def split_bio_label(label: str) -> Tuple[Optional[str], Optional[str]]: if not isinstance(label, str) or label == "O": return None, None prefix, sep, entity = label.partition("-") if sep != "-" or prefix not in {"B", "I"} or not entity: return None, None return prefix, entity
def label_entity(label: str) -> Optional[str]: return split_bio_label(label)[1]
def canonical_entity(entity: str) -> str: return DEFAULT_TITLE_ENTITY if entity == "TITLE" else entity
def canonical_bio_label(label: str) -> str: prefix, entity = split_bio_label(label) if prefix is None or entity is None: return "O" if label == "O" else label return f"{prefix}-{canonical_entity(entity)}"
def is_title_entity(entity: Optional[str]) -> bool: return entity in TITLE_LIKE_ENTITIES
def is_file_title_entity(entity: Optional[str]) -> bool: return entity in FILE_TITLE_ENTITIES or entity == "TITLE"
def is_path_title_entity(entity: Optional[str]) -> bool: return entity in PATH_TITLE_ENTITIES
def is_title_like_label(label: str) -> bool: return is_title_entity(label_entity(label))
def is_season_entity(entity: Optional[str]) -> bool: return entity in SEASON_LIKE_ENTITIES
def is_season_like_label(label: str) -> bool: return is_season_entity(label_entity(label))
def is_same_entity_label(label: str, entity: str) -> bool: return label_entity(label) == entity
def title_language(entity: Optional[str]) -> str: if entity == "TITLE": return "MIXED" if not entity: return "MIXED" if entity.startswith("PATH_TITLE_"): return entity.removeprefix("PATH_TITLE_") if entity.startswith("TITLE_"): return entity.removeprefix("TITLE_") return "MIXED"
def title_entity_priority(entity: Optional[str]) -> Tuple[int, int]: language = title_language(entity) language_rank = TITLE_PRIORITY.index(language) if language in TITLE_PRIORITY else len(TITLE_PRIORITY) path_rank = 1 if is_path_title_entity(entity) else 0 return path_rank, language_rank
def label_migration_sources(target_label: str) -> Tuple[str, ...]: """Return old-label candidates that can initialize a target label row.""" if target_label == "O": return ("O",)
prefix, entity = split_bio_label(target_label) if prefix is None or entity is None: return (target_label,)
sources = [target_label] if is_title_entity(entity): sources.append(f"{prefix}-TITLE") elif entity == "PATH_SEASON": sources.append(f"{prefix}-SEASON") return tuple(dict.fromkeys(sources))
def infer_legacy_id2label(num_labels: int) -> Optional[Dict[int, str]]: if num_labels == len(LEGACY_15_LABELS): return {idx: label for idx, label in enumerate(LEGACY_15_LABELS)} if num_labels == len(LABELS): return make_id2label() return None17 unmodified lines181920212223242 unmodified lines26626726826927027142 unmodified lines31431531631731831917 unmodified linesfrom transformers.modeling_utils import PreTrainedModelfrom .config import Configclass LinearChainCRF(nn.Module):242 unmodified linesattention_probs_dropout_prob=config.attention_probs_dropout_prob,id2label=config.id2label,label2id=config.label2id,)42 unmodified linesreturn BertForTokenClassification.from_pretrained(model_dir)def save_model_head_config(model: PreTrainedModel, model_head: str) -> None:"""Persist the selected head in config.json for later auto-loading."""head = normalize_model_head(model_head)17 unmodified lines18192021222324242 unmodified lines26726826927027127227342 unmodified lines31631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443517 unmodified linesfrom transformers.modeling_utils import PreTrainedModelfrom .config import Configfrom .labels import infer_legacy_id2label, label_migration_sourcesclass LinearChainCRF(nn.Module):242 unmodified linesattention_probs_dropout_prob=config.attention_probs_dropout_prob,id2label=config.id2label,label2id=config.label2id,label_schema_version=config.label_schema_version,)42 unmodified linesreturn BertForTokenClassification.from_pretrained(model_dir)def _model_id2label_for_migration(model: PreTrainedModel) -> dict[int, str]:raw_id2label = getattr(model.config, "id2label", None) or {}normalized = {int(label_id): str(label) for label_id, label in raw_id2label.items()}classifier = getattr(model, "classifier", None)out_features = getattr(classifier, "out_features", None)if out_features is not None and len(normalized) != int(out_features):inferred = infer_legacy_id2label(int(out_features))if inferred is not None:return inferredreturn normalizeddef migrate_token_classifier_labels(model: PreTrainedModel,target_label2id: dict[str, int],target_id2label: dict[int, str],) -> dict[str, object]:"""Expand or reorder token-classification label rows for the shared schema.Exact labels are copied by name. Legacy 15-label TITLE rows initialize alltitle-like rows, and legacy SEASON rows initialize PATH_SEASON."""classifier = getattr(model, "classifier", None)if classifier is None or not isinstance(classifier, nn.Linear):return {"changed": False, "reason": "no_linear_classifier"}target_id2label = {int(label_id): str(label) for label_id, label in target_id2label.items()}target_label2id = {str(label): int(label_id) for label, label_id in target_label2id.items()}old_id2label = _model_id2label_for_migration(model)old_label2id = {label: label_id for label_id, label in old_id2label.items()}old_num_labels = int(classifier.out_features)new_num_labels = len(target_label2id)same_schema = (old_num_labels == new_num_labelsand all(old_id2label.get(idx) == target_id2label.get(idx) for idx in range(new_num_labels)))if same_schema:model.config.num_labels = new_num_labelsmodel.config.id2label = target_id2labelmodel.config.label2id = target_label2idreturn {"changed": False, "copied": new_num_labels, "target_labels": new_num_labels}old_weight = classifier.weight.detach()old_bias = classifier.bias.detach() if classifier.bias is not None else Nonenew_classifier = nn.Linear(classifier.in_features,new_num_labels,bias=classifier.bias is not None,device=old_weight.device,dtype=old_weight.dtype,)nn.init.normal_(new_classifier.weight,mean=0.0,std=getattr(model.config, "initializer_range", 0.02),)if new_classifier.bias is not None:nn.init.zeros_(new_classifier.bias)row_sources: dict[int, int] = {}copied = 0for target_label, target_id in target_label2id.items():for source_label in label_migration_sources(target_label):source_id = old_label2id.get(source_label)if source_id is None or source_id >= old_num_labels:continuenew_classifier.weight.data[target_id].copy_(old_weight[source_id])if new_classifier.bias is not None and old_bias is not None:new_classifier.bias.data[target_id].copy_(old_bias[source_id])row_sources[target_id] = source_idcopied += 1breakmodel.classifier = new_classifiermodel.num_labels = new_num_labelsmodel.config.num_labels = new_num_labelsmodel.config.id2label = target_id2labelmodel.config.label2id = target_label2idif hasattr(model, "crf"):old_crf = model.crfnew_crf = LinearChainCRF(new_num_labels, target_id2label).to(device=old_weight.device,dtype=old_weight.dtype,)nn.init.zeros_(new_crf.start_transitions)nn.init.zeros_(new_crf.end_transitions)nn.init.zeros_(new_crf.transitions)with torch.no_grad():for target_id, source_id in row_sources.items():if source_id < old_crf.start_transitions.shape[0]:new_crf.start_transitions[target_id].copy_(old_crf.start_transitions[source_id])new_crf.end_transitions[target_id].copy_(old_crf.end_transitions[source_id])for target_to_id, source_to_id in row_sources.items():for target_from_id, source_from_id in row_sources.items():if (source_from_id < old_crf.transitions.shape[0]and source_to_id < old_crf.transitions.shape[1]):new_crf.transitions[target_from_id, target_to_id].copy_(old_crf.transitions[source_from_id, source_to_id])model.crf = new_crfreturn {"changed": True,"source_labels": old_num_labels,"target_labels": new_num_labels,"copied": copied,}def save_model_head_config(model: PreTrainedModel, model_head: str) -> None:"""Persist the selected head in config.json for later auto-loading."""head = normalize_model_head(model_head)
32 unmodified lines333435363738394041287 unmodified lines32933033133233333433533633733833934034116 unmodified lines35835936036136236322 unmodified lines3863873883893903915 unmodified lines39739839940040140215 unmodified lines4184194204214224238 unmodified lines43243343443543643743819 unmodified lines458459460461462463464553 unmodified lines10181019102010211022102332 unmodified lines105610571058105910601061106210631064264 unmodified lines132913301331133213331334133513361337187 unmodified lines15251526152715281529153032 unmodified linesfrom .config import Configfrom .tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerfrom .model import create_model, print_model_summary, count_parameters, load_model, save_model_head_configfrom .dataset import AnimeItemsDataset, EncodedAnimeDataset, labels_for_tokenizerfrom .inference import parse_filename, postprocessfrom .virtual_dataset import DatasetRangeView, ShardedEncodedDataset287 unmodified linesactive_tokens: List[str] = []for token, label in zip(tokens, labels):if label.startswith("B-"):if active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens))active_entity = label[2:]active_tokens = [str(token)]elif label.startswith("I-") and active_entity == label[2:]:active_tokens.append(str(token))else:if active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens))16 unmodified linesfor text, entity in spans:if not text:continuestart = filename.find(text, cursor)if start < 0:start = filename.find(text)22 unmodified lines"SPECIAL": 0.3,"RESOLUTION": 0.65,"SOURCE": 0.65,}.get(entity, 0.5)5 unmodified linesspecial = next((value.strip() for value in entities.get("SPECIAL", []) if value.strip()), None)resolution = next((value.strip() for value in entities.get("RESOLUTION", []) if value.strip()), None)source = next((value.strip() for value in entities.get("SOURCE", []) if value.strip()), None)specs: List[tuple[str, List[tuple[str, str]]]] = []if title:15 unmodified linesspecs.append((special, [(special, "SPECIAL")]))if title and special:specs.append((f"{title} - {special}", [(title, "TITLE"), (special, "SPECIAL")]))augmented: List[Dict] = []for text, spans in specs:8 unmodified linesentities = extract_entities_from_labels(item.get("tokens", []), item.get("labels", []))available = [entityfor entity in ("GROUP", "TITLE", "SEASON", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE")if entities.get(entity)]if not available:19 unmodified linesif not values:continuevalue = rng.choice(values)if entity in {"GROUP", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE"} and rng.random() < 0.35:parts.append(f"[{value}]")else:parts.append(value)553 unmodified linesdef normalize_field_value(field: str, value) -> Optional[str]:if value is None:return Noneif field in {"episode", "season"}:try:return str(int(value))32 unmodified linesgold_labels = gold_labels[:available]gold = postprocess(tokens, gold_labels, tokenizer=tokenizer)gold_entities = {label.split("-", 1)[1] for label in gold_labels if label.startswith(("B-", "I-"))}for optional_field, entity in (("episode", "EPISODE"), ("season", "SEASON")):if entity not in gold_entities:gold[optional_field] = Nonepred = parse_filename(filename,model,264 unmodified linesf" Remapped token embeddings: copied {copied:,}/{config.vocab_size:,} "f"tokens from init checkpoint")model.config.num_labels = config.num_labelsmodel.config.id2label = config.id2labelmodel.config.label2id = config.label2idelse:print("Creating model...")selected_model_head = "linear" if args.model_head == "auto" else args.model_head187 unmodified lines# Set proper label mappings in model config before savingmodel.config.id2label = config.id2labelmodel.config.label2id = config.label2idmodel.config.tokenizer_variant = tokenizer_variantmodel.config.max_seq_length = config.max_seq_lengthsave_model_head_config(model, selected_model_head)32 unmodified lines33343536373839404142434445464748495051525354287 unmodified lines34234334434534634734834935035135235335435535635735835936036136236336416 unmodified lines38138238338438538638722 unmodified lines4104114124134144154165 unmodified lines42242342442542642742815 unmodified lines4444454464474484494504518 unmodified lines46046146246346446546619 unmodified lines486487488489490491492553 unmodified lines104610471048104910501051105210531054105510561057105832 unmodified lines1091109210931094109510961097109810991100264 unmodified lines13651366136713681369137013711372137313741375137613771378137913801381187 unmodified lines156915701571157215731574157532 unmodified linesfrom .config import Configfrom .tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerfrom .model import (create_model,print_model_summary,count_parameters,load_model,migrate_token_classifier_labels,save_model_head_config,)from .dataset import AnimeItemsDataset, EncodedAnimeDataset, labels_for_tokenizerfrom .inference import parse_filename, postprocessfrom .labels import (canonical_entity,canonical_bio_label,is_season_like_label,is_title_entity,)from .virtual_dataset import DatasetRangeView, ShardedEncodedDataset287 unmodified linesactive_tokens: List[str] = []for token, label in zip(tokens, labels):label = canonical_bio_label(str(label))if label.startswith("B-"):if active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens))entity = label[2:]active_entity = "TITLE" if is_title_entity(entity) else ("SEASON" if entity == "PATH_SEASON" else entity)active_tokens = [str(token)]elif label.startswith("I-"):entity = label[2:]entity = "TITLE" if is_title_entity(entity) else ("SEASON" if entity == "PATH_SEASON" else entity)if active_entity == entity:active_tokens.append(str(token))else:if active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens))active_entity = entityactive_tokens = [str(token)]else:if active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens))16 unmodified linesfor text, entity in spans:if not text:continueentity = canonical_entity(entity)start = filename.find(text, cursor)if start < 0:start = filename.find(text)22 unmodified lines"SPECIAL": 0.3,"RESOLUTION": 0.65,"SOURCE": 0.65,"TAG": 0.35,}.get(entity, 0.5)5 unmodified linesspecial = next((value.strip() for value in entities.get("SPECIAL", []) if value.strip()), None)resolution = next((value.strip() for value in entities.get("RESOLUTION", []) if value.strip()), None)source = next((value.strip() for value in entities.get("SOURCE", []) if value.strip()), None)tag = next((value.strip() for value in entities.get("TAG", []) if value.strip()), None)specs: List[tuple[str, List[tuple[str, str]]]] = []if title:15 unmodified linesspecs.append((special, [(special, "SPECIAL")]))if title and special:specs.append((f"{title} - {special}", [(title, "TITLE"), (special, "SPECIAL")]))if title and tag:specs.append((f"{title} [{tag}]", [(title, "TITLE"), (tag, "TAG")]))augmented: List[Dict] = []for text, spans in specs:8 unmodified linesentities = extract_entities_from_labels(item.get("tokens", []), item.get("labels", []))available = [entityfor entity in ("GROUP", "TITLE", "SEASON", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE", "TAG")if entities.get(entity)]if not available:19 unmodified linesif not values:continuevalue = rng.choice(values)if entity in {"GROUP", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE", "TAG"} and rng.random() < 0.35:parts.append(f"[{value}]")else:parts.append(value)553 unmodified linesdef normalize_field_value(field: str, value) -> Optional[str]:if value is None:return Noneif isinstance(value, list):normalized_items = [normalize_field_value(field, item)for item in valueif item is not None]return "|".join(item for item in normalized_items if item)if field in {"episode", "season"}:try:return str(int(value))32 unmodified linesgold_labels = gold_labels[:available]gold = postprocess(tokens, gold_labels, tokenizer=tokenizer)gold_entities = {label.split("-", 1)[1] for label in gold_labels if label.startswith(("B-", "I-"))}if "EPISODE" not in gold_entities:gold["episode"] = Noneif not any(is_season_like_label(label) for label in gold_labels):gold["season"] = Nonepred = parse_filename(filename,model,264 unmodified linesf" Remapped token embeddings: copied {copied:,}/{config.vocab_size:,} "f"tokens from init checkpoint")migration = migrate_token_classifier_labels(model, config.label2id, config.id2label)if migration.get("changed"):print(" Migrated token classifier labels: "f"{migration.get('source_labels')} -> {migration.get('target_labels')} "f"(copied {migration.get('copied')} rows)")model.config.num_labels = config.num_labelsmodel.config.id2label = config.id2labelmodel.config.label2id = config.label2idmodel.config.label_schema_version = config.label_schema_versionelse:print("Creating model...")selected_model_head = "linear" if args.model_head == "auto" else args.model_head187 unmodified lines# Set proper label mappings in model config before savingmodel.config.id2label = config.id2labelmodel.config.label2id = config.label2idmodel.config.label_schema_version = config.label_schema_versionmodel.config.tokenizer_variant = tokenizer_variantmodel.config.max_seq_length = config.max_seq_lengthsave_model_head_config(model, selected_model_head)
109 unmodified lines110111112113114115125 unmodified lines241242243244245246109 unmodified lines"id": "long_running_episode","filename": "One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264","expected": {"title": "One.Piece","episode": 1110,"resolution": "1080p",125 unmodified lines"source": "GB"}},{"id": "vcb_special_iv_not_episode","filename": "[YYDM&VCB-Studio] Shinsekai Yori [IV05][Ma10p_1080p][x265_aac].mkv",109 unmodified lines110111112113114115116125 unmodified lines242243244245246247248249250251252253254255256257258259260261262263264265266267109 unmodified lines"id": "long_running_episode","filename": "One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264","expected": {"group": null,"title": "One.Piece","episode": 1110,"resolution": "1080p",125 unmodified lines"source": "GB"}},{"id": "path_sousou_dir_season_episode","filename": "/mnt/media/anime/Sousou no Frieren/Season 01/31.mkv","expected": {"group": null,"title": "Sousou no Frieren","season": 1,"episode": 31}},{"id": "path_generic_title_numeric_season_episode","filename": "/mnt/media/anime/Title/01/03.mkv","expected": {"group": null,"title": "Title","season": 1,"episode": 3}},{"id": "vcb_special_iv_not_episode","filename": "[YYDM&VCB-Studio] Shinsekai Yori [IV05][Ma10p_1080p][x265_aac].mkv",
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980{ "version": 2, "labels": [ "O", "B-TITLE_CHS", "I-TITLE_CHS", "B-TITLE_CHT", "I-TITLE_CHT", "B-TITLE_JPN", "I-TITLE_JPN", "B-TITLE_LATIN", "I-TITLE_LATIN", "B-TITLE_MIXED", "I-TITLE_MIXED", "B-PATH_TITLE_CHS", "I-PATH_TITLE_CHS", "B-PATH_TITLE_CHT", "I-PATH_TITLE_CHT", "B-PATH_TITLE_JPN", "I-PATH_TITLE_JPN", "B-PATH_TITLE_LATIN", "I-PATH_TITLE_LATIN", "B-PATH_TITLE_MIXED", "I-PATH_TITLE_MIXED", "B-PATH_SEASON", "I-PATH_SEASON", "B-SEASON", "I-SEASON", "B-EPISODE", "I-EPISODE", "B-SPECIAL", "I-SPECIAL", "B-GROUP", "I-GROUP", "B-RESOLUTION", "I-RESOLUTION", "B-SOURCE", "I-SOURCE", "B-TAG", "I-TAG" ], "title_entities": [ "TITLE_CHS", "TITLE_CHT", "TITLE_JPN", "TITLE_LATIN", "TITLE_MIXED", "PATH_TITLE_CHS", "PATH_TITLE_CHT", "PATH_TITLE_JPN", "PATH_TITLE_LATIN", "PATH_TITLE_MIXED" ], "file_title_entities": [ "TITLE_CHS", "TITLE_CHT", "TITLE_JPN", "TITLE_LATIN", "TITLE_MIXED" ], "path_title_entities": [ "PATH_TITLE_CHS", "PATH_TITLE_CHT", "PATH_TITLE_JPN", "PATH_TITLE_LATIN", "PATH_TITLE_MIXED" ], "title_priority": [ "CHS", "CHT", "JPN", "MIXED", "LATIN" ], "notes": { "PATH_SEASON": "Season value extracted from a directory/path segment. File-level SEASON wins when both are present.", "TAG": "Non-key side tags such as 国漫, 日漫, 剧场版, Gekijouban, Movie, TV, and years.", "TITLE_LATIN": "Latin-script titles, including English aliases and romaji." }}11 unmodified lines121314151617181920212217 unmodified lines404142434445463 unmodified lines50515253545556571 unmodified line59606162636465666768693 unmodified lines737475767778798081828384858687888990913 unmodified lines959697989910010110211 unmodified linesfrom pathlib import Pathdef char_item(filename: str, spans: list[tuple[str, str]], source: str) -> dict[str, object]:tokens = list(filename)labels = ["O"] * len(tokens)cursor = 0for text, entity in spans:start = filename.find(text, cursor)if start < 0:start = filename.find(text)17 unmodified lineschar_item(r"Z:\Library\Anime\Shinsekai Yori\Extras\NCED02 [Ma10p_1080p][x265_flac].mkv",[("Shinsekai Yori", "TITLE"),("NCED02", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),3 unmodified lineschar_item(r"O:\115open\Anime\Sousou no Frieren\Season 01\31 [1080P][Baha][WEB-DL].mkv",[("Sousou no Frieren", "TITLE"),("Season 01", "SEASON"),("31", "EPISODE"),("1080P", "RESOLUTION"),("Baha", "SOURCE"),1 unmodified line],source,),char_item(r"/mnt/media/anime/Bangumi/One Piece/Season 21/1110 [1080p][WEB-DL].mkv",[("One Piece", "TITLE"),("Season 21", "SEASON"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),3 unmodified lineschar_item(r"D:\Media\Anime\completed\Witch Watch\S01\15 [1080p][CHS].mkv",[("Witch Watch", "TITLE"),("S01", "SEASON"),("15", "EPISODE"),("1080p", "RESOLUTION"),("CHS", "SOURCE"),],source,),char_item(r"O:\115open\Anime\Kakuriyo no Yadomeshi\Season 02\12 [WebRip 1080p].mkv",[("Kakuriyo no Yadomeshi", "TITLE"),("Season 02", "SEASON"),("12", "EPISODE"),("WebRip", "SOURCE"),("1080p", "RESOLUTION"),3 unmodified lineschar_item(r"C:\Archive\old\misc\One Piece\Season 21\One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264.mkv",[("One Piece", "TITLE"),("Season 21", "SEASON"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),11 unmodified lines121314151617181920212223242526272829303117 unmodified lines495051525354553 unmodified lines59606162636465661 unmodified line68697071727374757677787980818283848586878889909192939495963 unmodified lines1001011021031041051061071081091101111121131141151161171183 unmodified lines12212312412512612712812913011 unmodified linesfrom pathlib import Pathdef canonical_entity(entity: str) -> str:if entity == "TITLE":return "TITLE_MIXED"if entity == "PATH_TITLE":return "PATH_TITLE_MIXED"return entitydef char_item(filename: str, spans: list[tuple[str, str]], source: str) -> dict[str, object]:tokens = list(filename)labels = ["O"] * len(tokens)cursor = 0for text, entity in spans:entity = canonical_entity(entity)start = filename.find(text, cursor)if start < 0:start = filename.find(text)17 unmodified lineschar_item(r"Z:\Library\Anime\Shinsekai Yori\Extras\NCED02 [Ma10p_1080p][x265_flac].mkv",[("Shinsekai Yori", "PATH_TITLE_LATIN"),("NCED02", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),3 unmodified lineschar_item(r"O:\115open\Anime\Sousou no Frieren\Season 01\31 [1080P][Baha][WEB-DL].mkv",[("Sousou no Frieren", "PATH_TITLE_LATIN"),("Season 01", "PATH_SEASON"),("31", "EPISODE"),("1080P", "RESOLUTION"),("Baha", "SOURCE"),1 unmodified line],source,),char_item(r"/mnt/media/anime/Sousou no Frieren/Season 01/31.mkv",[("Sousou no Frieren", "PATH_TITLE_LATIN"),("Season 01", "PATH_SEASON"),("31", "EPISODE"),],source,),char_item(r"/mnt/media/anime/Title/01/03.mkv",[("Title", "PATH_TITLE_LATIN"),("01", "PATH_SEASON"),("03", "EPISODE"),],source,),char_item(r"/mnt/media/anime/Bangumi/One Piece/Season 21/1110 [1080p][WEB-DL].mkv",[("One Piece", "PATH_TITLE_LATIN"),("Season 21", "PATH_SEASON"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),3 unmodified lineschar_item(r"D:\Media\Anime\completed\Witch Watch\S01\15 [1080p][CHS].mkv",[("Witch Watch", "PATH_TITLE_LATIN"),("S01", "PATH_SEASON"),("15", "EPISODE"),("1080p", "RESOLUTION"),("CHS", "TAG"),],source,),char_item(r"O:\115open\Anime\Kakuriyo no Yadomeshi\Season 02\12 [WebRip 1080p].mkv",[("Kakuriyo no Yadomeshi", "PATH_TITLE_LATIN"),("Season 02", "PATH_SEASON"),("12", "EPISODE"),("WebRip", "SOURCE"),("1080p", "RESOLUTION"),3 unmodified lineschar_item(r"C:\Archive\old\misc\One Piece\Season 21\One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264.mkv",[("One Piece", "PATH_TITLE_LATIN"),("Season 21", "PATH_SEASON"),("One.Piece", "TITLE_LATIN"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),
1 unmodified line234567891011 unmodified lines222324252627282930313233343561 unmodified lines9798991001011022 unmodified lines1051061071081091101112 unmodified lines11411511611711811912012112212317 unmodified lines14114214314414514624 unmodified lines17117217317417517617717817918038 unmodified lines21922022122222322411 unmodified lines2362372382392402412422432446 unmodified lines2512522532542552562572581 unmodified lineThe generated rows look like:noise/noise/TITLE/Season 01/03 [1080P][WEB-DL].mkvPrefix directories are always labeled ``O``. The title directory, seasondirectory, episode/special filename stem, and optional meta tags keep their BIOlabels so the model learns to ignore library paths without relying on runtimepath stripping.11 unmodified linesfrom typing import Iterable, OptionalENTITY_NAMES = {"TITLE","SEASON","EPISODE","SPECIAL","RESOLUTION","SOURCE","GROUP",}PREFIX_COMPONENTS = {61 unmodified linesraise ValueError(f"{path}:{line_no}: invalid JSON") from excdef extract_entities(tokens: list[str], labels: list[str]) -> dict[str, list[str]]:entities: dict[str, list[str]] = {name: [] for name in ENTITY_NAMES}active_entity: Optional[str] = None2 unmodified linesdef flush() -> None:nonlocal active_entity, active_tokensif active_entity and active_tokens:entities.setdefault(active_entity, []).append("".join(active_tokens).strip())active_entity = Noneactive_tokens = []2 unmodified linestoken = str(token)if label.startswith("B-"):flush()active_entity = label.split("-", 1)[1]active_tokens = [token]elif label.startswith("I-"):entity = label.split("-", 1)[1]if active_entity == entity:active_tokens.append(token)else:17 unmodified linesreturn rng.choice(values)def choose_group(entities: dict[str, list[str]],rng: random.Random,24 unmodified linesnumber = first_ascii_number(value)variants = [value.strip()]if number is not None:variants.extend([f"Season {number}", f"Season {number:02}", f"S{number:02}", f"第{number}季"])return rng.choice(variants)number = rng.choice([1, 1, 1, 2])return rng.choice([f"Season {number}", f"Season {number:02}", f"S{number:02}", f"第{number}季"])def episode_text(value: str, rng: random.Random) -> str:38 unmodified linesif source and rng.random() < 0.75:pieces.extend([("[", None), (source.strip(), "SOURCE"), ("]", None)])def build_path_row(record: dict,11 unmodified linesif len(tokens) != len(labels):return Noneentities = extract_entities(tokens, labels)title = choose_entity(entities, "TITLE", rng)if not title:return Nonegroup = choose_group(entities, rng, max_group_length)if require_group and not group:return None6 unmodified linesstyle = rng.choice(styles)separator = "\\" if style == "windows" else "/"components = prefix_components(style, rng)components.append([(title, "TITLE")])components.append([(season_text(choose_entity(entities, "SEASON", rng), rng), "SEASON")])endpoint_pieces: list[tuple[str, Optional[str]]] = []if group and rng.random() < group_prefix_prob:1 unmodified line234567891011 unmodified lines222324252627282930313233343536373839404142434461 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551562 unmodified lines1591601611621631641652 unmodified lines16816917017117217317417517617717 unmodified lines19519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623724 unmodified lines26226326426526626726826927027138 unmodified lines31031131231331431531631731831932032111 unmodified lines3333343353363373383393403413426 unmodified lines3493503513523533543553561 unmodified lineThe generated rows look like:noise/noise/PATH_TITLE_LATIN/PATH_SEASON/03 [1080P][WEB-DL].mkvPrefix directories are always labeled ``O``. The path-title directory, path-seasondirectory, episode/special filename stem, and optional meta tags keep their BIOlabels so the model learns to ignore library paths without relying on runtimepath stripping.11 unmodified linesfrom typing import Iterable, OptionalTITLE_SUFFIXES = ("CHS", "CHT", "JPN", "LATIN", "MIXED")FILE_TITLE_ENTITIES = tuple(f"TITLE_{suffix}" for suffix in TITLE_SUFFIXES)PATH_TITLE_ENTITIES = tuple(f"PATH_TITLE_{suffix}" for suffix in TITLE_SUFFIXES)ENTITY_NAMES = {*FILE_TITLE_ENTITIES,*PATH_TITLE_ENTITIES,"PATH_SEASON","SEASON","EPISODE","SPECIAL","RESOLUTION","SOURCE","GROUP","TAG","TITLE","PATH_TITLE",}PREFIX_COMPONENTS = {61 unmodified linesraise ValueError(f"{path}:{line_no}: invalid JSON") from excdef canonical_entity(entity: str) -> Optional[str]:if entity == "TITLE":return "TITLE_MIXED"if entity == "PATH_TITLE":return "PATH_TITLE_MIXED"if entity in ENTITY_NAMES:return entityreturn Nonedef file_title_to_path_title(entity: str) -> Optional[str]:if entity.startswith("TITLE_"):return "PATH_TITLE_" + entity.removeprefix("TITLE_")return Nonedef path_title_to_file_title(entity: str) -> Optional[str]:if entity.startswith("PATH_TITLE_"):return "TITLE_" + entity.removeprefix("PATH_TITLE_")return Nonedef append_entity_value(entities: dict[str, list[str]], entity: str, value: str) -> None:value = value.strip()if not value:returndef append_unique(target_entity: str) -> None:values = entities.setdefault(target_entity, [])if value not in values:values.append(value)append_unique(entity)path_title = file_title_to_path_title(entity)if path_title:append_unique(path_title)file_title = path_title_to_file_title(entity)if file_title:append_unique(file_title)if entity == "SEASON":append_unique("PATH_SEASON")elif entity == "PATH_SEASON":append_unique("SEASON")def extract_entities(tokens: list[str], labels: list[str]) -> dict[str, list[str]]:entities: dict[str, list[str]] = {name: [] for name in ENTITY_NAMES}active_entity: Optional[str] = None2 unmodified linesdef flush() -> None:nonlocal active_entity, active_tokensif active_entity and active_tokens:append_entity_value(entities, active_entity, "".join(active_tokens))active_entity = Noneactive_tokens = []2 unmodified linestoken = str(token)if label.startswith("B-"):flush()active_entity = canonical_entity(label.split("-", 1)[1])active_tokens = [token]elif label.startswith("I-"):entity = canonical_entity(label.split("-", 1)[1])if active_entity == entity:active_tokens.append(token)else:17 unmodified linesreturn rng.choice(values)def choose_path_title(entities: dict[str, list[str]], rng: random.Random) -> Optional[tuple[str, str]]:candidates: list[tuple[str, str]] = []seen: set[tuple[str, str]] = set()for entity in PATH_TITLE_ENTITIES:for value in entities.get(entity, []):value = value.strip()key = (value, entity)if value and key not in seen:candidates.append(key)seen.add(key)for entity in FILE_TITLE_ENTITIES:path_entity = file_title_to_path_title(entity)if path_entity is None:continuefor value in entities.get(entity, []):value = value.strip()key = (value, path_entity)if value and key not in seen:candidates.append(key)seen.add(key)if not candidates:return Nonereturn rng.choice(candidates)def choose_path_season_value(entities: dict[str, list[str]], rng: random.Random) -> Optional[str]:values = [value.strip()for entity in ("PATH_SEASON", "SEASON")for value in entities.get(entity, [])if value.strip()]if not values:return Nonereturn rng.choice(values)def choose_group(entities: dict[str, list[str]],rng: random.Random,24 unmodified linesnumber = first_ascii_number(value)variants = [value.strip()]if number is not None:variants.extend([f"{number:02}", f"Season {number}", f"Season {number:02}", f"S{number:02}", f"第{number}季"])return rng.choice(variants)number = rng.choice([1, 1, 1, 2])return rng.choice([f"{number:02}", f"Season {number}", f"Season {number:02}", f"S{number:02}", f"第{number}季"])def episode_text(value: str, rng: random.Random) -> str:38 unmodified linesif source and rng.random() < 0.75:pieces.extend([("[", None), (source.strip(), "SOURCE"), ("]", None)])tag_values = list(entities.get("TAG", []))rng.shuffle(tag_values)for tag in tag_values[:1]:if tag and rng.random() < 0.60:pieces.extend([("[", None), (tag.strip(), "TAG"), ("]", None)])def build_path_row(record: dict,11 unmodified linesif len(tokens) != len(labels):return Noneentities = extract_entities(tokens, labels)title_choice = choose_path_title(entities, rng)if not title_choice:return Nonetitle, path_title_entity = title_choicegroup = choose_group(entities, rng, max_group_length)if require_group and not group:return None6 unmodified linesstyle = rng.choice(styles)separator = "\\" if style == "windows" else "/"components = prefix_components(style, rng)components.append([(title, path_title_entity)])components.append([(season_text(choose_path_season_value(entities, rng), rng), "PATH_SEASON")])endpoint_pieces: list[tuple[str, Optional[str]]] = []if group and rng.random() < group_prefix_prob:
63 unmodified lines646566676869702 unmodified lines737475767778793 unmodified lines838485868788893 unmodified lines939495969798993 unmodified lines1031041051061071081094 unmodified lines1141151161171181191204 unmodified lines1251261271281291301317 unmodified lines1391401411421431441457 unmodified lines1531541551561571581596 unmodified lines1661671681691701711726 unmodified lines1791801811821831841855 unmodified lines1911921931941951961971984 unmodified lines2032042052062072082092104 unmodified lines2152162172182192202212224 unmodified lines2272282292302312322333 unmodified lines2372382392402412422432 unmodified lines2462472482492502512525 unmodified lines25825926026126226326463 unmodified linesyield char_item("One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264",[("One.Piece", "TITLE"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),2 unmodified linesyield char_item("One.Piece.1111.1080p.WEB-DL.AAC2.0.H.264",[("One.Piece", "TITLE"),("1111", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),3 unmodified lines"【喵萌奶茶屋】★04月新番★[葬送的芙莉莲][01][1080P][HEVC]",[("喵萌奶茶屋", "GROUP"),("葬送的芙莉莲", "TITLE"),("01", "EPISODE"),("1080P", "RESOLUTION"),("HEVC", "SOURCE"),3 unmodified lines"【喵萌奶茶屋】★10月新番★[药屋少女的呢喃][02][1080P][HEVC]",[("喵萌奶茶屋", "GROUP"),("药屋少女的呢喃", "TITLE"),("02", "EPISODE"),("1080P", "RESOLUTION"),("HEVC", "SOURCE"),3 unmodified lines"[Billion Meta Lab] 魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi [07][1080P][CHT&JPN][檢索:魔法姊妹露露特莉莉].mp4",[("Billion Meta Lab", "GROUP"),("魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi", "TITLE"),("07", "EPISODE"),("1080P", "RESOLUTION"),("CHT&JPN", "SOURCE"),4 unmodified lines"[Billion Meta Lab] 魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi [08][1080P][CHT&JPN][检索:魔法姊妹露露特莉莉].mp4",[("Billion Meta Lab", "GROUP"),("魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi", "TITLE"),("08", "EPISODE"),("1080P", "RESOLUTION"),("CHT&JPN", "SOURCE"),4 unmodified lines"[LoliHouse] Kakuriyo no Yadomeshi Ni - 12 [WebRip 1080p HEVC-10bit AAC SRTx2].mkv",[("LoliHouse", "GROUP"),("Kakuriyo no Yadomeshi", "TITLE"),("Ni", "SEASON"),("12", "EPISODE"),("WebRip", "SOURCE"),7 unmodified lines"[LoliHouse] Kakuriyo no Yadomeshi Ni - 13 [WebRip 1080p HEVC-10bit AAC SRTx2].mkv",[("LoliHouse", "GROUP"),("Kakuriyo no Yadomeshi", "TITLE"),("Ni", "SEASON"),("13", "EPISODE"),("WebRip", "SOURCE"),7 unmodified lines"[AI-Raws] 炎炎の消防隊 弐ノ章 #13 (BD HEVC 1920x1080 yuv444p10le FLAC)[FC74A2D5].mkv",[("AI-Raws", "GROUP"),("炎炎の消防隊", "TITLE"),("弐ノ章", "SEASON"),("13", "EPISODE"),("BD", "SOURCE"),6 unmodified lines"[AI-Raws] 炎炎の消防隊 弐ノ章 #01 (BD HEVC 1920x1080 FLAC).mkv",[("AI-Raws", "GROUP"),("炎炎の消防隊", "TITLE"),("弐ノ章", "SEASON"),("01", "EPISODE"),("BD", "SOURCE"),6 unmodified lines"[DBD-Raws][炎炎消防队 貳之章][01][1080P][BDRip][HEVC-10bit][FLAC]",[("DBD-Raws", "GROUP"),("炎炎消防队", "TITLE"),("貳之章", "SEASON"),("01", "EPISODE"),("1080P", "RESOLUTION"),5 unmodified lines"[GM-Team][国漫][逆天邪神 第2季][Against the Gods Ⅱ][2026][04][HEVC][GB][4K].mp4",[("GM-Team", "GROUP"),("逆天邪神", "TITLE"),("第2季", "SEASON"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[GM-Team][国漫][剑来 第2季][Sword of Coming Ⅱ][2025][04][HEVC][GB][4K]",[("GM-Team", "GROUP"),("剑来", "TITLE"),("第2季", "SEASON"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[GM-Team][国漫][大主宰 第2季][The Great Ruler Ⅱ][2026][04][HEVC][GB][4K]",[("GM-Team", "GROUP"),("大主宰", "TITLE"),("第2季", "SEASON"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[YYDM&VCB-Studio] Shinsekai Yori [IV05][Ma10p_1080p][x265_aac].mkv",[("YYDM&VCB-Studio", "GROUP"),("Shinsekai Yori", "TITLE"),("IV05", "SPECIAL"),("1080p", "RESOLUTION"),("x265_aac", "SOURCE"),3 unmodified lines"[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv",[("YYDM&VCB-Studio", "GROUP"),("Shinsekai Yori", "TITLE"),("NCED02", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),2 unmodified linesyield char_item("InuYasha.2000.NCED02.BDrip.AV1.10Bit.DTS.1080p-CalChi",[("InuYasha", "TITLE"),("NCED02", "SPECIAL"),("BDrip", "SOURCE"),("AV1", "SOURCE"),5 unmodified lines"[VCB-Studio] Yamada-kun to 7-nin no Majo [NCED][Ma10p_1080p][x265_flac]",[("VCB-Studio", "GROUP"),("Yamada-kun to 7-nin no Majo", "TITLE"),("NCED", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),63 unmodified lines646566676869702 unmodified lines737475767778793 unmodified lines83848586878889903 unmodified lines9495969798991001013 unmodified lines1051061071081091101114 unmodified lines1161171181191201211224 unmodified lines1271281291301311321337 unmodified lines1411421431441451461477 unmodified lines1551561571581591601616 unmodified lines1681691701711721731746 unmodified lines1811821831841851861875 unmodified lines1931941951961971981992002012022034 unmodified lines2082092102112122132142152162172184 unmodified lines2232242252262272282292302312322334 unmodified lines2382392402412422432443 unmodified lines2482492502512522532542 unmodified lines2572582592602612622635 unmodified lines26927027127227327427563 unmodified linesyield char_item("One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264",[("One.Piece", "TITLE_LATIN"),("1110", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),2 unmodified linesyield char_item("One.Piece.1111.1080p.WEB-DL.AAC2.0.H.264",[("One.Piece", "TITLE_LATIN"),("1111", "EPISODE"),("1080p", "RESOLUTION"),("WEB-DL", "SOURCE"),3 unmodified lines"【喵萌奶茶屋】★04月新番★[葬送的芙莉莲][01][1080P][HEVC]",[("喵萌奶茶屋", "GROUP"),("★04月新番★", "TAG"),("葬送的芙莉莲", "TITLE_CHS"),("01", "EPISODE"),("1080P", "RESOLUTION"),("HEVC", "SOURCE"),3 unmodified lines"【喵萌奶茶屋】★10月新番★[药屋少女的呢喃][02][1080P][HEVC]",[("喵萌奶茶屋", "GROUP"),("★10月新番★", "TAG"),("药屋少女的呢喃", "TITLE_CHS"),("02", "EPISODE"),("1080P", "RESOLUTION"),("HEVC", "SOURCE"),3 unmodified lines"[Billion Meta Lab] 魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi [07][1080P][CHT&JPN][檢索:魔法姊妹露露特莉莉].mp4",[("Billion Meta Lab", "GROUP"),("魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi", "TITLE_MIXED"),("07", "EPISODE"),("1080P", "RESOLUTION"),("CHT&JPN", "SOURCE"),4 unmodified lines"[Billion Meta Lab] 魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi [08][1080P][CHT&JPN][检索:魔法姊妹露露特莉莉].mp4",[("Billion Meta Lab", "GROUP"),("魔法姊妹露露莉莉 Mahou no Shimai Rurutto Riryi", "TITLE_MIXED"),("08", "EPISODE"),("1080P", "RESOLUTION"),("CHT&JPN", "SOURCE"),4 unmodified lines"[LoliHouse] Kakuriyo no Yadomeshi Ni - 12 [WebRip 1080p HEVC-10bit AAC SRTx2].mkv",[("LoliHouse", "GROUP"),("Kakuriyo no Yadomeshi", "TITLE_LATIN"),("Ni", "SEASON"),("12", "EPISODE"),("WebRip", "SOURCE"),7 unmodified lines"[LoliHouse] Kakuriyo no Yadomeshi Ni - 13 [WebRip 1080p HEVC-10bit AAC SRTx2].mkv",[("LoliHouse", "GROUP"),("Kakuriyo no Yadomeshi", "TITLE_LATIN"),("Ni", "SEASON"),("13", "EPISODE"),("WebRip", "SOURCE"),7 unmodified lines"[AI-Raws] 炎炎の消防隊 弐ノ章 #13 (BD HEVC 1920x1080 yuv444p10le FLAC)[FC74A2D5].mkv",[("AI-Raws", "GROUP"),("炎炎の消防隊", "TITLE_JPN"),("弐ノ章", "SEASON"),("13", "EPISODE"),("BD", "SOURCE"),6 unmodified lines"[AI-Raws] 炎炎の消防隊 弐ノ章 #01 (BD HEVC 1920x1080 FLAC).mkv",[("AI-Raws", "GROUP"),("炎炎の消防隊", "TITLE_JPN"),("弐ノ章", "SEASON"),("01", "EPISODE"),("BD", "SOURCE"),6 unmodified lines"[DBD-Raws][炎炎消防队 貳之章][01][1080P][BDRip][HEVC-10bit][FLAC]",[("DBD-Raws", "GROUP"),("炎炎消防队", "TITLE_CHS"),("貳之章", "SEASON"),("01", "EPISODE"),("1080P", "RESOLUTION"),5 unmodified lines"[GM-Team][国漫][逆天邪神 第2季][Against the Gods Ⅱ][2026][04][HEVC][GB][4K].mp4",[("GM-Team", "GROUP"),("国漫", "TAG"),("逆天邪神", "TITLE_CHS"),("第2季", "SEASON"),("Against the Gods Ⅱ", "TITLE_LATIN"),("2026", "TAG"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[GM-Team][国漫][剑来 第2季][Sword of Coming Ⅱ][2025][04][HEVC][GB][4K]",[("GM-Team", "GROUP"),("国漫", "TAG"),("剑来", "TITLE_CHS"),("第2季", "SEASON"),("Sword of Coming Ⅱ", "TITLE_LATIN"),("2025", "TAG"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[GM-Team][国漫][大主宰 第2季][The Great Ruler Ⅱ][2026][04][HEVC][GB][4K]",[("GM-Team", "GROUP"),("国漫", "TAG"),("大主宰", "TITLE_CHS"),("第2季", "SEASON"),("The Great Ruler Ⅱ", "TITLE_LATIN"),("2026", "TAG"),("04", "EPISODE"),("HEVC", "SOURCE"),("GB", "SOURCE"),4 unmodified lines"[YYDM&VCB-Studio] Shinsekai Yori [IV05][Ma10p_1080p][x265_aac].mkv",[("YYDM&VCB-Studio", "GROUP"),("Shinsekai Yori", "TITLE_LATIN"),("IV05", "SPECIAL"),("1080p", "RESOLUTION"),("x265_aac", "SOURCE"),3 unmodified lines"[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv",[("YYDM&VCB-Studio", "GROUP"),("Shinsekai Yori", "TITLE_LATIN"),("NCED02", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),2 unmodified linesyield char_item("InuYasha.2000.NCED02.BDrip.AV1.10Bit.DTS.1080p-CalChi",[("InuYasha", "TITLE_LATIN"),("NCED02", "SPECIAL"),("BDrip", "SOURCE"),("AV1", "SOURCE"),5 unmodified lines"[VCB-Studio] Yamada-kun to 7-nin no Majo [NCED][Ma10p_1080p][x265_flac]",[("VCB-Studio", "GROUP"),("Yamada-kun to 7-nin no Majo", "TITLE_LATIN"),("NCED", "SPECIAL"),("1080p", "RESOLUTION"),("x265_flac", "SOURCE"),
19 unmodified lines20212223242519 unmodified lines454647484950515253545552 unmodified lines10810911011111211310 unmodified lines1241251261271281296 unmodified lines13613713813914014126 unmodified lines1681691701711721732 unmodified lines1761771781791801816 unmodified lines18818919019119219319 unmodified linesdef normalize_field_value(field: str, value) -> Optional[str]:if value is None:return Noneif field in {"episode", "season"}:try:return str(int(value))19 unmodified linestokenizer_variant: Optional[str],max_length: Optional[int],constrain_bio: bool,) -> Dict:cfg = Config()tokenizer = load_tokenizer(model_dir, tokenizer_variant)model = load_model(model_dir)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)model.eval()52 unmodified lines"tokenizer_variant": getattr(tokenizer, "tokenizer_variant", "regex"),"max_length": resolved_max_length,"constrain_bio": constrain_bio,"case_count": len(cases),"full_correct": full_correct,"full_accuracy": full_correct / len(cases) if cases else 0.0,10 unmodified linescase_file: str,tokenizer_variant: Optional[str],max_length: Optional[int],) -> Dict:modes = {"model_only": {"constrain_bio": False},6 unmodified linestokenizer_variant=tokenizer_variant,max_length=max_length,constrain_bio=settings["constrain_bio"],)for name, settings in modes.items()}26 unmodified linesparser.add_argument("--output", default=DEFAULT_OUTPUT_FILE, help="JSON output path")parser.add_argument("--mode", choices=["all", "model-only", "normalized-only"], default="all")parser.add_argument("--no-constrained-bio", action="store_true")args = parser.parse_args()if args.mode == "all" and not args.no_constrained_bio:2 unmodified linescase_file=args.case_file,tokenizer_variant=args.tokenizer,max_length=args.max_length,)for name in ("model_only", "normalized_only"):print_metrics(name, metrics["modes"][name])6 unmodified linestokenizer_variant=args.tokenizer,max_length=args.max_length,constrain_bio=constrain_bio,)print_metrics(args.mode, metrics)19 unmodified lines2021222324252627282930313219 unmodified lines52535455565758596061626352 unmodified lines11611711811912012112210 unmodified lines1331341351361371381396 unmodified lines14614714814915015115226 unmodified lines1791801811821831841852 unmodified lines1881891901911921931946 unmodified lines20120220320420520620719 unmodified linesdef normalize_field_value(field: str, value) -> Optional[str]:if value is None:return Noneif isinstance(value, list):normalized_items = [normalize_field_value(field, item)for item in valueif item is not None]return "|".join(item for item in normalized_items if item)if field in {"episode", "season"}:try:return str(int(value))19 unmodified linestokenizer_variant: Optional[str],max_length: Optional[int],constrain_bio: bool,force_cpu: bool = False,) -> Dict:cfg = Config()tokenizer = load_tokenizer(model_dir, tokenizer_variant)model = load_model(model_dir)device = torch.device("cpu" if force_cpu else ("cuda" if torch.cuda.is_available() else "cpu"))model.to(device)model.eval()52 unmodified lines"tokenizer_variant": getattr(tokenizer, "tokenizer_variant", "regex"),"max_length": resolved_max_length,"constrain_bio": constrain_bio,"device": str(device),"case_count": len(cases),"full_correct": full_correct,"full_accuracy": full_correct / len(cases) if cases else 0.0,10 unmodified linescase_file: str,tokenizer_variant: Optional[str],max_length: Optional[int],force_cpu: bool = False,) -> Dict:modes = {"model_only": {"constrain_bio": False},6 unmodified linestokenizer_variant=tokenizer_variant,max_length=max_length,constrain_bio=settings["constrain_bio"],force_cpu=force_cpu,)for name, settings in modes.items()}26 unmodified linesparser.add_argument("--output", default=DEFAULT_OUTPUT_FILE, help="JSON output path")parser.add_argument("--mode", choices=["all", "model-only", "normalized-only"], default="all")parser.add_argument("--no-constrained-bio", action="store_true")parser.add_argument("--cpu", action="store_true", help="Force CPU evaluation")args = parser.parse_args()if args.mode == "all" and not args.no_constrained_bio:2 unmodified linescase_file=args.case_file,tokenizer_variant=args.tokenizer,max_length=args.max_length,force_cpu=args.cpu,)for name in ("model_only", "normalized_only"):print_metrics(name, metrics["modes"][name])6 unmodified linestokenizer_variant=args.tokenizer,max_length=args.max_length,constrain_bio=constrain_bio,force_cpu=args.cpu,)print_metrics(args.mode, metrics)
134 unmodified lines13513613713813914020 unmodified lines1611621631641651669 unmodified lines17617717817918018118218314 unmodified lines1981992002012022032042052066 unmodified lines2132142152162172182192202212223 unmodified lines22622722822923023123245 unmodified lines27827928028128228349 unmodified lines33333433533633733820 unmodified lines35936036136236336436536636736836937037137237337437536 unmodified lines41241341441541641734 unmodified lines45245345445545645745845984 unmodified lines544545546547548549212 unmodified lines762763764765766767153 unmodified lines92192292392492592660 unmodified lines98798898999099199231 unmodified lines10241025102610271028102910301 unmodified line103210331034103510361037103815 unmodified lines10541055105610571058105941 unmodified lines11011102110311041105110632 unmodified lines1139114011411142114311441145114611471148114936 unmodified lines1186118711881189119011911192119311941195119611971198119913 unmodified lines1213121412151216121712181219122012211222122312241225122612271228122912302 unmodified lines1233123412351236123712381239124012411242124353 unmodified lines1297129812991300130113022 unmodified lines1305130613071308130913104 unmodified lines1315131613171318131913203 unmodified lines1324132513261327132813291 unmodified line1331133213331334133513362 unmodified lines1339134013411342134313442 unmodified lines134713481349135013511352415 unmodified lines1768176917701771177217731774177517768 unmodified lines17851786178717881789179017911792179317941795179617971798179918001801180218031804180589 unmodified lines18951896189718981899190019011902190319041905190619074 unmodified lines19121913191419151916191719181 unmodified line19201921192219231924192519268 unmodified lines1935193619371938193919402 unmodified lines1943194419451946194719481949195019511952195319541955195685 unmodified lines204220432044204520462047204820492050205120522053336 unmodified lines239023912392239323942395121 unmodified lines251725182519252025212522252398 unmodified lines2622262326242625262626272628262926304 unmodified lines26352636263726382639264026416 unmodified lines26482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268331 unmodified lines2715271627172718271927202721272227232724272527262727272827292730273127 unmodified lines275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278973 unmodified lines2863286428652866286728682869287028719 unmodified lines2881288228832884288528862887288828896 unmodified lines2896289728982899290029012902107 unmodified lines301030113012301330143015301630174 unmodified lines302230233024302530263027302830293030303130323033303426 unmodified lines30613062306330643065306630671 unmodified line30693070307130723073307430753 unmodified lines307930803081308230833084308520 unmodified lines31063107310831093110311131122 unmodified lines3115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331442 unmodified lines314731483149315031513152131 unmodified lines32843285328632873288328981 unmodified lines3371337233733374337533763377337838 unmodified lines34173418341934203421342234233424342534263427342834293 unmodified lines343334343435343634373438343911 unmodified lines3451345234533454345534563457345834593460346134623463346434653466346730 unmodified lines349834993500350135023503350410 unmodified lines3515351635173518351935203521352235233524352535263527352835293530353135323533353414 unmodified lines35493550355135523553355435553556355735583559356035613562356353 unmodified lines3617361836193620362136223623362436253626362736283629363044 unmodified lines367536763677367836793680368136823683368436853686368727 unmodified lines371537163717371837193720372137223723372437253726372737283729373037312 unmodified lines373437353736373737383739374022 unmodified lines3763376437653766376737683769377012 unmodified lines3783378437853786378737883789379057 unmodified lines3848384938503851385238533854385529 unmodified lines388538863887388838893890389138923893389438953896389738983899390017 unmodified lines39183919392039213922392339243925392639273928392939306 unmodified lines393739383939394039413942394339443945394642 unmodified lines39893990399139923993399439953996399736 unmodified lines4034403540364037403840394040404140424043404423 unmodified lines406840694070407140724073407440754076407740784079408040819 unmodified lines4091409240934094409540964097409815 unmodified lines411441154116411741184119412041219 unmodified lines4131413241334134413541364137413841394140414141424143414411 unmodified lines415641574158415941604161416239 unmodified lines42024203420442054206420742081 unmodified line4210421142124213421442154216421742184219422042214222422372 unmodified lines42964297429842994300430143028 unmodified lines43114312431343144315431643174318431943204321432250 unmodified lines43734374437543764377437843795 unmodified lines43854386438743884389439043914392439343942 unmodified lines43974398439944004401440244034404440512 unmodified lines4418441944204421442244234424442539 unmodified lines446544664467446844694470447149 unmodified lines45214522452345244525452645278 unmodified lines45364537453845394540454145424543454445454546454745484549455045514552455313 unmodified lines456745684569457045714572457345744575457645774578457913 unmodified lines45934594459545964597459845994 unmodified lines4604460546064607460846094610461146121 unmodified line461446154616461746184619462018 unmodified lines463946404641464246434644464516 unmodified lines46624663466446654666466746688 unmodified lines46774678467946804681468246834684468546864687468846894690469143 unmodified lines47354736473747384739474047414742474347444745134 unmodified linesstruct Stats {seen: usize,skipped_encoding_noise: usize,trimmed_parent_path: usize,skipped_no_recipe: usize,skipped_sample_cap: usize,20 unmodified linesSkipped {reason: &'static str,trimmed_parent: bool,},}9 unmodified lines});static EPISODE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}(?:\.\d{1,2})?(?:END)?$").unwrap());static DECIMAL_EPISODE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^\d{1,3}\.\d{1,2}$").unwrap());static NUMERIC_TITLE_PREFIX_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^\d{1,3}(?:[./-]\d{1,3})?$").unwrap());static EPISODE_CJK_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^第?\d{1,4}[话話回集]$").unwrap());14 unmodified lines});static CJK_SEASON_TOKEN_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^第[一二三四五六七八九十\d]+[季期部]$").unwrap());static CJK_SEASON_EMBEDDED_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"^(.+?)(第[一二三四五六七八九十\d]+[季期部])(.{0,12})$").unwrap()});static CJK_EPISODE_EMBEDDED_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(.+?)(第?\d{1,4}[话話回集])(.{0,32})$").unwrap());static CJK_TITLE_TRAILING_EPISODE_RE: Lazy<Regex> =6 unmodified linesRegex::new(r"(?i)^(?:First|Second|Third|Fourth|Fifth|Sixth|Seventh|Eighth|Ninth|Tenth)$").unwrap()});static SEASON_WORD_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"(?i)^(?:Season|Saison)$").unwrap());static CJK_TITLE_LANG_PREFIX_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(.+?)(国日双语|國日雙語|日语版|日語版|国语版|國語版|双语|雙語)(第?)$").unwrap());static SEASON_VALUE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^S(\d{1,2})$").unwrap());static SPECIAL_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"(?i)^(?:(?:NCOP|NCED|OP|ED|PV|CM)(?:[\s_.-]?(?:\d{1,4}|v\d{1,3}|[A-Z]))?|SP(?:[\s_.-]?\d{0,4})?|(?:OVA|OAD|IV)(?:[\s_.-]?\d{0,4})?|(?:BD)?Menu(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?|(?:BD[-_. ]?)?Spot(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?|(?:Intro|Preview|Trailer|Teaser|Animatics?)(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?)$").unwrap()3 unmodified linesstatic DATE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}$").unwrap());static DATE_RANGE_MIXED_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"^(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}\s*[-~]\s*(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}$").unwrap()});static CJK_DATE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(?:19|20)\d{2}年\d{1,2}月\d{1,2}日$").unwrap());45 unmodified linesstatic SIMPLE_EPISODE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}$").unwrap());static SPECIAL_SPACE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\s_.-]+").unwrap());fn main() -> Result<()> {let args = Args::parse();49 unmodified lineslet mut label_counts: HashMap<String, usize> = HashMap::new();let mut template_counts: HashMap<String, usize> = HashMap::new();let mut examples = Vec::new();let mut writer = BufWriter::new(File::create(&args.output)?);for item in processed {match item {20 unmodified linesProcessed::Skipped {reason,trimmed_parent,} => {if trimmed_parent {stats.trimmed_parent_path += 1;}match reason {"encoding_noise" => stats.skipped_encoding_noise += 1,"no_recipe" => stats.skipped_no_recipe += 1,"sample_cap" => stats.skipped_sample_cap += 1,"role_mismatch" => stats.skipped_role_mismatch += 1,"low_frequency_audit_warning" => {stats.skipped_low_frequency_audit_warning += 1}_ => {}}36 unmodified lines"label_counts": label_counts,"top_template_counts": top_template_counts,"examples": examples,"implementation": "rust_dmhy_template_apply"});fs::write(34 unmodified linesif !path.exists() {return Ok(Vec::new());}let file = File::open(path).with_context(|| format!("failed to open whitelist {}", path.display()))?;let mut lines = Vec::new();for line in BufReader::new(file).lines() {let line = line?;84 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(&original)|| has_non_anime_noise(&original)|| has_abstract_path_noise(&original)){skipped_encoding_noise += 1;212 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(&original)|| has_non_anime_noise(&original)|| has_abstract_path_noise(&original)){continue;153 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(original)|| has_non_anime_noise(original)|| has_abstract_path_noise(original)){return None;60 unmodified lineslet (key, tokens, _classes, groups) = template_key_for_filename(segment);let suggested = suggested_roles(&key);let roles = adjust_contextual_roles(&tokens, &groups, &suggested);let candidates = rich_candidates_for_segment(segment, &tokens, &groups, &roles, is_leaf);json!({"index": index,31 unmodified linescontinue;}output.push(json!({"role": fine_title_role(segment, &text, is_leaf, candidate_index, title_ranges.len()),"coarse_role": "TITLE","text": text,"group_start": start,1 unmodified line}));}for (group_index, role) in roles.iter().enumerate() {if role == "TITLE" || role == "O" || role == "HASH" {continue;}let text = group_text(tokens, &groups[group_index]);15 unmodified linesoutput}fn candidate_text(tokens: &[String], groups: &[Group], start: usize, end: usize) -> String {let Some(first) = groups.get(start).and_then(|group| group.indices.first()) else {return String::new();41 unmodified lines"GROUP" => "RELEASE_GROUP","EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" => "EPISODE","SEASON" => "SEASON","SPECIAL" | "VOLUME" => "SPECIAL","RESOLUTION" => "RESOLUTION","SOURCE" => "SOURCE",32 unmodified linesfn audit_warnings(record: &Record) -> Vec<String> {let mut warnings = Vec::new();let title_texts = entity_texts(&record.tokens, &record.labels, "TITLE");let title_spans = title_texts.len();if title_spans == 0 {warnings.push("no_title".to_string());} else if title_spans > 1 {warnings.push("multiple_title_spans".to_string());}if !title_texts.is_empty() && title_texts.iter().all(|title| generic_title_text(title)) {36 unmodified lineswarnings.push("encoding_noise_survived".to_string());}for (index, token) in record.tokens.iter().enumerate() {let entity = record.labels.get(index).and_then(|label| label_entity(label));let cleaned = strip_wrapper(token);if HASH_RE.is_match(token) && record.labels.get(index).is_some_and(|label| label != "O") {warnings.push("hash_labeled".to_string());break;}if EPISODE_VERSION_RE.is_match(&compact_for_classify(&cleaned))&& entity != Some("EPISODE"){warnings.push("episode_version_missing_label".to_string());}13 unmodified lines.or_else(|| label.strip_prefix("I-"))}fn entity_texts(tokens: &[String], labels: &[String], target: &str) -> Vec<String> {let mut spans = Vec::new();let mut current = String::new();for (token, label) in tokens.iter().zip(labels.iter()) {let entity = label_entity(label);if entity == Some(target) {current.push_str(token);} else if !current.trim().is_empty() {spans.push(current.trim().to_string());current.clear();} else {current.clear();}}if !current.trim().is_empty() {2 unmodified linesspans}fn generic_title_text(text: &str) -> bool {matches!(text.trim().to_ascii_lowercase().as_str(),"tv"| "movie"| "mov"| "sample"| "commercial"53 unmodified linesrecipes: &HashMap<String, Recipe>,sample_counters: &HashMap<String, AtomicUsize>,) -> Processed {if !args.keep_encoding_noise&& (has_encoding_noise(original)|| has_non_anime_noise(original)2 unmodified linesreturn Processed::Skipped {reason: "encoding_noise",trimmed_parent: false,};}let (training_filename, trimmed_parent) = training_filename_for(original);4 unmodified linesreturn Processed::Skipped {reason: "no_recipe",trimmed_parent,}}};3 unmodified linesreturn Processed::Skipped {reason: "sample_cap",trimmed_parent,};}}1 unmodified linereturn Processed::Skipped {reason: "role_mismatch",trimmed_parent,};}let mut record = match dmhy_record(&training_filename, &recipe.template_id, &recipe.roles) {2 unmodified linesreturn Processed::Skipped {reason: "role_mismatch",trimmed_parent,}}};2 unmodified linesreturn Processed::Skipped {reason: "low_frequency_audit_warning",trimmed_parent,};}if trimmed_parent {415 unmodified linesroles}fn filename_has_title(filename: &str) -> bool {let (key, _, _, _) = template_key_for_filename(filename);suggested_roles(&key).iter().any(|role| role == "TITLE")}fn training_filename_for(original: &str) -> (String, bool) {8 unmodified lines&& path_segment_starts_with_episode(parts[parts.len() - 1])&& !leaf_has_full_title_after_episode(parts[parts.len() - 1]))){if let Some(parent) = parts[..parts.len() - 1].iter().rev().find(|part| {let trimmed = trim_parent_title_segment(part);filename_has_title(&trimmed) && !path_segment_is_media_noise(&trimmed)}){let parent = trim_parent_title_segment(parent.trim());return (format!("{} {}",parent,parts[parts.len() - 1].trim()),true,);}89 unmodified linesreturn true;}let markers = ["譁", "蜈", "螟", "蟄", "謇", "邱", "荳", "縺", "繧", "莨", "鬆", "髯", "瀛","楀", "箷", "绲", "刔", "鏃", "湪", "鏍", "犲", "儚", "鐗", "吀", "铦", "躲","伄", "椋", "伓", "姘", "帽", "娆", "洖", "浜", "堝", "澶", "湴", "鐒","銇", "銈", "銉", "偅", "偗", "儱", "儫", "兗", "仧", "鏉变", "鍠靛","銉熴", "銈︺", "瀵掕", "潐楦", "常涔", "涓歖", "缁堟", "湯鍒","瀵诲", "線浣", "曟柟", "瓒呴", "绁炪", "偘銉", "兇銈", "銉砡","銉砕", "杩风", "硦澶", "銇淬", "仧銉", "銉嗐", "偅銈", "銈躲",];let marker_hits = markers.iter()4 unmodified lines.filter(|ch| ('\u{ff61}'..='\u{ff9f}').contains(ch)).count();let latin_mojibake = value.split_whitespace().any(|part| {part.chars().any(|ch| matches!(ch, '帽' | '茅' | '脳' | '锛'))&& part.chars().any(|ch| ch.is_ascii_alphabetic())});marker_hits >= 2 || (marker_hits >= 1 && halfwidth_hits >= 1) || latin_mojibake1 unmodified linefn has_non_anime_noise(value: &str) -> bool {let normalized = value.replace('\\', "/").trim().to_ascii_lowercase();normalized == "mtv" || normalized.starts_with("mtv/") || normalized.contains("/mtv/")|| value.contains("[旅游")|| value.contains("[旅游番")|| normalized.contains("tokyo deep")8 unmodified lines.to_ascii_lowercase()}fn path_segment_is_episodeish(value: &str) -> bool {let (_, _, _, groups) = template_key_for_filename(value);let structural: Vec<&String> = groups2 unmodified lines.filter(|item| item.as_str() != "SEP").collect();!structural.is_empty()&& structural.iter().all(|item| {item.starts_with("EPISODE")|| item.as_str() == "SPECIAL"|| item.as_str() == "VOLUME"|| item.as_str() == "BRACKET_VOLUME"})}fn path_segment_starts_with_episode(value: &str) -> bool {85 unmodified linesfn role_label(role: &str) -> String {let entity = match role {"GROUP" => Some("GROUP"),"TITLE" => Some("TITLE"),"EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" => Some("EPISODE"),"SEASON" => Some("SEASON"),"SPECIAL" | "VOLUME" => Some("SPECIAL"),"RESOLUTION" => Some("RESOLUTION"),"SOURCE" => Some("SOURCE"),_ => None,};entity.map_or_else(|| "O".to_string(), |entity| format!("B-{entity}"))336 unmodified lines|| normalized.contains("字幕組")}const KNOWN_TITLE_PHRASES: &[&[&str]] = &[&["SPY", "x", "FAMILY"],&["Spy", "x", "Family"],121 unmodified lines});if !first_is_known_group {if let Some(groupish_index) = (1..groups.len()).find(|&index| {output[index] == "TITLE" && looks_like_release_group(&group_text(tokens, &groups[index]))}) {output[0] = "TITLE".to_string();output[groupish_index] = "GROUP".to_string();98 unmodified lines}if roles[index].starts_with("EPISODE")&& index >= 2&& matches!(group_text(tokens, &groups[index - 1]).as_str(), "×" | "x" | "X")&& output[index - 2] == "TITLE"&& !roles[index + 1..].iter().any(|role| role.starts_with("EPISODE")){output[index] = "TITLE".to_string();if let Some(next_text_index) = (index + 1..roles.len()).find(|&cursor| {4 unmodified linescontinue;}if roles[index].starts_with("EPISODE")&& !output[..index].iter().any(|role| role.starts_with("EPISODE"))&& group_text(tokens,&groups[(0..index)6 unmodified linesoutput[index] = "TITLE".to_string();continue;}if output[index] == "TITLE"&& matches!(text.as_str(), "中日" | "日中" | "英日" | "日英"){let next_source_lang = (index + 1..roles.len()).find(|&cursor| groups[cursor].class_name != "SEP").is_some_and(|cursor| {output[cursor] == "SOURCE"&& group_text(tokens, &groups[cursor]).contains('语')});if next_source_lang {output[index] = "SOURCE".to_string();continue;}}if roles[index].starts_with("EPISODE")&& index >= 1&& output[index - 1] == "TITLE"&& groups[index - 1].class_name != "SEP"&& text.chars().all(|ch| ch.is_ascii_digit())&& (text.len() <= 2|| (text.len() <= 3&& group_text(tokens, &groups[index - 1]).chars().any(|ch| !ch.is_ascii())&& !group_text(tokens, &groups[index - 1]).ends_with('第')))&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE")){output[index] = "TITLE".to_string();continue;}if roles[index].starts_with("EPISODE") && (2..roles.len()).contains(&index) {31 unmodified lines&& output[index - 1] == "TITLE"&& groups[index - 1].class_name != "SEP"&& text.chars().all(|ch| ch.is_ascii_digit())&& (text.len() <= 2|| (text.len() <= 3&& group_text(tokens, &groups[index - 1]).chars().any(|ch| !ch.is_ascii())&& !group_text(tokens, &groups[index - 1]).ends_with('第')))&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE")){output[index] = "TITLE".to_string();continue;}if !output[..index].iter().any(|role| role == "TITLE")27 unmodified lines&& previous_text.len() <= 48&& previous_text.chars().any(|ch| ch.is_alphabetic())&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 3&& !(index + 2 < roles.len()&& groups[index + 1].class_name == "SEP"&& group_text(tokens, &groups[index + 2]).eq_ignore_ascii_case("episode"))&& (next_episode|| (next_special&& (text.parse::<u16>().is_ok_and(|value| value >= 100)|| (previous_text.len() <= 4&& previous_text.is_ascii()&& previous_text.chars().all(|ch| ch.is_ascii_alphabetic()))))){output[index] = "TITLE".to_string();continue;}}if roles[index].starts_with("EPISODE")&& (text.chars().all(|ch| ch.is_ascii_digit())|| matches!(classify_atom(&text).as_str(),"EPISODE" | "EPISODE_VERSION"))&& output[..index].iter().any(|role| role == "SPECIAL")&& !output[..index].iter().any(|role| role.starts_with("EPISODE")){let previous_structural = (0..index).rev()73 unmodified lines}if roles[index] == "TITLE"&& matches!(text.to_ascii_uppercase().as_str(), "TV" | "TV版")&& output.iter().enumerate().any(|(other, role)| {other != index && role == "TITLE"}){output[index] = "O".to_string();continue;9 unmodified linescontinue;}if output[index] == "TITLE" && text.eq_ignore_ascii_case("Creditless") {let later_special = output[index + 1..].iter().any(|role| role == "SPECIAL");if later_special {output[index] = "SPECIAL".to_string();continue;6 unmodified lines}if output[index] == "O"&& groups[index].class_name == "TEXT"&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE"))&& text.chars().any(|ch| ch.is_alphabetic())&& !ep_markers.contains(&text.as_str()){107 unmodified linesif matches!(previous_real_text.to_ascii_lowercase().as_str(),"lesson" | "part" | "no"){output[index] = "O".to_string();continue;}4 unmodified linescontinue;}if output[..index].iter().any(|role| role == "TITLE")&& (output[..index].iter().enumerate().any(|(cursor, role)| {role == "TITLE" && is_special_title_phrase(&group_text(tokens, &groups[cursor]))}))&& !output[..index].iter().any(|role| role.starts_with("EPISODE"))&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 3{26 unmodified lineslet mut candidates = Vec::new();let mut index = 0;while index < roles.len() {if roles[index] != "TITLE" {index += 1;continue;}1 unmodified lineindex += 1;loop {if index < roles.len()&& roles[index] == "TITLE"&& !(groups[index - 1].class_name == "BRACKET_TEXT"&& groups[index].class_name == "BRACKET_TEXT"){3 unmodified linesif index + 1 < roles.len()&& roles[index] == "O"&& groups[index].class_name == "SEP"&& roles[index + 1] == "TITLE"{index += 2;continue;20 unmodified linesrole.starts_with("EPISODE")|| matches!(role.as_str(),"SEASON" | "SPECIAL" | "SOURCE" | "RESOLUTION")}).unwrap_or(roles.len());2 unmodified lines.copied().filter(|(_, end)| *end <= first_anchor).collect();let selected_pool = if before_anchor.is_empty() {&candidates} else {&before_anchor};let selected = selected_pool.iter().max_by_key(|(start, end)| {(title_candidate_score(tokens, groups, *start, *end),*end,end - start,)}).copied().unwrap();let mut output = roles.to_vec();let mut dropped = Vec::new();for (start, end) in candidates {if (start, end) == selected {continue;}for index in start..end {if output[index] == "TITLE" {output[index] = "O".to_string();dropped.push(index.to_string());}2 unmodified lines(output, dropped)}fn title_candidate_score(tokens: &[String], groups: &[Group], start: usize, end: usize) -> isize {let text = (start..end).filter(|&index| roles_candidate_text_group(&groups[index]))131 unmodified linesif let Some(caps) = CJK_TITLE_TRAILING_EPISODE_RE.captures(&piece) {let before = caps.get(1).map(|m| m.as_str()).unwrap_or_default();let episode = caps.get(2).map(|m| m.as_str()).unwrap_or_default();if !before.is_empty() {output_pieces.push(before.to_string());labels.push("B-TITLE".to_string());81 unmodified lines| "SOURCE"| "RESOLUTION"| "SEASON") {if role == "SEASON" {if let Some((pieces, labels)) = split_season_token(token) {output_tokens.extend(pieces);output_labels.extend(labels);38 unmodified linesoutput_labels.extend(labels);}} else {if role == "TITLE" && matches!(token.as_str(), "第" | "話" | "话" | "回" | "集"){output_tokens.push(token.clone());output_labels.push("O".to_string());continue;}if role == "TITLE" && token.ends_with('第') && token.chars().count() > 1 {let trimmed = token.trim_end_matches('第').to_string();let (pieces, labels) = normalize_generated_tokens(&[trimmed, "第".to_string()],3 unmodified linesoutput_labels.extend(labels);continue;}if role == "TITLE" {let (pieces, labels) = normalize_title_token(token);output_tokens.extend(pieces);output_labels.extend(labels);11 unmodified linesfn smooth_title_spans(tokens: &[String], labels: &[String]) -> Vec<String> {let joiners = [" ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":", ":", "!", "!", "?","?", ";", ";", ",", ",", "、", "。", "~", "~", "-", "+", "+", "(", ")","(", ")", "[", "]", "【", "】", "<", ">", "<", ">", "「", "」", "「", "」", "《", "》","☆", "♪", "`", "@", "‐", "‑", "–", "—", "−", "$", "$", "∽", "꞉", "♥",];let title_terminal_punctuation = ["!", "!", "?", "?"];let entity_joiners = [" ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":", ":", "!", "!", "?","?", ";", ";", ",", ",", "、", "。", "~", "~", "-", "+", "+", "(", ")","(", "���", "[", "]", "【", "】", "<", ">", "<", ">", "「", "」", "「", "」", "《", "》","☆", "♪", "`", "@", "&", "&", "‐", "‑", "–", "—", "−", "$", "$", "∽", "꞉", "♥",];let mut output = labels.to_vec();for (index, (token, label)) in tokens.iter().zip(labels.iter()).enumerate() {30 unmodified lines.any(|item| item.eq_ignore_ascii_case("lupin"));if nearby_lupin&& next_number.is_some_and(|cursor| {tokens[cursor].chars().all(|ch| ch.is_ascii_digit()) && tokens[cursor].len() <= 2}){output[index] = "B-SEASON".to_string();10 unmodified lineslet mut cursor = index + 1;while cursor < tokens.len() {output[cursor] = "O".to_string();if matches!(tokens[cursor].as_str(), "」" | "」" | "\"" | "'") && cursor > index + 1 {break;}cursor += 1;}continue;}if label == "B-TITLE" && matches!(token.as_str(), "中日" | "日中" | "英日" | "日英") {let next_word = (index + 1..tokens.len()).find(|&cursor| {tokens[cursor].chars().any(|ch| ch.is_alphanumeric())});if next_word.is_some_and(|cursor| {labels[cursor] == "B-SOURCE" && tokens[cursor].contains('语')}) {output[index] = "B-SOURCE".to_string();continue;}14 unmodified lines.chars().any(|ch| ch.is_alphanumeric() || ('\u{4e00}'..='\u{9fff}').contains(&ch))});let later_episode = (index + 1..tokens.len()).any(|cursor| labels[cursor] == "B-EPISODE");if previous_title_word.is_none() && later_episode {output[index] = "B-SEASON".to_string();continue;}let previous_word = previous_title_word.map(|cursor| tokens[cursor].to_ascii_lowercase());if previous_title_word.is_some()&& !matches!(previous_word.as_deref(), Some("lupin")){output[index] = "B-SEASON".to_string();continue;}53 unmodified linescontinue;}if previous_non_space.is_some_and(|cursor| tokens[cursor] == "第")&& next_non_space.is_some_and(|cursor| {matches!(tokens[cursor].as_str(), "话" | "話" | "回" | "集")|| tokens[cursor].starts_with('话')|| tokens[cursor].starts_with('話')|| tokens[cursor].starts_with('回')|| tokens[cursor].starts_with('集')}){if let Some(cursor) = previous_non_space {output[cursor] = "B-EPISODE".to_string();44 unmodified lineslet followed_by_title_word = (index + 1..tokens.len()).find(|&cursor| {!joiners.contains(&tokens[cursor].as_str())&& !matches!(tokens[cursor].as_str(), "-" | "-" | "," | "," | ":" | ":")}).is_some_and(|cursor| {!matches!(tokens[cursor].as_str(), "[" | "【" | "(" | "(" | "]" | "】")&& output.get(cursor).is_some_and(|label| label == "B-TITLE")&& tokens[cursor].chars().any(|ch| ch.is_alphabetic())});if followed_by_title_word && matches!(previous_word.as_deref(), Some("movie" | "part"))27 unmodified linescontinue;}}if label == "O"&& token.chars().all(|ch| ch.is_ascii_digit())&& token.len() <= 3{let previous_non_space = (0..index).rev().find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));let next_non_space = (index + 1..tokens.len()).find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));if previous_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "[" | "【"))&& next_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "]" | "】"))&& output[..index].iter().any(|label| label == "B-TITLE")&& output[index + 1..].iter()2 unmodified linesoutput[index] = "B-EPISODE".to_string();continue;}if previous_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "-" | "-"))&& output[..index].iter().any(|label| label == "B-TITLE")&& output[index + 1..].iter()22 unmodified lineslet next_non_space = (index + 1..tokens.len()).find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));if previous_non_space.is_some_and(|cursor| tokens[cursor] == "第")&& next_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "话" | "話" | "回" | "集")){if let Some(cursor) = previous_non_space {output[cursor] = "B-EPISODE".to_string();12 unmodified linesif left_title {output[index] = "B-TITLE".to_string();if let Some(next_word) = (index + 1..tokens.len()).find(|&cursor| {labels[cursor] == "O"&& tokens[cursor].chars().any(|ch| ch.is_alphabetic())}) {output[next_word] = "B-TITLE".to_string();}57 unmodified linesoutput[index] = "B-TITLE".to_string();}}if matches!(token.as_str(), "]" | "】" | ")" | ")" | ">" | ">" | "」" | "」")&& index > 0&& output[index - 1] == "B-TITLE"&& title_span_has_labeled_opener(&tokens[..index], &output[..index], token){29 unmodified lines)}fn dmhy_record(filename: &str, template_id: &str, roles: &[String]) -> Option<Record> {let (key, tokens, _classes, groups) = template_key_for_filename(filename);if groups.len() != roles.len() {return None;}let roles = adjust_contextual_roles(&tokens, &groups, roles);let (roles, dropped) = enforce_single_title_candidate(&tokens, &groups, &roles);let (tokens, labels) = project_refined_tokens(&tokens, &groups, &roles);let (tokens, labels) = repair_compact_sxe_tokens(tokens, labels);let labels = smooth_title_spans(&tokens, &labels);if tokens.len() != labels.len() {return None;}17 unmodified linesmod tests {use super::*;fn labels_for(filename: &str) -> Vec<(String, String)> {let (key, _, _, _) = template_key_for_filename(filename);let roles = suggested_roles(&key);let record = dmhy_record(filename, "tpl_test", &roles).unwrap();record.tokens.into_iter().zip(record.labels).collect()}#[test]fn rich_title_candidates_keep_readable_spacing() {let row = rich_annotation_for(6 unmodified lines);}#[test]fn required_regressions() {let title_91 = labels_for("Title 91 EP 01 [1080p]");assert!(title_91.contains(&("91".to_string(), "B-TITLE".to_string())));assert!(title_91.contains(&("EP".to_string(), "O".to_string())));assert!(title_91.contains(&("01".to_string(), "B-EPISODE".to_string())));42 unmodified linesassert!(!episode_version_title.contains(&("10v2".to_string(), "B-TITLE".to_string())));let episode_version_lang =labels_for("[GalaxyRailroad-888] Yu-Gi-Oh! GO RUSH !! [043v2_GB]");assert!(episode_version_lang.contains(&("043v2".to_string(), "B-EPISODE".to_string())));assert!(episode_version_lang.contains(&("GB".to_string(), "B-SOURCE".to_string())));let cursed = labels_for("[Coalgirls]_C3-Cube_x_Cursed_x_Curious_01_[8E416230]");36 unmodified lineslet music_title =labels_for("[アニメ BD] うたの☆プリンスさまっ♪ マジLOVE2000% 第01話「ポワゾンKISS」(1920x1080 x264 Hi10p AAC)");assert!(music_title.contains(&("♪".to_string(), "B-TITLE".to_string())));let cm_version = labels_for("[U2-Rip]Inari, Konkon, Koi Iroha[CMv2][Hi10p_1080p][x264_flac]");assert!(cm_version.contains(&("CMv2".to_string(), "B-SPECIAL".to_string())));assert!(!cm_version.contains(&("CMv2".to_string(), "B-TITLE".to_string())));let hdma_block =labels_for("[Niconeiko Works] Gekijouban Violet Evergarden [1080P_Ma10p_DTS-HDMA][CM01]");assert!(hdma_block.contains(&("Gekijouban".to_string(), "B-TITLE".to_string())));assert!(hdma_block.contains(&("1080P".to_string(), "B-RESOLUTION".to_string())));assert!(hdma_block.contains(&("HDMA".to_string(), "B-SOURCE".to_string())));23 unmodified linesassert!(!zom.contains(&("100".to_string(), "B-EPISODE".to_string())));assert!(zom.contains(&("Animatics02".to_string(), "B-SPECIAL".to_string())));let sky = labels_for("[Skytree][海贼王][One_Piece][918][GB_JP][1080P]");assert!(sky.contains(&("One".to_string(), "B-TITLE".to_string())));assert!(!sky.contains(&("海贼王".to_string(), "B-TITLE".to_string())));assert!(sky.contains(&("918".to_string(), "B-EPISODE".to_string())));let happy = labels_for("My.Happy.Marriage.S01E01.The.Meeting.1080p.NF.WEB-DL.AAC2.0.H.264-VARYG",);assert!(happy.contains(&("01".to_string(), "B-SEASON".to_string())));assert!(happy.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!happy.contains(&("0".to_string(), "B-EPISODE".to_string())));9 unmodified linesassert!(!akira.contains(&("AVC".to_string(), "B-TITLE".to_string())));assert!(akira.contains(&("AVC".to_string(), "B-SOURCE".to_string())));let doraemon =labels_for("[DORASUB][DORAEMON1979][1998.03.07][WEB][1998x1080][AVC][简日]哆啦A梦归来了");assert!(doraemon.contains(&("DORAEMON1979".to_string(), "B-TITLE".to_string())));assert!(doraemon.contains(&("WEB".to_string(), "B-SOURCE".to_string())));assert!(!doraemon.contains(&("WEB".to_string(), "B-TITLE".to_string())));15 unmodified linesassert!(bang_season.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!bang_season.contains(&("01".to_string(), "B-SEASON".to_string())));let basket =labels_for("[Nekomoe kissaten&VCB-Studio] Fruits Basket 1st Season [24][1080p][x264_aac][sc]");assert!(basket.contains(&("Fruits".to_string(), "B-TITLE".to_string())));assert!(basket.contains(&("1st".to_string(), "B-SEASON".to_string())));assert!(basket.contains(&("Season".to_string(), "B-SEASON".to_string())));9 unmodified linesassert!(full.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!full.contains(&("01".to_string(), "B-TITLE".to_string())));let r18 = labels_for("[HYSUB]Skirt no Naka wa Kedamono Deshita.[01_R18][BIG5_MP4][1280X720]");assert!(r18.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!r18.contains(&("01".to_string(), "B-TITLE".to_string())));let ddp = labels_for("Akuma.Kun.S01E02.1080p.NF.WEB-DL.DDP5.1.H.264");assert!(ddp.contains(&("02".to_string(), "B-EPISODE".to_string())));assert!(!ddp.contains(&("1".to_string(), "B-EPISODE".to_string())));assert!(ddp.iter().any(|(token, label)| token.starts_with("DDP") && label == "B-SOURCE"));let aac_space = labels_for("Bleach S01E02 AAC 2.0 H.264");assert!(aac_space.contains(&("02".to_string(), "B-EPISODE".to_string())));11 unmodified linesassert!(air_episode.contains(&("Air".to_string(), "B-TITLE".to_string())));assert!(air_episode.contains(&("01".to_string(), "B-EPISODE".to_string())));let decimal_episode = labels_for("[HoneyGod] Usagi Drop [02.5][x264_10bit][粤日双语][BDrip_1080p]");assert!(decimal_episode.contains(&("02".to_string(), "B-EPISODE".to_string())));assert!(decimal_episode.contains(&(".".to_string(), "B-EPISODE".to_string())));assert!(decimal_episode.contains(&("5".to_string(), "B-EPISODE".to_string())));39 unmodified linesassert!(gundam.contains(&("00".to_string(), "B-TITLE".to_string())));assert!(gundam.contains(&("01".to_string(), "B-EPISODE".to_string())));let spy = labels_for("[Studio GreenTea] Spy x Family [38][WebRip][HEVC-10bit 1080p AAC ASSx2]");assert!(spy.contains(&("Studio".to_string(), "B-GROUP".to_string())));assert!(spy.contains(&("Spy".to_string(), "B-TITLE".to_string())));assert!(spy.contains(&("x".to_string(), "B-TITLE".to_string())));1 unmodified lineassert!(spy.contains(&("38".to_string(), "B-EPISODE".to_string())));assert!(!spy.contains(&("Spy".to_string(), "B-SPECIAL".to_string())));let spy_s3 = labels_for("[Feibanyama] SPY x FAMILY S3 - 01 [IQIYI WebRip 2160p HEVC-10bit OPUS Multi-Subs]");assert!(spy_s3.contains(&("Feibanyama".to_string(), "B-GROUP".to_string())));assert!(spy_s3.contains(&("SPY".to_string(), "B-TITLE".to_string())));assert!(spy_s3.contains(&("FAMILY".to_string(), "B-TITLE".to_string())));assert!(spy_s3.contains(&("3".to_string(), "B-SEASON".to_string())));assert!(spy_s3.contains(&("01".to_string(), "B-EPISODE".to_string())));let slime = labels_for("[Nekomoe kissaten&VCB-Studio] Slime 300 [Menu01][Ma10p_1080p][x265_flac]");assert!(slime.contains(&("Slime".to_string(), "B-TITLE".to_string())));assert!(slime.contains(&("300".to_string(), "B-TITLE".to_string())),72 unmodified linesassert!(was_trimmed);assert_eq!(trimmed, "Avatar The Last Airbender S2 14 [1080p]");let plain_season_dir = "Season 1/[Kamigami] Junjou Romantica 1 - 01 [BD 1280x720 x264 AAC Sub(Chs,Jap)]";let (trimmed, was_trimmed) = training_filename_for(plain_season_dir);assert!(was_trimmed);assert_eq!(8 unmodified lines"[Airota&ANK-Raws] 亜人ちゃんは語りたい (BDrip 1920x1080 HEVC-YUV420P10 FLAC SUP)/Menu (Vol.1)";let (trimmed, was_trimmed) = training_filename_for(menu_parent);assert!(was_trimmed);assert_eq!(trimmed, "[Airota&ANK-Raws] 亜人ちゃんは語りたい Menu (Vol.1)");assert!(has_encoding_noise("[4K_SDR][DBD-Raws&HKG瀛楀箷绲刔[鏃ュ湪鏍″湌][01][2160P]"));assert!(has_encoding_noise("ATRI -My Dear Moments-/娆″洖浜堝憡 EP01 Log01"));assert!(has_encoding_noise("[2002-2003] Mew Mew_鏉变含鍠靛柕(鏉变含銉熴儱銈︺儫銉ャ偊)_TV"));50 unmodified lines"Season 4 E07 - The New Woody Woodpecker Show (Season 1-4) (1999-2002) WEB-DL 720p");let najica = "[2001] Najica_七虹香電擊作戰(ナジカ電撃作戦)_TV/SourceUnknown.RMVB.640x480.twHard/01";let (trimmed, was_trimmed) = training_filename_for(najica);assert!(was_trimmed);assert_eq!(trimmed, "[2001] Najica_七虹香電擊作戰(ナジカ電撃作戦) 01");5 unmodified lineslet galient = "[1984-1986] Galient_機甲界(機甲界ガリアン)_TV.OVA/[1984-1985] Galient_機甲界(機甲界ガリアン)_TV/DVDRip.MKV.720x480.ruSub.左右黑邊保留/01";let (trimmed, was_trimmed) = training_filename_for(galient);assert!(was_trimmed);assert_eq!(trimmed,"[1984-1985] Galient_機甲界(機甲界ガリアン) 01");let galient_labels = labels_for(&trimmed);assert!(galient_labels.contains(&("Galient".to_string(), "B-TITLE".to_string())));assert!(!galient_labels.contains(&("TV".to_string(), "B-TITLE".to_string())));2 unmodified lineslet nced = "[BDrip] Ao no Exorcist Yuki no Hate Hen S04 [343-Labs]/NCED";let (trimmed, was_trimmed) = training_filename_for(nced);assert!(was_trimmed);assert_eq!(trimmed, "[BDrip] Ao no Exorcist Yuki no Hate Hen S04 [343-Labs] NCED");let sakura = "Card Captor Sakura Chinese/魔卡少女樱(台配国语)/第01集 小樱与不可思议的魔法书";let (trimmed, was_trimmed) = training_filename_for(sakura);assert!(was_trimmed);assert_eq!(12 unmodified linesassert!(volume.contains(&("MENU02".to_string(), "B-SPECIAL".to_string())));assert!(!volume.contains(&("01".to_string(), "B-EPISODE".to_string())));let aria_notice =labels_for("[KNA-Subs&ANK-Raws] 緋弾のアリアAA 番宣1 (BDrip 1920x1080 HEVC-YUV420P10 FLAC)");assert!(aria_notice.contains(&("緋弾のアリア".to_string(), "B-TITLE".to_string())));assert!(aria_notice.contains(&("番宣".to_string(), "B-SPECIAL".to_string())));assert!(aria_notice.contains(&("1".to_string(), "B-SPECIAL".to_string())));39 unmodified linesassert!(!mahoro.contains(&("Full".to_string(), "B-TITLE".to_string())));assert!(mahoro.contains(&("01".to_string(), "B-EPISODE".to_string())));let kitaro = labels_for("[1985.10-1988.02] Kitaro_鬼太郎 第3期(ゲゲゲの鬼太郎)_TV 036 異次元妖怪かまなり");assert!(kitaro.contains(&("Kitaro".to_string(), "B-TITLE".to_string())));assert!(kitaro.contains(&("3".to_string(), "B-SEASON".to_string())));assert!(kitaro.contains(&("036".to_string(), "B-EPISODE".to_string())));49 unmodified linesassert!(ghiblies.contains(&("2".to_string(), "B-TITLE".to_string())));assert!(!ghiblies.contains(&("2".to_string(), "B-EPISODE".to_string())));let tv_spot = labels_for("[RUELL-Next] Fruits Basket TV Spot 1 (DVD 768x576 x264 AAC) [49531416]");assert!(tv_spot.contains(&("TV".to_string(), "B-SPECIAL".to_string())));assert!(tv_spot.contains(&("1".to_string(), "B-SPECIAL".to_string())));assert!(!tv_spot.contains(&("1".to_string(), "B-EPISODE".to_string())));8 unmodified linesassert!(hi10_source.contains(&("Hi10".to_string(), "B-SOURCE".to_string())));assert!(!hi10_source.contains(&("Hi10".to_string(), "B-GROUP".to_string())));let souten =labels_for("[苍天之拳].[Fosky_Fansub][Souten_No_Ken][DVDRIP][01][H.264_FLAC][848x480][CDD495FC]");assert!(souten.contains(&("Fosky".to_string(), "B-GROUP".to_string())));assert!(!souten.contains(&("苍天之拳".to_string(), "B-GROUP".to_string())));assert!(souten.contains(&("Souten".to_string(), "B-TITLE".to_string())));let bonjour =labels_for("(2014Q4) Bonjour♪恋味パティスリー 第01話 「Lesson 1」 (1280x720 x265 10bit AAC)");assert!(bonjour.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!bonjour.contains(&("1".to_string(), "B-EPISODE".to_string())));let durarara = labels_for("[VCB-Studio] Durarara!!×2 Ketsu [Menu01][Ma10p_1080p][x265_flac]");assert!(durarara.contains(&("Durarara".to_string(), "B-TITLE".to_string())));assert!(durarara.contains(&("2".to_string(), "B-TITLE".to_string())));assert!(!durarara.contains(&("2".to_string(), "B-EPISODE".to_string())));13 unmodified linesassert!(bleach_movie.contains(&("3".to_string(), "B-TITLE".to_string())));assert!(!bleach_movie.contains(&("3".to_string(), "B-EPISODE".to_string())));let conan_movie =labels_for("[DBD-Raws][Detective Conan Movie 27 The Million-Dollar Pentagram][PV][01][1080P]");assert!(conan_movie.contains(&("27".to_string(), "B-TITLE".to_string())));assert!(conan_movie.contains(&("PV".to_string(), "B-SPECIAL".to_string())));let madoka_movie =labels_for("[DBD-Raws][Puella Magi Madoka Magica the Movie 01 Beginnings][NCED][1080P]");assert!(madoka_movie.contains(&("01".to_string(), "B-TITLE".to_string())));assert!(madoka_movie.contains(&("Beginnings".to_string(), "B-TITLE".to_string())));13 unmodified linesassert!(lapis.contains(&("꞉".to_string(), "B-TITLE".to_string())));assert!(lapis.contains(&("LiGHTs".to_string(), "B-TITLE".to_string())));let rezero = labels_for("TVアニメ『Re:ゼロから始める異世界生活』第10話「鬼がかったやり方」予告");assert!(!rezero.contains(&("TV".to_string(), "B-TITLE".to_string())));assert!(!rezero.contains(&("アニメ".to_string(), "B-TITLE".to_string())));assert!(rezero.contains(&("Re".to_string(), "B-TITLE".to_string())));4 unmodified linesassert!(!shark.contains(&("アニメ".to_string(), "B-TITLE".to_string())));assert!(shark.contains(&("おでかけ子ザメ".to_string(), "B-TITLE".to_string())));let creditless = labels_for("[ANK-Raws] デート・ア・ライブⅡ Creditless ED (Bdrip 1920x1080 HEVC FLAC)",);assert!(creditless.contains(&("Creditless".to_string(), "B-SPECIAL".to_string())));assert!(creditless.contains(&("ED".to_string(), "B-SPECIAL".to_string())));1 unmodified lineassert!(no_number.contains(&("081".to_string(), "B-EPISODE".to_string())));assert!(!no_number.contains(&("1".to_string(), "B-EPISODE".to_string())));let bilingual = labels_for("辉夜大小姐想让我告白~天才们的恋爱头脑战~.S2-01.中日双语.云光字幕组.[1080p]");assert!(bilingual.contains(&("中日".to_string(), "B-SOURCE".to_string())));assert!(!bilingual.contains(&("中日".to_string(), "B-TITLE".to_string())));18 unmodified linesassert!(one_room.contains(&("Second".to_string(), "B-SEASON".to_string())));assert!(one_room.contains(&("Season".to_string(), "B-SEASON".to_string())));let jade = labels_for("[GM-Team][国漫][诛仙 第2季][Jade Dynasty Ⅱ][2024][12][AVC][GB][1080P]");assert!(jade.contains(&("Jade".to_string(), "B-TITLE".to_string())));assert!(jade.contains(&("Dynasty".to_string(), "B-TITLE".to_string())));assert!(jade.contains(&("Ⅱ".to_string(), "B-SEASON".to_string())));16 unmodified linesassert!(fox.contains(&("Fox".to_string(), "B-TITLE".to_string())));assert!(fox.contains(&("Ⅷ".to_string(), "B-SEASON".to_string())));let kage = labels_for("[LKSUB][Kage no Jitsuryokusha ni Naritakute! 2nd Season][03][GB][720P]");assert!(kage.contains(&("2nd".to_string(), "B-SEASON".to_string())));assert!(kage.contains(&(" ".to_string(), "B-SEASON".to_string())));assert!(kage.contains(&("Season".to_string(), "B-SEASON".to_string())));8 unmodified linesassert!(date_live_special.contains(&("Ⅱ".to_string(), "B-SEASON".to_string())));assert!(date_live_special.contains(&("CM01".to_string(), "B-SPECIAL".to_string())));let lupin_part =labels_for("[SnowDream][Part 5_Lupin Sansei Part 5][01][BIG5][720P]");assert!(lupin_part.contains(&("Lupin".to_string(), "B-TITLE".to_string())));assert!(lupin_part.contains(&("Sansei".to_string(), "B-TITLE".to_string())));assert!(!lupin_part.contains(&("Part".to_string(), "B-TITLE".to_string())));assert!(lupin_part.contains(&("5".to_string(), "B-SEASON".to_string())));assert!(!lupin_part.contains(&("5".to_string(), "B-SPECIAL".to_string())));let roman_leaf = dmhy_record("Ⅰ 001 魯邦燃起了鬥志", "tpl_test", &suggested_roles("TEXT SEP EPISODE SEP TEXT")).unwrap();assert!(roman_leaf.tokens.iter()43 unmodified linesassert!(ajin_movie.contains(&("Ajin".to_string(), "B-TITLE".to_string())));assert!(ajin_movie.contains(&("01".to_string(), "B-SPECIAL".to_string())));let eien = labels_for("[Nekomoe kissaten&LoliHouse] Eien no 831 [WebRip 1080p HEVC-10bit AAC ASSx2]");assert!(eien.contains(&("Eien".to_string(), "B-TITLE".to_string())));assert!(eien.contains(&("831".to_string(), "B-TITLE".to_string())));let ep_only = dmhy_record("Ep.25", "tpl_test", &suggested_roles("TEXT SEP EPISODE")).unwrap();assert!(audit_warnings(&ep_only).contains(&"no_title".to_string()));}}134 unmodified lines13513613713813914014120 unmodified lines1621631641651661671681699 unmodified lines17918018118218318418514 unmodified lines2002012022032042052062076 unmodified lines2142152162172182192202212222233 unmodified lines22722822923023123223323423523645 unmodified lines28228328428528628728828929029129229349 unmodified lines34334434534634734834935035135220 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141236 unmodified lines44945045145245345445545645734 unmodified lines49249349449549649749849984 unmodified lines584585586587588589590212 unmodified lines803804805806807808809153 unmodified lines96396496596696796896960 unmodified lines103010311032103310341035103631 unmodified lines106810691070107110721073107410751 unmodified line107710781079108010811082108315 unmodified lines10991100110111021103110411051106110711081109111011111112111311141115111611171118111941 unmodified lines1161116211631164116511661167116832 unmodified lines1201120212031204120512061207120812091210121136 unmodified lines124812491250125112521253125412551256125712581259126012611262126313 unmodified lines127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812992 unmodified lines130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132953 unmodified lines138313841385138613871388138913901391139213931394139513962 unmodified lines139914001401140214031404140514064 unmodified lines141114121413141414151416141714183 unmodified lines142214231424142514261427142814291 unmodified line143114321433143414351436143714382 unmodified lines144114421443144414451446144714482 unmodified lines14511452145314541455145614571458415 unmodified lines18741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119228 unmodified lines193119321933193419351936193719381939194019411942194389 unmodified lines2033203420352036203720382039204020412042204320444 unmodified lines204920502051205220532054205520561 unmodified line2058205920602061206220632064206520668 unmodified lines20752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402 unmodified lines22432244224522462247224822492250225122522253225485 unmodified lines23402341234223432344234523462347234823492350235123522353336 unmodified lines26902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733121 unmodified lines2855285628572858285928602861286298 unmodified lines296129622963296429652966296729682969297029712972297329744 unmodified lines2979298029812982298329842985298629876 unmodified lines29942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304131 unmodified lines307330743075307630773078307930803081308230833084308530863087308830893090309127 unmodified lines311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316173 unmodified lines32353236323732383239324032413242324332449 unmodified lines32543255325632573258325932606 unmodified lines326732683269327032713272327332743275107 unmodified lines33833384338533863387338833894 unmodified lines33943395339633973398339934003401340234033404340526 unmodified lines34323433343434353436343734381 unmodified line34403441344234433444344534463 unmodified lines345034513452345334543455345620 unmodified lines34773478347934803481348234832 unmodified lines3486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635272 unmodified lines35303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555131 unmodified lines368736883689369036913692369336943695369636973698369981 unmodified lines37813782378337843785378637873788378938 unmodified lines38283829383038313832383338343835383638373838383938403 unmodified lines384438453846384738483849385011 unmodified lines3862386338643865386638673868386938703871387238733874387538763877387830 unmodified lines3909391039113912391339143915391610 unmodified lines39273928392939303931393239333934393539363937393839393940394139423943394439453946394714 unmodified lines39623963396439653966396739683969397039713972397339743975397653 unmodified lines403040314032403340344035403640374038403940404041404244 unmodified lines408740884089409040914092409340944095409640974098409941004101410227 unmodified lines41304131413241334134413541364137413841394140414141424143414441452 unmodified lines4148414941504151415241534154415522 unmodified lines41784179418041814182418341844185418612 unmodified lines419942004201420242034204420557 unmodified lines426342644265426642674268426942704271427229 unmodified lines43024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440617 unmodified lines44244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944606 unmodified lines44674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455942 unmodified lines460246034604460546064607460836 unmodified lines464546464647464846494650465146524653465446554656465723 unmodified lines468146824683468446854686468746884689469046914692469346949 unmodified lines47044705470647074708470947104711471215 unmodified lines4728472947304731473247334734473547369 unmodified lines4746474747484749475047514752475347544755475647574758475947604761476211 unmodified lines4774477547764777477847794780478139 unmodified lines482148224823482448254826482748281 unmodified line4830483148324833483448354836483748384839484048414842484348444845484672 unmodified lines491949204921492249234924492549268 unmodified lines4935493649374938493949404941494249434944494549464947494849494950495150 unmodified lines500250035004500550065007500850095 unmodified lines50155016501750185019502050212 unmodified lines502450255026502750285029503050315032503350345035503612 unmodified lines50495050505150525053505450555056505739 unmodified lines50975098509951005101510251035104510549 unmodified lines515551565157515851595160516151628 unmodified lines51715172517351745175517651775178517951805181518251835184518551865187518851895190519113 unmodified lines52055206520752085209521052115212521352145215521652175218521913 unmodified lines523352345235523652375238523952404 unmodified lines524552465247524852495250525152521 unmodified line52545255525652575258525952605261526218 unmodified lines5281528252835284528552865287528816 unmodified lines530553065307530853095310531153128 unmodified lines532153225323532453255326532753285329533053315332533353345335533653375338533943 unmodified lines53835384538553865387538853895390539153925393539453955396134 unmodified linesstruct Stats {seen: usize,skipped_encoding_noise: usize,skipped_music_audio_collection: usize,trimmed_parent_path: usize,skipped_no_recipe: usize,skipped_sample_cap: usize,20 unmodified linesSkipped {reason: &'static str,trimmed_parent: bool,example: Option<String>,warnings: Vec<String>,},}9 unmodified lines});static EPISODE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}(?:\.\d{1,2})?(?:END)?$").unwrap());static DECIMAL_EPISODE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\d{1,3}\.\d{1,2}$").unwrap());static NUMERIC_TITLE_PREFIX_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^\d{1,3}(?:[./-]\d{1,3})?$").unwrap());static EPISODE_CJK_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^第?\d{1,4}[话話回集]$").unwrap());14 unmodified lines});static CJK_SEASON_TOKEN_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^第[一二三四五六七八九十\d]+[季期部]$").unwrap());static CJK_SEASON_EMBEDDED_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(.+?)(第[一二三四五六七八九十\d]+[季期部])(.{0,12})$").unwrap());static CJK_EPISODE_EMBEDDED_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(.+?)(第?\d{1,4}[话話回集])(.{0,32})$").unwrap());static CJK_TITLE_TRAILING_EPISODE_RE: Lazy<Regex> =6 unmodified linesRegex::new(r"(?i)^(?:First|Second|Third|Fourth|Fifth|Sixth|Seventh|Eighth|Ninth|Tenth)$").unwrap()});static SEASON_WORD_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:Season|Saison)$").unwrap());static CJK_TITLE_LANG_PREFIX_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"^(.+?)(国日双语|國日雙語|日语版|日語版|国语版|國語版|双语|雙語)(第?)$").unwrap()});static SEASON_VALUE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^S(\d{1,2})$").unwrap());static SPECIAL_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"(?i)^(?:(?:NCOP|NCED|OP|ED|PV|CM)(?:[\s_.-]?(?:\d{1,4}|v\d{1,3}|[A-Z]))?|SP(?:[\s_.-]?\d{0,4})?|(?:OVA|OAD|IV)(?:[\s_.-]?\d{0,4})?|(?:BD)?Menu(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?|(?:BD[-_. ]?)?Spot(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?|(?:Intro|Preview|Trailer|Teaser|Animatics?)(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?)$").unwrap()3 unmodified linesstatic DATE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}$").unwrap());static DATE_RANGE_MIXED_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"^(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}\s*[-~]\s*(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}$",).unwrap()});static CJK_DATE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"^(?:19|20)\d{2}年\d{1,2}月\d{1,2}日$").unwrap());45 unmodified linesstatic SIMPLE_EPISODE_RE: Lazy<Regex> =Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}$").unwrap());static SPECIAL_SPACE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\s_.-]+").unwrap());static MUSIC_COLLECTION_RE: Lazy<Regex> = Lazy::new(|| {Regex::new(r"(?i)(?:^|[^A-Z0-9])(?:MUSIC\s*CLIP|MUSIC\s+COLLECTION|SOUNDTRACK|OST|CHARACTER\s+SONG|DRAMA\s+CD|CD\s+ALBUM|BONUS\s+CD)(?:$|[^A-Z0-9])",).unwrap()});fn main() -> Result<()> {let args = Args::parse();49 unmodified lineslet mut label_counts: HashMap<String, usize> = HashMap::new();let mut template_counts: HashMap<String, usize> = HashMap::new();let mut examples = Vec::new();let mut skipped_music_audio_collection_examples = Vec::new();let mut skipped_low_frequency_audit_warning_counts: HashMap<String, usize> = HashMap::new();let mut skipped_low_frequency_audit_warning_examples: HashMap<String, Vec<String>> =HashMap::new();let mut writer = BufWriter::new(File::create(&args.output)?);for item in processed {match item {20 unmodified linesProcessed::Skipped {reason,trimmed_parent,example,warnings,} => {if trimmed_parent {stats.trimmed_parent_path += 1;}match reason {"encoding_noise" => stats.skipped_encoding_noise += 1,"music_audio_collection" => {stats.skipped_music_audio_collection += 1;if let Some(example) = example {if skipped_music_audio_collection_examples.len() < 20 {skipped_music_audio_collection_examples.push(example);}}}"no_recipe" => stats.skipped_no_recipe += 1,"sample_cap" => stats.skipped_sample_cap += 1,"role_mismatch" => stats.skipped_role_mismatch += 1,"low_frequency_audit_warning" => {stats.skipped_low_frequency_audit_warning += 1;for warning in warnings {*skipped_low_frequency_audit_warning_counts.entry(warning.clone()).or_default() += 1;if let Some(example) = example.as_ref() {let bucket = skipped_low_frequency_audit_warning_examples.entry(warning).or_default();if bucket.len() < 10 {bucket.push(example.clone());}}}}_ => {}}36 unmodified lines"label_counts": label_counts,"top_template_counts": top_template_counts,"examples": examples,"skipped_music_audio_collection_examples": skipped_music_audio_collection_examples,"skipped_low_frequency_audit_warning_counts": skipped_low_frequency_audit_warning_counts,"skipped_low_frequency_audit_warning_examples": skipped_low_frequency_audit_warning_examples,"implementation": "rust_dmhy_template_apply"});fs::write(34 unmodified linesif !path.exists() {return Ok(Vec::new());}let file =File::open(path).with_context(|| format!("failed to open whitelist {}", path.display()))?;let mut lines = Vec::new();for line in BufReader::new(file).lines() {let line = line?;84 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(&original)|| has_non_anime_noise(&original)|| has_music_collection_noise(&original)|| has_abstract_path_noise(&original)){skipped_encoding_noise += 1;212 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(&original)|| has_non_anime_noise(&original)|| has_music_collection_noise(&original)|| has_abstract_path_noise(&original)){continue;153 unmodified linesif !args.keep_encoding_noise&& (has_encoding_noise(original)|| has_non_anime_noise(original)|| has_music_collection_noise(original)|| has_abstract_path_noise(original)){return None;60 unmodified lineslet (key, tokens, _classes, groups) = template_key_for_filename(segment);let suggested = suggested_roles(&key);let roles = adjust_contextual_roles(&tokens, &groups, &suggested);let roles = refine_semantic_roles(&tokens, &groups, &roles);let candidates = rich_candidates_for_segment(segment, &tokens, &groups, &roles, is_leaf);json!({"index": index,31 unmodified linescontinue;}output.push(json!({"role": fine_title_role_for_candidate(&roles, start, end).unwrap_or_else(|| fine_title_role(segment, &text, is_leaf, candidate_index, title_ranges.len()).to_string()),"coarse_role": "TITLE","text": text,"group_start": start,1 unmodified line}));}for (group_index, role) in roles.iter().enumerate() {if is_title_role(role) || role == "O" || role == "HASH" {continue;}let text = group_text(tokens, &groups[group_index]);15 unmodified linesoutput}fn fine_title_role_for_candidate(roles: &[String], start: usize, end: usize) -> Option<String> {let mut entities: Vec<&str> = roles[start..end].iter().filter_map(|role| title_entity_from_role(role)).filter(|entity| *entity != "TITLE").collect();entities.sort();entities.dedup();match entities.len() {0 => None,1 => Some(entities[0].to_string()),_ => Some("TITLE_MIXED".to_string()),}}fn candidate_text(tokens: &[String], groups: &[Group], start: usize, end: usize) -> String {let Some(first) = groups.get(start).and_then(|group| group.indices.first()) else {return String::new();41 unmodified lines"GROUP" => "RELEASE_GROUP","EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" => "EPISODE","SEASON" => "SEASON","PATH_SEASON" => "PATH_SEASON","TAG" => "TAG","SPECIAL" | "VOLUME" => "SPECIAL","RESOLUTION" => "RESOLUTION","SOURCE" => "SOURCE",32 unmodified linesfn audit_warnings(record: &Record) -> Vec<String> {let mut warnings = Vec::new();let title_texts = title_entity_texts(&record.tokens, &record.labels);let title_spans = title_texts.len();if title_spans == 0 {warnings.push("no_title".to_string());} else if repeated_title_entity_spans(&record.labels) {warnings.push("multiple_title_spans".to_string());}if !title_texts.is_empty() && title_texts.iter().all(|title| generic_title_text(title)) {36 unmodified lineswarnings.push("encoding_noise_survived".to_string());}for (index, token) in record.tokens.iter().enumerate() {let entity = record.labels.get(index).and_then(|label| label_entity(label));let cleaned = strip_wrapper(token);if HASH_RE.is_match(token) && record.labels.get(index).is_some_and(|label| label != "O") {warnings.push("hash_labeled".to_string());break;}if EPISODE_VERSION_RE.is_match(&compact_for_classify(&cleaned)) && entity != Some("EPISODE"){warnings.push("episode_version_missing_label".to_string());}13 unmodified lines.or_else(|| label.strip_prefix("I-"))}fn title_entity_texts(tokens: &[String], labels: &[String]) -> Vec<String> {let mut spans = Vec::new();let mut current = String::new();let mut current_entity: Option<String> = None;for (token, label) in tokens.iter().zip(labels.iter()) {let entity = label_entity(label).filter(|entity| is_title_entity(entity));if entity.is_some() && current_entity.as_deref() == entity {current.push_str(token);} else {if !current.trim().is_empty() {spans.push(current.trim().to_string());}current.clear();current_entity = entity.map(str::to_string);if entity.is_some() {current.push_str(token);}}}if !current.trim().is_empty() {2 unmodified linesspans}fn repeated_title_entity_spans(labels: &[String]) -> bool {let mut seen = HashSet::new();let mut previous: Option<String> = None;for label in labels {let entity = label_entity(label).filter(|entity| is_title_entity(entity)).map(str::to_string);if entity.is_some() && entity != previous {let entity = entity.clone().unwrap();if !seen.insert(entity) {return true;}}previous = entity;}false}fn generic_title_text(text: &str) -> bool {matches!(text.trim().to_ascii_lowercase().as_str(),"tv" | "movie"| "mov"| "sample"| "commercial"53 unmodified linesrecipes: &HashMap<String, Recipe>,sample_counters: &HashMap<String, AtomicUsize>,) -> Processed {if !args.keep_encoding_noise && has_music_collection_noise(original) {return Processed::Skipped {reason: "music_audio_collection",trimmed_parent: false,example: Some(original.to_string()),warnings: Vec::new(),};}if !args.keep_encoding_noise&& (has_encoding_noise(original)|| has_non_anime_noise(original)2 unmodified linesreturn Processed::Skipped {reason: "encoding_noise",trimmed_parent: false,example: None,warnings: Vec::new(),};}let (training_filename, trimmed_parent) = training_filename_for(original);4 unmodified linesreturn Processed::Skipped {reason: "no_recipe",trimmed_parent,example: None,warnings: Vec::new(),}}};3 unmodified linesreturn Processed::Skipped {reason: "sample_cap",trimmed_parent,example: None,warnings: Vec::new(),};}}1 unmodified linereturn Processed::Skipped {reason: "role_mismatch",trimmed_parent,example: None,warnings: Vec::new(),};}let mut record = match dmhy_record(&training_filename, &recipe.template_id, &recipe.roles) {2 unmodified linesreturn Processed::Skipped {reason: "role_mismatch",trimmed_parent,example: None,warnings: Vec::new(),}}};2 unmodified linesreturn Processed::Skipped {reason: "low_frequency_audit_warning",trimmed_parent,example: Some(record.filename.clone()),warnings,};}if trimmed_parent {415 unmodified linesroles}fn refine_semantic_roles(tokens: &[String], groups: &[Group], roles: &[String]) -> Vec<String> {let mut output = roles.to_vec();let mut segment_end = groups.iter().position(|group| group.class_name == "PATH").unwrap_or(groups.len());let mut is_path_segment = segment_end < groups.len();for index in 0..groups.len() {if groups[index].class_name == "PATH" {segment_end = groups[index + 1..].iter().position(|group| group.class_name == "PATH").map(|offset| index + 1 + offset).unwrap_or(groups.len());is_path_segment = segment_end < groups.len();continue;}let text = group_text(tokens, &groups[index]);let bracketed = is_bracket_group(&groups[index]);if is_category_tag_text(&text, bracketed, is_path_segment)&& matches!(output[index].as_str(), "O" | "TITLE" | "GROUP" | "SPECIAL"){output[index] = "TAG".to_string();continue;}if output[index] == "SEASON" && is_path_segment {output[index] = "PATH_SEASON".to_string();continue;}if output[index] == "TITLE" {output[index] = title_role_for_text(&text, is_path_segment);}}output}fn filename_has_title(filename: &str) -> bool {let (key, _, _, _) = template_key_for_filename(filename);suggested_roles(&key).iter().any(|role| is_title_role(role))}fn training_filename_for(original: &str) -> (String, bool) {8 unmodified lines&& path_segment_starts_with_episode(parts[parts.len() - 1])&& !leaf_has_full_title_after_episode(parts[parts.len() - 1]))){if let Some(parent) = parts[..parts.len() - 1].iter().rev().find(|part| {let trimmed = trim_parent_title_segment(part);filename_has_title(&trimmed) && !path_segment_is_media_noise(&trimmed)}) {let parent = trim_parent_title_segment(parent.trim());return (format!("{} {}", parent, parts[parts.len() - 1].trim()),true,);}89 unmodified linesreturn true;}let markers = ["譁", "蜈", "螟", "蟄", "謇", "邱", "荳", "縺", "繧", "莨", "鬆", "髯", "瀛", "楀", "箷","绲", "刔", "鏃", "湪", "鏍", "犲", "儚", "鐗", "吀", "铦", "躲", "伄", "椋", "伓", "姘","帽", "娆", "洖", "浜", "堝", "澶", "湴", "鐒", "銇", "銈", "銉", "偅", "偗", "儱", "儫","兗", "仧", "鏉变", "鍠靛", "銉熴", "銈︺", "瀵掕", "潐楦", "常涔", "涓歖", "缁堟", "湯鍒","瀵诲", "線浣", "曟柟", "瓒呴", "绁炪", "偘銉", "兇銈", "銉砡", "銉砕", "杩风", "硦澶","銇淬", "仧銉", "銉嗐", "偅銈", "銈躲",];let marker_hits = markers.iter()4 unmodified lines.filter(|ch| ('\u{ff61}'..='\u{ff9f}').contains(ch)).count();let latin_mojibake = value.split_whitespace().any(|part| {part.chars().any(|ch| matches!(ch, '帽' | '茅' | '脳' | '锛'))&& part.chars().any(|ch| ch.is_ascii_alphabetic())});marker_hits >= 2 || (marker_hits >= 1 && halfwidth_hits >= 1) || latin_mojibake1 unmodified linefn has_non_anime_noise(value: &str) -> bool {let normalized = value.replace('\\', "/").trim().to_ascii_lowercase();normalized == "mtv"|| normalized.starts_with("mtv/")|| normalized.contains("/mtv/")|| value.contains("[旅游")|| value.contains("[旅游番")|| normalized.contains("tokyo deep")8 unmodified lines.to_ascii_lowercase()}fn normalized_tag_text(value: &str) -> String {value.replace(['_', '.', '-', '・'], " ").split_whitespace().collect::<Vec<_>>().join(" ").trim().to_ascii_lowercase()}fn compact_tag_text(value: &str) -> String {value.chars().filter(|ch| ch.is_alphanumeric()).collect::<String>().to_ascii_lowercase()}fn is_bracket_group(group: &Group) -> bool {group.class_name.starts_with("BRACKET_")}fn is_category_tag_text(text: &str, bracketed: bool, path_segment: bool) -> bool {let cleaned = strip_wrapper(text);let trimmed = cleaned.trim();if trimmed.is_empty() {return false;}if (bracketed || path_segment) && (DATE_RE.is_match(trimmed) || YEAR_RANGE_RE.is_match(trimmed)){return true;}if (bracketed || path_segment)&& matches!(trimmed,"国漫" | "國漫" | "日漫" | "剧场版" | "劇場版" | "新番"){return true;}if (bracketed || path_segment)&& (trimmed.ends_with("月新番") || trimmed.ends_with("月新番合集")){return true;}let normalized = normalized_tag_text(trimmed);(bracketed || path_segment)&& matches!(normalized.as_str(),"anime" | "gekijouban" | "movie" | "movies" | "the movie" | "tv" | "tv series")}fn has_music_collection_noise(value: &str) -> bool {let normalized = value.replace(['_', '.', '-', '・', '/', '\\'], " ").split_whitespace().collect::<Vec<_>>().join(" ");let compact = compact_tag_text(value);MUSIC_COLLECTION_RE.is_match(&normalized) || compact.contains("musicclip")}fn is_title_role(role: &str) -> bool {role == "TITLE" || role.starts_with("TITLE_") || role.starts_with("PATH_TITLE_")}fn is_path_title_role(role: &str) -> bool {role.starts_with("PATH_TITLE_")}fn title_entity_from_role(role: &str) -> Option<&str> {if role == "TITLE" {Some("TITLE")} else if role.starts_with("TITLE_") || role.starts_with("PATH_TITLE_") {Some(role)} else {None}}fn is_title_entity(entity: &str) -> bool {entity == "TITLE"|| matches!(entity,"TITLE_CHS"| "TITLE_CHT"| "TITLE_JPN"| "TITLE_LATIN"| "TITLE_MIXED"| "PATH_TITLE_CHS"| "PATH_TITLE_CHT"| "PATH_TITLE_JPN"| "PATH_TITLE_LATIN"| "PATH_TITLE_MIXED")}fn is_title_label(label: &str) -> bool {label_entity(label).is_some_and(is_title_entity)}fn title_language_suffix(text: &str) -> &'static str {let mut has_latin = false;let mut has_han = false;let mut has_kana = false;for ch in text.chars() {if ch.is_ascii_alphabetic() {has_latin = true;} else if ('\u{3040}'..='\u{30ff}').contains(&ch) || ('\u{31f0}'..='\u{31ff}').contains(&ch){has_kana = true;} else if ('\u{4e00}'..='\u{9fff}').contains(&ch) {has_han = true;}}if has_kana {return "JPN";}if has_latin && has_han {return "MIXED";}if has_han {return cjk_title_language_suffix(text);}if has_latin {return "LATIN";}"MIXED"}fn cjk_title_language_suffix(text: &str) -> &'static str {let japanese_markers = ['々', 'ヶ', '君', '戦', '気', '辺', '沢', '桜', '竜', '広', '処', '歩', '黒', '円',];if text.chars().any(|ch| japanese_markers.contains(&ch)) {return "JPN";}let simplified_markers = ['国', '剧', '场', '农', '闲', '汉', '龙', '门', '击', '战', '体', '后', '爱', '边', '声','岛', '学', '万',];if text.chars().any(|ch| simplified_markers.contains(&ch)) {return "CHS";}let traditional_markers = ['國', '劇', '場', '農', '閒', '漢', '龍', '門', '擊', '戰', '體', '後', '愛', '邊', '聲','島', '學', '萬', '縛', '異', '臺', '灣', '搖', '滾',];if text.chars().any(|ch| traditional_markers.contains(&ch)) {return "CHT";}"CHS"}fn title_role_for_text(text: &str, path_title: bool) -> String {let prefix = if path_title { "PATH_TITLE" } else { "TITLE" };format!("{prefix}_{}", title_language_suffix(text))}fn path_segment_is_episodeish(value: &str) -> bool {let (_, _, _, groups) = template_key_for_filename(value);let structural: Vec<&String> = groups2 unmodified lines.filter(|item| item.as_str() != "SEP").collect();!structural.is_empty()&& structural.iter().all(|item| {item.starts_with("EPISODE")|| item.as_str() == "SPECIAL"|| item.as_str() == "VOLUME"|| item.as_str() == "BRACKET_VOLUME"})}fn path_segment_starts_with_episode(value: &str) -> bool {85 unmodified linesfn role_label(role: &str) -> String {let entity = match role {"GROUP" => Some("GROUP"),role if is_title_role(role) => Some("TITLE"),"EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" => Some("EPISODE"),"SEASON" => Some("SEASON"),"PATH_SEASON" => Some("PATH_SEASON"),"SPECIAL" | "VOLUME" => Some("SPECIAL"),"RESOLUTION" => Some("RESOLUTION"),"SOURCE" => Some("SOURCE"),"TAG" => Some("TAG"),_ => None,};entity.map_or_else(|| "O".to_string(), |entity| format!("B-{entity}"))336 unmodified lines|| normalized.contains("字幕組")}fn title_context_before(tokens: &[String],groups: &[Group],roles: &[String],index: usize,) -> String {(0..index).filter(|&cursor| roles[cursor] == "TITLE").map(|cursor| group_text(tokens, &groups[cursor])).collect::<Vec<_>>().join(" ")}fn short_number_title_exception(context: &str, number: &str) -> bool {let normalized = normalized_tag_text(context);let compact = compact_tag_text(context);matches!((normalized.as_str(), number),("kamisama hajimemashita", "2") | ("ghiblies episode", "2") | ("r", "15")) || (normalized.contains("91 days") && number == "91")|| (context.contains("銀河鉄道") && number == "999")|| compact.contains("highschooldd")|| (context.contains("機動戦士ガンダム") && number == "00")}fn group_followed_by_quote(tokens: &[String], groups: &[Group], index: usize) -> bool {let Some(last_token) = groups.get(index).and_then(|group| group.indices.last()) else {return false;};for token in &tokens[*last_token + 1..] {if token.chars().all(char::is_whitespace) {continue;}return matches!(token.as_str(), "「" | "「" | "\"" | "'");}false}const KNOWN_TITLE_PHRASES: &[&[&str]] = &[&["SPY", "x", "FAMILY"],&["Spy", "x", "Family"],121 unmodified lines});if !first_is_known_group {if let Some(groupish_index) = (1..groups.len()).find(|&index| {output[index] == "TITLE"&& looks_like_release_group(&group_text(tokens, &groups[index]))}) {output[0] = "TITLE".to_string();output[groupish_index] = "GROUP".to_string();98 unmodified lines}if roles[index].starts_with("EPISODE")&& index >= 2&& matches!(group_text(tokens, &groups[index - 1]).as_str(),"×" | "x" | "X")&& output[index - 2] == "TITLE"&& !roles[index + 1..].iter().any(|role| role.starts_with("EPISODE")){output[index] = "TITLE".to_string();if let Some(next_text_index) = (index + 1..roles.len()).find(|&cursor| {4 unmodified linescontinue;}if roles[index].starts_with("EPISODE")&& !output[..index].iter().any(|role| role.starts_with("EPISODE"))&& group_text(tokens,&groups[(0..index)6 unmodified linesoutput[index] = "TITLE".to_string();continue;}if output[index] == "TITLE" && matches!(text.as_str(), "中日" | "日中" | "英日" | "日英"){let next_source_lang = (index + 1..roles.len()).find(|&cursor| groups[cursor].class_name != "SEP").is_some_and(|cursor| {output[cursor] == "SOURCE" && group_text(tokens, &groups[cursor]).contains('语')});if next_source_lang {output[index] = "SOURCE".to_string();continue;}}if roles[index].starts_with("EPISODE")&& index >= 1&& output[..index].iter().any(|role| role == "TITLE")&& text.chars().all(|ch| ch.is_ascii_digit())&& short_number_title_exception(&title_context_before(tokens, groups, &output, index),&text,){output[index] = "TITLE".to_string();continue;}if roles[index].starts_with("EPISODE")&& index >= 1&& output[index - 1] == "TITLE"&& groups[index - 1].class_name != "SEP"&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 2&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE"))&& !group_followed_by_quote(tokens, groups, index){let context = title_context_before(tokens, groups, &output, index);output[index] = if short_number_title_exception(&context, &text) {"TITLE"} else {"SEASON"}.to_string();continue;}if roles[index].starts_with("EPISODE") && (2..roles.len()).contains(&index) {31 unmodified lines&& output[index - 1] == "TITLE"&& groups[index - 1].class_name != "SEP"&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 2&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE"))&& !group_followed_by_quote(tokens, groups, index){let context = title_context_before(tokens, groups, &output, index);output[index] = if short_number_title_exception(&context, &text) {"TITLE"} else {"SEASON"}.to_string();continue;}if !output[..index].iter().any(|role| role == "TITLE")27 unmodified lines&& previous_text.len() <= 48&& previous_text.chars().any(|ch| ch.is_alphabetic())&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 2&& !(index + 2 < roles.len()&& groups[index + 1].class_name == "SEP"&& group_text(tokens, &groups[index + 2]).eq_ignore_ascii_case("episode"))&& !(index + 1 < roles.len()&& groups[index + 1].class_name == "SEP"&& group_text(tokens, &groups[index + 1]).chars().any(|ch| matches!(ch, '「' | '「' | '"' | '\'')))&& !group_followed_by_quote(tokens, groups, index)&& (next_episode|| (next_special&& (text.parse::<u16>().is_ok_and(|value| value >= 100)|| (previous_text.len() <= 4&& previous_text.is_ascii()&& previous_text.chars().all(|ch| ch.is_ascii_alphabetic()))))){output[index] = if next_episode&& !short_number_title_exception(&title_context_before(tokens, groups, &output, index),&text,) {"SEASON"} else {"TITLE"}.to_string();continue;}}if roles[index].starts_with("EPISODE")&& (text.chars().all(|ch| ch.is_ascii_digit())|| matches!(classify_atom(&text).as_str(), "EPISODE" | "EPISODE_VERSION"))&& output[..index].iter().any(|role| role == "SPECIAL")&& !output[..index].iter().any(|role| role.starts_with("EPISODE")){let previous_structural = (0..index).rev()73 unmodified lines}if roles[index] == "TITLE"&& matches!(text.to_ascii_uppercase().as_str(), "TV" | "TV版")&& output.iter().enumerate().any(|(other, role)| other != index && role == "TITLE"){output[index] = "O".to_string();continue;9 unmodified linescontinue;}if output[index] == "TITLE" && text.eq_ignore_ascii_case("Creditless") {let later_special = output[index + 1..].iter().any(|role| role == "SPECIAL");if later_special {output[index] = "SPECIAL".to_string();continue;6 unmodified lines}if output[index] == "O"&& groups[index].class_name == "TEXT"&& roles[index + 1..].iter().any(|role| role.starts_with("EPISODE"))&& text.chars().any(|ch| ch.is_alphabetic())&& !ep_markers.contains(&text.as_str()){107 unmodified linesif matches!(previous_real_text.to_ascii_lowercase().as_str(),"lesson" | "part" | "no") {output[index] = "O".to_string();continue;}4 unmodified linescontinue;}if output[..index].iter().any(|role| role == "TITLE")&& (output[..index].iter().enumerate().any(|(cursor, role)| {role == "TITLE" && is_special_title_phrase(&group_text(tokens, &groups[cursor]))}))&& !output[..index].iter().any(|role| role.starts_with("EPISODE"))&& text.chars().all(|ch| ch.is_ascii_digit())&& text.len() <= 3{26 unmodified lineslet mut candidates = Vec::new();let mut index = 0;while index < roles.len() {if !is_title_role(&roles[index]) {index += 1;continue;}1 unmodified lineindex += 1;loop {if index < roles.len()&& is_title_role(&roles[index])&& !(groups[index - 1].class_name == "BRACKET_TEXT"&& groups[index].class_name == "BRACKET_TEXT"){3 unmodified linesif index + 1 < roles.len()&& roles[index] == "O"&& groups[index].class_name == "SEP"&& is_title_role(&roles[index + 1]){index += 2;continue;20 unmodified linesrole.starts_with("EPISODE")|| matches!(role.as_str(),"SEASON" | "PATH_SEASON" | "SPECIAL" | "SOURCE" | "RESOLUTION")}).unwrap_or(roles.len());2 unmodified lines.copied().filter(|(_, end)| *end <= first_anchor).collect();let before_anchor_only_path_titles = !before_anchor.is_empty()&& before_anchor.iter().all(|(start, end)| {(*start..*end).all(|index| !is_title_role(&roles[index]) || is_path_title_role(&roles[index]))});let selected_pool = if before_anchor.is_empty() || before_anchor_only_path_titles {&candidates} else {&before_anchor};let mut selected_by_kind: HashMap<String, ((usize, usize), (isize, usize, usize))> =HashMap::new();for (start, end) in selected_pool.iter().copied() {let score = (title_candidate_score(tokens, groups, start, end),end,end - start,);let key = title_candidate_key(tokens, groups, roles, start, end);match selected_by_kind.get(&key) {Some((_, best_score)) if *best_score >= score => {}_ => {selected_by_kind.insert(key, ((start, end), score));}}}let selected: HashSet<(usize, usize)> =selected_by_kind.values().map(|(range, _)| *range).collect();let mut output = roles.to_vec();let mut dropped = Vec::new();for (start, end) in candidates {if selected.contains(&(start, end)) {continue;}for index in start..end {if is_title_role(&output[index]) {output[index] = "O".to_string();dropped.push(index.to_string());}2 unmodified lines(output, dropped)}fn title_candidate_key(tokens: &[String],groups: &[Group],roles: &[String],start: usize,end: usize,) -> String {let mut entities: Vec<String> = (start..end).filter_map(|index| title_entity_from_role(&roles[index]).map(str::to_string)).filter(|entity| entity != "TITLE").collect();entities.sort();entities.dedup();if entities.is_empty() {let text = candidate_text(tokens, groups, start, end);return title_role_for_text(&text, false);}entities.join("+")}fn title_candidate_score(tokens: &[String], groups: &[Group], start: usize, end: usize) -> isize {let text = (start..end).filter(|&index| roles_candidate_text_group(&groups[index]))131 unmodified linesif let Some(caps) = CJK_TITLE_TRAILING_EPISODE_RE.captures(&piece) {let before = caps.get(1).map(|m| m.as_str()).unwrap_or_default();let episode = caps.get(2).map(|m| m.as_str()).unwrap_or_default();if before.contains("銀河鉄道") && episode == "999" {output_pieces.push(before.to_string());labels.push("B-TITLE".to_string());output_pieces.push(episode.to_string());labels.push("B-TITLE".to_string());continue;}if !before.is_empty() {output_pieces.push(before.to_string());labels.push("B-TITLE".to_string());81 unmodified lines| "SOURCE"| "RESOLUTION"| "SEASON"| "PATH_SEASON") {if matches!(role, "SEASON" | "PATH_SEASON") {if let Some((pieces, labels)) = split_season_token(token) {output_tokens.extend(pieces);output_labels.extend(labels);38 unmodified linesoutput_labels.extend(labels);}} else {if is_title_role(role) && matches!(token.as_str(), "第" | "話" | "话" | "回" | "集"){output_tokens.push(token.clone());output_labels.push("O".to_string());continue;}if is_title_role(role) && token.ends_with('第') && token.chars().count() > 1 {let trimmed = token.trim_end_matches('第').to_string();let (pieces, labels) = normalize_generated_tokens(&[trimmed, "第".to_string()],3 unmodified linesoutput_labels.extend(labels);continue;}if is_title_role(role) {let (pieces, labels) = normalize_title_token(token);output_tokens.extend(pieces);output_labels.extend(labels);11 unmodified linesfn smooth_title_spans(tokens: &[String], labels: &[String]) -> Vec<String> {let joiners = [" ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":", ":", "!", "!", "?", "?",";", ";", ",", ",", "、", "。", "~", "~", "-", "+", "+", "(", ")", "(", ")", "[","]", "【", "】", "<", ">", "<", ">", "「", "」", "「", "」", "《", "》", "☆", "♪", "`","@", "‐", "‑", "–", "—", "−", "$", "$", "∽", "꞉", "♥",];let title_terminal_punctuation = ["!", "!", "?", "?"];let entity_joiners = [" ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":", ":", "!", "!", "?", "?",";", ";", ",", ",", "、", "。", "~", "~", "-", "+", "+", "(", ")", "(", ")", "[","]", "【", "】", "<", ">", "<", ">", "「", "」", "「", "」", "《", "》", "☆", "♪", "`","@", "&", "&", "‐", "‑", "–", "—", "−", "$", "$", "∽", "꞉", "♥",];let mut output = labels.to_vec();for (index, (token, label)) in tokens.iter().zip(labels.iter()).enumerate() {30 unmodified lines.any(|item| item.eq_ignore_ascii_case("lupin"));if nearby_lupin&& next_number.is_some_and(|cursor| {tokens[cursor].chars().all(|ch| ch.is_ascii_digit())&& tokens[cursor].len() <= 2}){output[index] = "B-SEASON".to_string();10 unmodified lineslet mut cursor = index + 1;while cursor < tokens.len() {output[cursor] = "O".to_string();if matches!(tokens[cursor].as_str(), "」" | "」" | "\"" | "'") && cursor > index + 1{break;}cursor += 1;}continue;}if label == "B-TITLE" && matches!(token.as_str(), "中日" | "日中" | "英日" | "日英"){let next_word = (index + 1..tokens.len()).find(|&cursor| tokens[cursor].chars().any(|ch| ch.is_alphanumeric()));if next_word.is_some_and(|cursor| labels[cursor] == "B-SOURCE" && tokens[cursor].contains('语')){output[index] = "B-SOURCE".to_string();continue;}14 unmodified lines.chars().any(|ch| ch.is_alphanumeric() || ('\u{4e00}'..='\u{9fff}').contains(&ch))});let later_episode =(index + 1..tokens.len()).any(|cursor| labels[cursor] == "B-EPISODE");if previous_title_word.is_none() && later_episode {output[index] = "B-SEASON".to_string();continue;}let previous_word =previous_title_word.map(|cursor| tokens[cursor].to_ascii_lowercase());if previous_title_word.is_some() && !matches!(previous_word.as_deref(), Some("lupin")) {output[index] = "B-SEASON".to_string();continue;}53 unmodified linescontinue;}if previous_non_space.is_some_and(|cursor| tokens[cursor] == "第")&& next_non_space.is_some_and(|cursor| {matches!(tokens[cursor].as_str(), "话" | "話" | "回" | "集")|| tokens[cursor].starts_with('话')|| tokens[cursor].starts_with('話')|| tokens[cursor].starts_with('回')|| tokens[cursor].starts_with('集')}){if let Some(cursor) = previous_non_space {output[cursor] = "B-EPISODE".to_string();44 unmodified lineslet followed_by_title_word = (index + 1..tokens.len()).find(|&cursor| {!joiners.contains(&tokens[cursor].as_str())&& !matches!(tokens[cursor].as_str(),"-" | "-" | "," | "," | ":" | ":")}).is_some_and(|cursor| {!matches!(tokens[cursor].as_str(),"[" | "【" | "(" | "(" | "]" | "】") && output.get(cursor).is_some_and(|label| label == "B-TITLE")&& tokens[cursor].chars().any(|ch| ch.is_alphabetic())});if followed_by_title_word && matches!(previous_word.as_deref(), Some("movie" | "part"))27 unmodified linescontinue;}}if label == "O" && token.chars().all(|ch| ch.is_ascii_digit()) && token.len() <= 3 {let previous_non_space = (0..index).rev().find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));let next_non_space = (index + 1..tokens.len()).find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));if previous_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "[" | "【"))&& next_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "]" | "】"))&& output[..index].iter().any(|label| label == "B-TITLE")&& output[index + 1..].iter()2 unmodified linesoutput[index] = "B-EPISODE".to_string();continue;}if previous_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "-" | "-"))&& output[..index].iter().any(|label| label == "B-TITLE")&& output[index + 1..].iter()22 unmodified lineslet next_non_space = (index + 1..tokens.len()).find(|&cursor| !tokens[cursor].chars().all(char::is_whitespace));if previous_non_space.is_some_and(|cursor| tokens[cursor] == "第")&& next_non_space.is_some_and(|cursor| {matches!(tokens[cursor].as_str(), "话" | "話" | "回" | "集")}){if let Some(cursor) = previous_non_space {output[cursor] = "B-EPISODE".to_string();12 unmodified linesif left_title {output[index] = "B-TITLE".to_string();if let Some(next_word) = (index + 1..tokens.len()).find(|&cursor| {labels[cursor] == "O" && tokens[cursor].chars().any(|ch| ch.is_alphabetic())}) {output[next_word] = "B-TITLE".to_string();}57 unmodified linesoutput[index] = "B-TITLE".to_string();}}if matches!(token.as_str(),"]" | "】" | ")" | ")" | ">" | ">" | "」" | "」") && index > 0&& output[index - 1] == "B-TITLE"&& title_span_has_labeled_opener(&tokens[..index], &output[..index], token){29 unmodified lines)}fn retag_semantic_labels(tokens: &[String], labels: &[String]) -> Vec<String> {let last_path = tokens.iter().rposition(|token| token == "/" || token == "\\");let mut output = labels.to_vec();for index in 0..labels.len() {let Some(entity) = label_entity(&labels[index]) else {continue;};let prefix = if labels[index].starts_with("I-") {"I"} else {"B"};if entity == "TITLE" {let path_title = last_path.is_some_and(|path_index| index < path_index);let suffix = title_suffix_for_label_index(tokens, labels, index);output[index] = format!("{prefix}-{}_{}",if path_title { "PATH_TITLE" } else { "TITLE" },suffix);} else if entity == "SEASON" && last_path.is_some_and(|path_index| index < path_index) {output[index] = format!("{prefix}-PATH_SEASON");}}output}fn title_suffix_for_label_index(tokens: &[String],labels: &[String],index: usize,) -> &'static str {if let Some(suffix) = direct_title_suffix(&tokens[index]) {return suffix;}let left = nearest_title_suffix(tokens, labels, index, true);let right = nearest_title_suffix(tokens, labels, index, false);match (left, right) {(Some(left), Some(right)) if left == right => left,(Some(left), None) => left,(None, Some(right)) => right,_ => "MIXED",}}fn nearest_title_suffix(tokens: &[String],labels: &[String],index: usize,search_left: bool,) -> Option<&'static str> {let mut cursor = index as isize;loop {cursor += if search_left { -1 } else { 1 };if cursor < 0 || cursor as usize >= tokens.len() {return None;}let cursor = cursor as usize;if !is_title_label(&labels[cursor]) {if tokens[cursor].chars().all(|ch| ch.is_whitespace() || !ch.is_alphanumeric()){continue;}return None;}if let Some(suffix) = direct_title_suffix(&tokens[cursor]) {return Some(suffix);}}}fn direct_title_suffix(token: &str) -> Option<&'static str> {if !token.chars().any(|ch| {ch.is_ascii_alphabetic()|| ('\u{3040}'..='\u{30ff}').contains(&ch)|| ('\u{31f0}'..='\u{31ff}').contains(&ch)|| ('\u{4e00}'..='\u{9fff}').contains(&ch)}) {return None;}Some(title_language_suffix(token))}fn dmhy_record(filename: &str, template_id: &str, roles: &[String]) -> Option<Record> {let (key, tokens, _classes, groups) = template_key_for_filename(filename);if groups.len() != roles.len() {return None;}let roles = adjust_contextual_roles(&tokens, &groups, roles);let roles = refine_semantic_roles(&tokens, &groups, &roles);let (roles, dropped) = enforce_single_title_candidate(&tokens, &groups, &roles);let (tokens, labels) = project_refined_tokens(&tokens, &groups, &roles);let (tokens, labels) = repair_compact_sxe_tokens(tokens, labels);let labels = smooth_title_spans(&tokens, &labels);let labels = retag_semantic_labels(&tokens, &labels);if tokens.len() != labels.len() {return None;}17 unmodified linesmod tests {use super::*;fn schema_labels_for(filename: &str) -> Vec<(String, String)> {let (key, _, _, _) = template_key_for_filename(filename);let roles = suggested_roles(&key);let record = dmhy_record(filename, "tpl_test", &roles).unwrap();record.tokens.into_iter().zip(record.labels).collect()}fn labels_for(filename: &str) -> Vec<(String, String)> {schema_labels_for(filename).into_iter().map(|(token, label)| (token, legacy_label(&label))).collect()}fn legacy_label(label: &str) -> String {let Some(entity) = label_entity(label) else {return label.to_string();};let prefix = if label.starts_with("I-") { "I" } else { "B" };if is_title_entity(entity) {return format!("{prefix}-TITLE");}if entity == "PATH_SEASON" {return format!("{prefix}-SEASON");}if entity == "TAG" {return format!("{prefix}-SPECIAL");}label.to_string()}#[test]fn rich_title_candidates_keep_readable_spacing() {let row = rich_annotation_for(6 unmodified lines);}#[test]fn semantic_schema_roles_cover_multilingual_tags_paths_and_music_skips() {let gm = schema_labels_for("[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4",);assert!(gm.contains(&("GM".to_string(), "B-GROUP".to_string())));assert!(gm.contains(&("国漫".to_string(), "B-TAG".to_string())));assert!(gm.contains(&("神印王座".to_string(), "B-TITLE_CHS".to_string())));assert!(gm.contains(&("Throne".to_string(), "B-TITLE_LATIN".to_string())));assert!(gm.contains(&("Seal".to_string(), "B-TITLE_LATIN".to_string())));assert!(gm.contains(&("2022".to_string(), "B-TAG".to_string())));assert!(gm.contains(&("200".to_string(), "B-EPISODE".to_string())));let sky = schema_labels_for("[Skytree][海贼王][One_Piece][918][GB_JP][1080P]");assert!(sky.contains(&("Skytree".to_string(), "B-GROUP".to_string())));assert!(sky.contains(&("海贼王".to_string(), "B-TITLE_CHS".to_string())));assert!(sky.contains(&("One".to_string(), "B-TITLE_LATIN".to_string())));assert!(sky.contains(&("Piece".to_string(), "B-TITLE_LATIN".to_string())));assert!(sky.contains(&("918".to_string(), "B-EPISODE".to_string())));let farming = schema_labels_for("異世界悠閒農家 2 - 06");assert!(farming.contains(&("異世界悠閒農家".to_string(), "B-TITLE_CHT".to_string())));assert!(farming.contains(&("2".to_string(), "B-SEASON".to_string())));assert!(farming.contains(&("06".to_string(), "B-EPISODE".to_string())));let hanako = schema_labels_for("地縛少年花子君 2 - 13");assert!(hanako.contains(&("地縛少年花子君".to_string(), "B-TITLE_JPN".to_string())));assert!(hanako.contains(&("2".to_string(), "B-SEASON".to_string())));assert!(hanako.contains(&("13".to_string(), "B-EPISODE".to_string())));let one_piece = schema_labels_for("One.Piece.1110");assert!(one_piece.contains(&("One".to_string(), "B-TITLE_LATIN".to_string())));assert!(one_piece.contains(&("Piece".to_string(), "B-TITLE_LATIN".to_string())));assert!(one_piece.contains(&("1110".to_string(), "B-EPISODE".to_string())));assert!(!one_piece.contains(&("1110".to_string(), "B-SEASON".to_string())));let nekomoe_prefix = schema_labels_for("[喵萌奶茶屋][7月新番][Lycoris Recoil][01][1080P]");assert!(nekomoe_prefix.contains(&("喵萌奶茶屋".to_string(), "B-GROUP".to_string())));assert!(nekomoe_prefix.contains(&("7月新番".to_string(), "B-TAG".to_string())));assert!(nekomoe_prefix.contains(&("Lycoris".to_string(), "B-TITLE_LATIN".to_string())));let subtitle_group = schema_labels_for("[桜都字幕组][Title][01][1080P]");assert!(subtitle_group.contains(&("桜都字幕组".to_string(), "B-GROUP".to_string())));let path = schema_labels_for("海贼王/Season 2/One Piece - 01 [1080P]");assert!(path.contains(&("海贼王".to_string(), "B-PATH_TITLE_CHS".to_string())));assert!(path.contains(&("2".to_string(), "B-PATH_SEASON".to_string())));assert!(path.contains(&("One".to_string(), "B-TITLE_LATIN".to_string())));assert!(path.contains(&("01".to_string(), "B-EPISODE".to_string())));let tags = schema_labels_for("[日漫][剧场版][Movie][TV][2024][Title][01][1080P]");assert!(tags.contains(&("日漫".to_string(), "B-TAG".to_string())));assert!(tags.contains(&("剧场版".to_string(), "B-TAG".to_string())));assert!(tags.contains(&("Movie".to_string(), "B-TAG".to_string())));assert!(tags.contains(&("TV".to_string(), "B-TAG".to_string())));assert!(tags.contains(&("2024".to_string(), "B-TAG".to_string())));assert!(tags.contains(&("Title".to_string(), "B-TITLE_LATIN".to_string())));for skipped in ["[Group] Title OST [FLAC]","[Group] Title MUSICCLIP [BDRip]","[Group] Title Music Collection [FLAC]","[Group] Title Character Song [MP3]","[Group] Title Drama CD [FLAC]","[Group] Title CD Album [FLAC]","[Group] Title Bonus CD [FLAC]","[Group] Title Soundtrack [FLAC]",] {assert!(has_music_collection_noise(skipped), "{skipped}");}for preserved in ["[Group] Title OP [FLAC]","[Group] Title ED [FLAC]","[Group] Title NCOP [FLAC]","[Group] Title NCED [FLAC]","[Group] Title PV [1080P]","[Group] Title CM [1080P]","[Group] Title Menu [1080P]","[Group] Title Trailer [1080P]",] {assert!(!has_music_collection_noise(preserved), "{preserved}");}}#[test]fn required_regressions() {let title_91 = labels_for("Title 91 EP 01 [1080p]");assert!(title_91.contains(&("91".to_string(), "B-SEASON".to_string())));assert!(title_91.contains(&("EP".to_string(), "O".to_string())));assert!(title_91.contains(&("01".to_string(), "B-EPISODE".to_string())));42 unmodified linesassert!(!episode_version_title.contains(&("10v2".to_string(), "B-TITLE".to_string())));let episode_version_lang =labels_for("[GalaxyRailroad-888] Yu-Gi-Oh! GO RUSH !! [043v2_GB]");assert!(episode_version_lang.contains(&("043v2".to_string(), "B-EPISODE".to_string())));assert!(episode_version_lang.contains(&("GB".to_string(), "B-SOURCE".to_string())));let cursed = labels_for("[Coalgirls]_C3-Cube_x_Cursed_x_Curious_01_[8E416230]");36 unmodified lineslet music_title =labels_for("[アニメ BD] うたの☆プリンスさまっ♪ マジLOVE2000% 第01話「ポワゾンKISS」(1920x1080 x264 Hi10p AAC)");assert!(music_title.contains(&("♪".to_string(), "B-TITLE".to_string())));let cm_version =labels_for("[U2-Rip]Inari, Konkon, Koi Iroha[CMv2][Hi10p_1080p][x264_flac]");assert!(cm_version.contains(&("CMv2".to_string(), "B-SPECIAL".to_string())));assert!(!cm_version.contains(&("CMv2".to_string(), "B-TITLE".to_string())));let hdma_block = labels_for("[Niconeiko Works] Gekijouban Violet Evergarden [1080P_Ma10p_DTS-HDMA][CM01]",);assert!(hdma_block.contains(&("Gekijouban".to_string(), "B-TITLE".to_string())));assert!(hdma_block.contains(&("1080P".to_string(), "B-RESOLUTION".to_string())));assert!(hdma_block.contains(&("HDMA".to_string(), "B-SOURCE".to_string())));23 unmodified linesassert!(!zom.contains(&("100".to_string(), "B-EPISODE".to_string())));assert!(zom.contains(&("Animatics02".to_string(), "B-SPECIAL".to_string())));let sky = schema_labels_for("[Skytree][海贼王][One_Piece][918][GB_JP][1080P]");assert!(sky.contains(&("海贼王".to_string(), "B-TITLE_CHS".to_string())));assert!(sky.contains(&("One".to_string(), "B-TITLE_LATIN".to_string())));assert!(sky.contains(&("Piece".to_string(), "B-TITLE_LATIN".to_string())));assert!(sky.contains(&("918".to_string(), "B-EPISODE".to_string())));let happy =labels_for("My.Happy.Marriage.S01E01.The.Meeting.1080p.NF.WEB-DL.AAC2.0.H.264-VARYG");assert!(happy.contains(&("01".to_string(), "B-SEASON".to_string())));assert!(happy.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!happy.contains(&("0".to_string(), "B-EPISODE".to_string())));9 unmodified linesassert!(!akira.contains(&("AVC".to_string(), "B-TITLE".to_string())));assert!(akira.contains(&("AVC".to_string(), "B-SOURCE".to_string())));let doraemon = labels_for("[DORASUB][DORAEMON1979][1998.03.07][WEB][1998x1080][AVC][简日]哆啦A梦归来了",);assert!(doraemon.contains(&("DORAEMON1979".to_string(), "B-TITLE".to_string())));assert!(doraemon.contains(&("WEB".to_string(), "B-SOURCE".to_string())));assert!(!doraemon.contains(&("WEB".to_string(), "B-TITLE".to_string())));15 unmodified linesassert!(bang_season.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!bang_season.contains(&("01".to_string(), "B-SEASON".to_string())));let basket = labels_for("[Nekomoe kissaten&VCB-Studio] Fruits Basket 1st Season [24][1080p][x264_aac][sc]",);assert!(basket.contains(&("Fruits".to_string(), "B-TITLE".to_string())));assert!(basket.contains(&("1st".to_string(), "B-SEASON".to_string())));assert!(basket.contains(&("Season".to_string(), "B-SEASON".to_string())));9 unmodified linesassert!(full.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!full.contains(&("01".to_string(), "B-TITLE".to_string())));let r18 =labels_for("[HYSUB]Skirt no Naka wa Kedamono Deshita.[01_R18][BIG5_MP4][1280X720]");assert!(r18.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!r18.contains(&("01".to_string(), "B-TITLE".to_string())));let ddp = labels_for("Akuma.Kun.S01E02.1080p.NF.WEB-DL.DDP5.1.H.264");assert!(ddp.contains(&("02".to_string(), "B-EPISODE".to_string())));assert!(!ddp.contains(&("1".to_string(), "B-EPISODE".to_string())));assert!(ddp.iter().any(|(token, label)| token.starts_with("DDP") && label == "B-SOURCE"));let aac_space = labels_for("Bleach S01E02 AAC 2.0 H.264");assert!(aac_space.contains(&("02".to_string(), "B-EPISODE".to_string())));11 unmodified linesassert!(air_episode.contains(&("Air".to_string(), "B-TITLE".to_string())));assert!(air_episode.contains(&("01".to_string(), "B-EPISODE".to_string())));let decimal_episode =labels_for("[HoneyGod] Usagi Drop [02.5][x264_10bit][粤日双语][BDrip_1080p]");assert!(decimal_episode.contains(&("02".to_string(), "B-EPISODE".to_string())));assert!(decimal_episode.contains(&(".".to_string(), "B-EPISODE".to_string())));assert!(decimal_episode.contains(&("5".to_string(), "B-EPISODE".to_string())));39 unmodified linesassert!(gundam.contains(&("00".to_string(), "B-TITLE".to_string())));assert!(gundam.contains(&("01".to_string(), "B-EPISODE".to_string())));let spy =labels_for("[Studio GreenTea] Spy x Family [38][WebRip][HEVC-10bit 1080p AAC ASSx2]");assert!(spy.contains(&("Studio".to_string(), "B-GROUP".to_string())));assert!(spy.contains(&("Spy".to_string(), "B-TITLE".to_string())));assert!(spy.contains(&("x".to_string(), "B-TITLE".to_string())));1 unmodified lineassert!(spy.contains(&("38".to_string(), "B-EPISODE".to_string())));assert!(!spy.contains(&("Spy".to_string(), "B-SPECIAL".to_string())));let spy_s3 = labels_for("[Feibanyama] SPY x FAMILY S3 - 01 [IQIYI WebRip 2160p HEVC-10bit OPUS Multi-Subs]",);assert!(spy_s3.contains(&("Feibanyama".to_string(), "B-GROUP".to_string())));assert!(spy_s3.contains(&("SPY".to_string(), "B-TITLE".to_string())));assert!(spy_s3.contains(&("FAMILY".to_string(), "B-TITLE".to_string())));assert!(spy_s3.contains(&("3".to_string(), "B-SEASON".to_string())));assert!(spy_s3.contains(&("01".to_string(), "B-EPISODE".to_string())));let slime =labels_for("[Nekomoe kissaten&VCB-Studio] Slime 300 [Menu01][Ma10p_1080p][x265_flac]");assert!(slime.contains(&("Slime".to_string(), "B-TITLE".to_string())));assert!(slime.contains(&("300".to_string(), "B-TITLE".to_string())),72 unmodified linesassert!(was_trimmed);assert_eq!(trimmed, "Avatar The Last Airbender S2 14 [1080p]");let plain_season_dir ="Season 1/[Kamigami] Junjou Romantica 1 - 01 [BD 1280x720 x264 AAC Sub(Chs,Jap)]";let (trimmed, was_trimmed) = training_filename_for(plain_season_dir);assert!(was_trimmed);assert_eq!(8 unmodified lines"[Airota&ANK-Raws] 亜人ちゃんは語りたい (BDrip 1920x1080 HEVC-YUV420P10 FLAC SUP)/Menu (Vol.1)";let (trimmed, was_trimmed) = training_filename_for(menu_parent);assert!(was_trimmed);assert_eq!(trimmed,"[Airota&ANK-Raws] 亜人ちゃんは語りたい Menu (Vol.1)");assert!(has_encoding_noise("[4K_SDR][DBD-Raws&HKG瀛楀箷绲刔[鏃ュ湪鏍″湌][01][2160P]"));assert!(has_encoding_noise("ATRI -My Dear Moments-/娆″洖浜堝憡 EP01 Log01"));assert!(has_encoding_noise("[2002-2003] Mew Mew_鏉变含鍠靛柕(鏉变含銉熴儱銈︺儫銉ャ偊)_TV"));50 unmodified lines"Season 4 E07 - The New Woody Woodpecker Show (Season 1-4) (1999-2002) WEB-DL 720p");let najica ="[2001] Najica_七虹香電擊作戰(ナジカ電撃作戦)_TV/SourceUnknown.RMVB.640x480.twHard/01";let (trimmed, was_trimmed) = training_filename_for(najica);assert!(was_trimmed);assert_eq!(trimmed, "[2001] Najica_七虹香電擊作戰(ナジカ電撃作戦) 01");5 unmodified lineslet galient = "[1984-1986] Galient_機甲界(機甲界ガリアン)_TV.OVA/[1984-1985] Galient_機甲界(機甲界ガリアン)_TV/DVDRip.MKV.720x480.ruSub.左右黑邊保留/01";let (trimmed, was_trimmed) = training_filename_for(galient);assert!(was_trimmed);assert_eq!(trimmed, "[1984-1985] Galient_機甲界(機甲界ガリアン) 01");let galient_labels = labels_for(&trimmed);assert!(galient_labels.contains(&("Galient".to_string(), "B-TITLE".to_string())));assert!(!galient_labels.contains(&("TV".to_string(), "B-TITLE".to_string())));2 unmodified lineslet nced = "[BDrip] Ao no Exorcist Yuki no Hate Hen S04 [343-Labs]/NCED";let (trimmed, was_trimmed) = training_filename_for(nced);assert!(was_trimmed);assert_eq!(trimmed,"[BDrip] Ao no Exorcist Yuki no Hate Hen S04 [343-Labs] NCED");let sakura ="Card Captor Sakura Chinese/魔卡少女樱(台配国语)/第01集 小樱与不可思议的魔法书";let (trimmed, was_trimmed) = training_filename_for(sakura);assert!(was_trimmed);assert_eq!(12 unmodified linesassert!(volume.contains(&("MENU02".to_string(), "B-SPECIAL".to_string())));assert!(!volume.contains(&("01".to_string(), "B-EPISODE".to_string())));let aria_notice = labels_for("[KNA-Subs&ANK-Raws] 緋弾のアリアAA 番宣1 (BDrip 1920x1080 HEVC-YUV420P10 FLAC)",);assert!(aria_notice.contains(&("緋弾のアリア".to_string(), "B-TITLE".to_string())));assert!(aria_notice.contains(&("番宣".to_string(), "B-SPECIAL".to_string())));assert!(aria_notice.contains(&("1".to_string(), "B-SPECIAL".to_string())));39 unmodified linesassert!(!mahoro.contains(&("Full".to_string(), "B-TITLE".to_string())));assert!(mahoro.contains(&("01".to_string(), "B-EPISODE".to_string())));let kitaro = labels_for("[1985.10-1988.02] Kitaro_鬼太郎 第3期(ゲゲゲの鬼太郎)_TV 036 異次元妖怪かまなり",);assert!(kitaro.contains(&("Kitaro".to_string(), "B-TITLE".to_string())));assert!(kitaro.contains(&("3".to_string(), "B-SEASON".to_string())));assert!(kitaro.contains(&("036".to_string(), "B-EPISODE".to_string())));49 unmodified linesassert!(ghiblies.contains(&("2".to_string(), "B-TITLE".to_string())));assert!(!ghiblies.contains(&("2".to_string(), "B-EPISODE".to_string())));let tv_spot =labels_for("[RUELL-Next] Fruits Basket TV Spot 1 (DVD 768x576 x264 AAC) [49531416]");assert!(tv_spot.contains(&("TV".to_string(), "B-SPECIAL".to_string())));assert!(tv_spot.contains(&("1".to_string(), "B-SPECIAL".to_string())));assert!(!tv_spot.contains(&("1".to_string(), "B-EPISODE".to_string())));8 unmodified linesassert!(hi10_source.contains(&("Hi10".to_string(), "B-SOURCE".to_string())));assert!(!hi10_source.contains(&("Hi10".to_string(), "B-GROUP".to_string())));let souten = labels_for("[苍天之拳].[Fosky_Fansub][Souten_No_Ken][DVDRIP][01][H.264_FLAC][848x480][CDD495FC]",);assert!(souten.contains(&("Fosky".to_string(), "B-GROUP".to_string())));assert!(!souten.contains(&("苍天之拳".to_string(), "B-GROUP".to_string())));assert!(souten.contains(&("Souten".to_string(), "B-TITLE".to_string())));let bonjour = labels_for("(2014Q4) Bonjour♪恋味パティスリー 第01話 「Lesson 1」 (1280x720 x265 10bit AAC)",);assert!(bonjour.contains(&("01".to_string(), "B-EPISODE".to_string())));assert!(!bonjour.contains(&("1".to_string(), "B-EPISODE".to_string())));let durarara =labels_for("[VCB-Studio] Durarara!!×2 Ketsu [Menu01][Ma10p_1080p][x265_flac]");assert!(durarara.contains(&("Durarara".to_string(), "B-TITLE".to_string())));assert!(durarara.contains(&("2".to_string(), "B-TITLE".to_string())));assert!(!durarara.contains(&("2".to_string(), "B-EPISODE".to_string())));13 unmodified linesassert!(bleach_movie.contains(&("3".to_string(), "B-TITLE".to_string())));assert!(!bleach_movie.contains(&("3".to_string(), "B-EPISODE".to_string())));let conan_movie = labels_for("[DBD-Raws][Detective Conan Movie 27 The Million-Dollar Pentagram][PV][01][1080P]",);assert!(conan_movie.contains(&("27".to_string(), "B-TITLE".to_string())));assert!(conan_movie.contains(&("PV".to_string(), "B-SPECIAL".to_string())));let madoka_movie = labels_for("[DBD-Raws][Puella Magi Madoka Magica the Movie 01 Beginnings][NCED][1080P]",);assert!(madoka_movie.contains(&("01".to_string(), "B-TITLE".to_string())));assert!(madoka_movie.contains(&("Beginnings".to_string(), "B-TITLE".to_string())));13 unmodified linesassert!(lapis.contains(&("꞉".to_string(), "B-TITLE".to_string())));assert!(lapis.contains(&("LiGHTs".to_string(), "B-TITLE".to_string())));let rezero =labels_for("TVアニメ『Re:ゼロから始める異世界生活』第10話「鬼がかったやり方」予告");assert!(!rezero.contains(&("TV".to_string(), "B-TITLE".to_string())));assert!(!rezero.contains(&("アニメ".to_string(), "B-TITLE".to_string())));assert!(rezero.contains(&("Re".to_string(), "B-TITLE".to_string())));4 unmodified linesassert!(!shark.contains(&("アニメ".to_string(), "B-TITLE".to_string())));assert!(shark.contains(&("おでかけ子ザメ".to_string(), "B-TITLE".to_string())));let creditless =labels_for("[ANK-Raws] デート・ア・ライブⅡ Creditless ED (Bdrip 1920x1080 HEVC FLAC)");assert!(creditless.contains(&("Creditless".to_string(), "B-SPECIAL".to_string())));assert!(creditless.contains(&("ED".to_string(), "B-SPECIAL".to_string())));1 unmodified lineassert!(no_number.contains(&("081".to_string(), "B-EPISODE".to_string())));assert!(!no_number.contains(&("1".to_string(), "B-EPISODE".to_string())));let bilingual = labels_for("辉夜大小姐想让我告白~天才们的恋爱头脑战~.S2-01.中日双语.云光字幕组.[1080p]",);assert!(bilingual.contains(&("中日".to_string(), "B-SOURCE".to_string())));assert!(!bilingual.contains(&("中日".to_string(), "B-TITLE".to_string())));18 unmodified linesassert!(one_room.contains(&("Second".to_string(), "B-SEASON".to_string())));assert!(one_room.contains(&("Season".to_string(), "B-SEASON".to_string())));let jade =labels_for("[GM-Team][国漫][诛仙 第2季][Jade Dynasty Ⅱ][2024][12][AVC][GB][1080P]");assert!(jade.contains(&("Jade".to_string(), "B-TITLE".to_string())));assert!(jade.contains(&("Dynasty".to_string(), "B-TITLE".to_string())));assert!(jade.contains(&("Ⅱ".to_string(), "B-SEASON".to_string())));16 unmodified linesassert!(fox.contains(&("Fox".to_string(), "B-TITLE".to_string())));assert!(fox.contains(&("Ⅷ".to_string(), "B-SEASON".to_string())));let kage =labels_for("[LKSUB][Kage no Jitsuryokusha ni Naritakute! 2nd Season][03][GB][720P]");assert!(kage.contains(&("2nd".to_string(), "B-SEASON".to_string())));assert!(kage.contains(&(" ".to_string(), "B-SEASON".to_string())));assert!(kage.contains(&("Season".to_string(), "B-SEASON".to_string())));8 unmodified linesassert!(date_live_special.contains(&("Ⅱ".to_string(), "B-SEASON".to_string())));assert!(date_live_special.contains(&("CM01".to_string(), "B-SPECIAL".to_string())));let lupin_part = labels_for("[SnowDream][Part 5_Lupin Sansei Part 5][01][BIG5][720P]");assert!(lupin_part.contains(&("Lupin".to_string(), "B-TITLE".to_string())));assert!(lupin_part.contains(&("Sansei".to_string(), "B-TITLE".to_string())));assert!(!lupin_part.contains(&("Part".to_string(), "B-TITLE".to_string())));assert!(lupin_part.contains(&("5".to_string(), "B-SEASON".to_string())));assert!(!lupin_part.contains(&("5".to_string(), "B-SPECIAL".to_string())));let roman_leaf = dmhy_record("Ⅰ 001 魯邦燃起了鬥志","tpl_test",&suggested_roles("TEXT SEP EPISODE SEP TEXT"),).unwrap();assert!(roman_leaf.tokens.iter()43 unmodified linesassert!(ajin_movie.contains(&("Ajin".to_string(), "B-TITLE".to_string())));assert!(ajin_movie.contains(&("01".to_string(), "B-SPECIAL".to_string())));let eien = labels_for("[Nekomoe kissaten&LoliHouse] Eien no 831 [WebRip 1080p HEVC-10bit AAC ASSx2]",);assert!(eien.contains(&("Eien".to_string(), "B-TITLE".to_string())));assert!(eien.contains(&("831".to_string(), "B-TITLE".to_string())));let ep_only =dmhy_record("Ep.25", "tpl_test", &suggested_roles("TEXT SEP EPISODE")).unwrap();assert!(audit_warnings(&ep_only).contains(&"no_title".to_string()));}}
50 unmodified lines515253545556158 unmodified lines2152162172182192202211 unmodified line2232242252262272282292302312322332342352362372382392 unmodified lines2422432442452462472483 unmodified lines25225325425525625725835 unmodified lines2942952962972982993003013023033042 unmodified lines3073083093103113123134 unmodified lines3183193203213223233242 unmodified lines32732832933033133233333433533633733833922 unmodified lines36236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541611 unmodified lines428429430431432433101 unmodified lines53553653753853954054113 unmodified lines55555655755855956056156228 unmodified lines59159259359459550 unmodified linessource: Option<String>,}fn main() -> Result<()> {let args = Args::parse();let target_re = Regex::new(158 unmodified linesfn build_combo_variants(row: &CharRow, max_chars: usize) -> Vec<CharRow> {let entities = extract_entities_from_labels(&row.tokens, &row.labels);let title = first_value(&entities, "TITLE");let season = first_value(&entities, "SEASON");let episode = first_value(&entities, "EPISODE");let special = first_value(&entities, "SPECIAL");1 unmodified linelet source = first_value(&entities, "SOURCE");let mut specs: Vec<(String, Vec<(String, String)>, &'static str)> = Vec::new();if let Some(title) = title.clone() {specs.push((title.clone(),vec![(title.clone(), "TITLE".to_string())],"combo_title",));if let Some(season) = season.clone() {specs.push((format!("{title} {season}"),vec![(title.clone(), "TITLE".to_string()),(season.clone(), "SEASON".to_string()),],"combo_title_season",2 unmodified linesspecs.push((format!("{title} {season} {episode}"),vec![(title.clone(), "TITLE".to_string()),(season.clone(), "SEASON".to_string()),(episode.clone(), "EPISODE".to_string()),],3 unmodified linesspecs.push((format!("{title} {season} {episode} [{resolution}][{source}]"),vec![(title.clone(), "TITLE".to_string()),(season.clone(), "SEASON".to_string()),(episode.clone(), "EPISODE".to_string()),(resolution.clone(), "RESOLUTION".to_string()),35 unmodified lines"combo_special_only",));}if let (Some(title), Some(special)) = (title.clone(), special.clone()) {specs.push((format!("{title} - {special}"),vec![(title.clone(), "TITLE".to_string()),(special.clone(), "SPECIAL".to_string()),],"combo_title_special",2 unmodified linesspecs.push((format!("{title} - {special} [{episode}]"),vec![(title.clone(), "TITLE".to_string()),(special.clone(), "SPECIAL".to_string()),(episode, "EPISODE".to_string()),],4 unmodified linesspecs.push((format!("{title} - {special} [{resolution}][{source}]"),vec![(title, "TITLE".to_string()),(special, "SPECIAL".to_string()),(resolution.clone(), "RESOLUTION".to_string()),(source, "SOURCE".to_string()),2 unmodified lines));}}if let (Some(title), Some(resolution), Some(source)) =(title, resolution.clone(), source.clone()){specs.push((format!("{title} [{resolution}][{source}]"),vec![(title.clone(), "TITLE".to_string()),(resolution.clone(), "RESOLUTION".to_string()),(source, "SOURCE".to_string()),],22 unmodified lineslet mut active_entity: Option<String> = None;let mut active_tokens: Vec<String> = Vec::new();for (token, label) in tokens.iter().zip(labels.iter()) {if let Some(rest) = label.strip_prefix("B-") {if let Some(entity) = active_entity.take() {if !active_tokens.is_empty() {entities.entry(entity).or_default().push(active_tokens.join(""));}}active_entity = Some(rest.to_string());active_tokens = vec![token.clone()];} else if let Some(rest) = label.strip_prefix("I-") {if active_entity.as_deref() == Some(rest) {active_tokens.push(token.clone());} else {if let Some(entity) = active_entity.take() {if !active_tokens.is_empty() {entities.entry(entity).or_default().push(active_tokens.join(""));}}active_entity = Some(rest.to_string());active_tokens = vec![token.clone()];}} else {if let Some(entity) = active_entity.take() {if !active_tokens.is_empty() {entities.entry(entity).or_default().push(active_tokens.join(""));}}active_tokens.clear();}}if let Some(entity) = active_entity.take() {if !active_tokens.is_empty() {entities.entry(entity).or_default().push(active_tokens.join(""));}}entities}fn first_value(entities: &HashMap<String, Vec<String>>, name: &str) -> Option<String> {11 unmodified linesif text.is_empty() {continue;}if let Some(start) = find_substring(filename, text, cursor) {let end = start + text.chars().count();if start < labels.len() {101 unmodified lineslet row = make_row("One Piece Season 21 1110 [1080p][WEB-DL].mkv",&[("One Piece".to_string(), "TITLE".to_string()),("Season 21".to_string(), "SEASON".to_string()),("1110".to_string(), "EPISODE".to_string()),("1080p".to_string(), "RESOLUTION".to_string()),13 unmodified linesassert_eq!(&combo.labels[0..9],&["B-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE","I-TITLE", "I-TITLE"]);assert_eq!(28 unmodified linesassert_eq!(combo.labels[31], "O");assert_eq!(combo.labels[32], "O");assert_eq!(combo.labels[39], "O");}}50 unmodified lines51525354555657585960616263646566676869707172158 unmodified lines2312322332342352362371 unmodified line2392402412422432442452462472482492502512522532542552 unmodified lines2582592602612622632643 unmodified lines26826927027127227327435 unmodified lines3103113123133143153163173183193202 unmodified lines3233243253263273283294 unmodified lines3343353363373383393402 unmodified lines34334434534634734834935035135235335435522 unmodified lines37837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148211 unmodified lines494495496497498499500501101 unmodified lines60360460560660760860913 unmodified lines62362462562662762862963063163263363463563663728 unmodified lines66666766866967067167267367450 unmodified linessource: Option<String>,}const FILE_TITLE_ENTITIES: [&str; 5] = ["TITLE_CHS","TITLE_CHT","TITLE_JPN","TITLE_LATIN","TITLE_MIXED",];const PATH_TITLE_ENTITIES: [&str; 5] = ["PATH_TITLE_CHS","PATH_TITLE_CHT","PATH_TITLE_JPN","PATH_TITLE_LATIN","PATH_TITLE_MIXED",];fn main() -> Result<()> {let args = Args::parse();let target_re = Regex::new(158 unmodified linesfn build_combo_variants(row: &CharRow, max_chars: usize) -> Vec<CharRow> {let entities = extract_entities_from_labels(&row.tokens, &row.labels);let title = first_title_value(&entities);let season = first_value(&entities, "SEASON");let episode = first_value(&entities, "EPISODE");let special = first_value(&entities, "SPECIAL");1 unmodified linelet source = first_value(&entities, "SOURCE");let mut specs: Vec<(String, Vec<(String, String)>, &'static str)> = Vec::new();if let Some((title, title_entity)) = title.clone() {specs.push((title.clone(),vec![(title.clone(), title_entity.clone())],"combo_title",));if let Some(season) = season.clone() {specs.push((format!("{title} {season}"),vec![(title.clone(), title_entity.clone()),(season.clone(), "SEASON".to_string()),],"combo_title_season",2 unmodified linesspecs.push((format!("{title} {season} {episode}"),vec![(title.clone(), title_entity.clone()),(season.clone(), "SEASON".to_string()),(episode.clone(), "EPISODE".to_string()),],3 unmodified linesspecs.push((format!("{title} {season} {episode} [{resolution}][{source}]"),vec![(title.clone(), title_entity.clone()),(season.clone(), "SEASON".to_string()),(episode.clone(), "EPISODE".to_string()),(resolution.clone(), "RESOLUTION".to_string()),35 unmodified lines"combo_special_only",));}if let (Some((title, title_entity)), Some(special)) = (title.clone(), special.clone()) {specs.push((format!("{title} - {special}"),vec![(title.clone(), title_entity.clone()),(special.clone(), "SPECIAL".to_string()),],"combo_title_special",2 unmodified linesspecs.push((format!("{title} - {special} [{episode}]"),vec![(title.clone(), title_entity.clone()),(special.clone(), "SPECIAL".to_string()),(episode, "EPISODE".to_string()),],4 unmodified linesspecs.push((format!("{title} - {special} [{resolution}][{source}]"),vec![(title, title_entity),(special, "SPECIAL".to_string()),(resolution.clone(), "RESOLUTION".to_string()),(source, "SOURCE".to_string()),2 unmodified lines));}}if let (Some((title, title_entity)), Some(resolution), Some(source)) =(title, resolution.clone(), source.clone()){specs.push((format!("{title} [{resolution}][{source}]"),vec![(title.clone(), title_entity),(resolution.clone(), "RESOLUTION".to_string()),(source, "SOURCE".to_string()),],22 unmodified lineslet mut active_entity: Option<String> = None;let mut active_tokens: Vec<String> = Vec::new();let flush = |entities: &mut HashMap<String, Vec<String>>,active_entity: &mut Option<String>,active_tokens: &mut Vec<String>| {if let Some(entity) = active_entity.take() {if !active_tokens.is_empty() {push_entity_value(entities, &entity, active_tokens.join(""));}}active_tokens.clear();};for (token, label) in tokens.iter().zip(labels.iter()) {if let Some(rest) = label.strip_prefix("B-") {flush(&mut entities, &mut active_entity, &mut active_tokens);active_entity = canonical_entity(rest);active_tokens = vec![token.clone()];} else if let Some(rest) = label.strip_prefix("I-") {let entity = canonical_entity(rest);if active_entity == entity {active_tokens.push(token.clone());} else {flush(&mut entities, &mut active_entity, &mut active_tokens);active_entity = entity;active_tokens = vec![token.clone()];}} else {flush(&mut entities, &mut active_entity, &mut active_tokens);}}flush(&mut entities, &mut active_entity, &mut active_tokens);entities}fn canonical_entity(entity: &str) -> Option<String> {match entity {"TITLE" | "TITLE_MIXED" => Some("TITLE_MIXED".to_string()),"PATH_TITLE" | "PATH_TITLE_MIXED" => Some("PATH_TITLE_MIXED".to_string()),"TITLE_CHS" | "TITLE_CHT" | "TITLE_JPN" | "TITLE_LATIN" | "PATH_TITLE_CHS"| "PATH_TITLE_CHT" | "PATH_TITLE_JPN" | "PATH_TITLE_LATIN" | "SEASON" | "PATH_SEASON"| "EPISODE" | "SPECIAL" | "GROUP" | "RESOLUTION" | "SOURCE" | "TAG" => {Some(entity.to_string())}_ => None,}}fn path_title_to_file_title(entity: &str) -> Option<String> {entity.strip_prefix("PATH_TITLE_").map(|suffix| format!("TITLE_{suffix}"))}fn file_title_to_path_title(entity: &str) -> Option<String> {entity.strip_prefix("TITLE_").map(|suffix| format!("PATH_TITLE_{suffix}"))}fn push_entity_value(entities: &mut HashMap<String, Vec<String>>, entity: &str, value: String) {let value = value.trim();if value.is_empty() {return;}push_unique(entities, entity, value);if let Some(file_title) = path_title_to_file_title(entity) {push_unique(entities, &file_title, value);}if let Some(path_title) = file_title_to_path_title(entity) {push_unique(entities, &path_title, value);}match entity {"PATH_SEASON" => push_unique(entities, "SEASON", value),"SEASON" => push_unique(entities, "PATH_SEASON", value),_ => {}}}fn push_unique(entities: &mut HashMap<String, Vec<String>>, entity: &str, value: &str) {let values = entities.entry(entity.to_string()).or_default();if !values.iter().any(|existing| existing == value) {values.push(value.to_string());}}fn first_title_value(entities: &HashMap<String, Vec<String>>) -> Option<(String, String)> {for entity in FILE_TITLE_ENTITIES {if let Some(value) = first_value(entities, entity) {return Some((value, entity.to_string()));}}for entity in PATH_TITLE_ENTITIES {if let Some(value) = first_value(entities, entity) {let file_entity =path_title_to_file_title(entity).unwrap_or_else(|| "TITLE_MIXED".to_string());return Some((value, file_entity));}}None}fn first_value(entities: &HashMap<String, Vec<String>>, name: &str) -> Option<String> {11 unmodified linesif text.is_empty() {continue;}let entity = canonical_entity(entity).and_then(|value| path_title_to_file_title(&value).or(Some(value)))?;if let Some(start) = find_substring(filename, text, cursor) {let end = start + text.chars().count();if start < labels.len() {101 unmodified lineslet row = make_row("One Piece Season 21 1110 [1080p][WEB-DL].mkv",&[("One Piece".to_string(), "TITLE_LATIN".to_string()),("Season 21".to_string(), "SEASON".to_string()),("1110".to_string(), "EPISODE".to_string()),("1080p".to_string(), "RESOLUTION".to_string()),13 unmodified linesassert_eq!(&combo.labels[0..9],&["B-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN","I-TITLE_LATIN"]);assert_eq!(28 unmodified linesassert_eq!(combo.labels[31], "O");assert_eq!(combo.labels[32], "O");assert_eq!(combo.labels[39], "O");assert!(!combo.labels.iter().any(|label| label == "B-TITLE" || label == "I-TITLE"));}}
10 unmodified lines111213141516171819202122232425262728102 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661 unmodified line168169170171172173174175176177178179180181182183184185186187188189190191435 unmodified lines6276286296306316326336346356366376386396406416426436446 unmodified lines65165265365465565665765865920 unmodified lines68068168268368468568668768868969069169269334 unmodified lines72872973073173273373441 unmodified lines77677777877978078178278378478578620 unmodified lines8078088098108118128138148158168175 unmodified lines82382482582682782882983083183283383483583683715 unmodified lines85385485585685785885986086186286386486536 unmodified lines90290390490590690790890991091191291391491591635 unmodified lines952953954955956957958959960961962963964965966158 unmodified lines11251126112711281129113011311132113311341135113627 unmodified lines116411651166116711681169117065 unmodified lines1236123712381239124012411242124312441245124612471248124912501251125282 unmodified lines13351336133713381339134024 unmodified lines136513661367136813691370412 unmodified lines17831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180697 unmodified lines190419051906190719081909191025 unmodified lines19361937193819391940194119421943194419453 unmodified lines1949195019511952195319545 unmodified lines19601961196219631964196519663 unmodified lines197019711972197319741975197619775 unmodified lines1983198419851986198719885 unmodified lines1994199519961997199819992000200110 unmodified linesuse std::fs::{self, File};use std::io::{BufRead, BufReader, BufWriter, Write};use std::path::{Path, PathBuf};use std::time::Instant;const ENTITIES: [Entity; 7] = [Entity::Group,Entity::Title,Entity::Season,Entity::Episode,Entity::Special,Entity::Resolution,Entity::Source,];#[derive(Parser, Debug)]#[command(about = "Generate pre-encoded AniFileBERT virtual BIO permutation shards",102 unmodified lines#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize)]enum Entity {Group,Title,Season,Episode,Special,Resolution,Source,}impl Entity {fn index(self) -> usize {match self {Entity::Group => 0,Entity::Title => 1,Entity::Season => 2,Entity::Episode => 3,Entity::Special => 4,Entity::Resolution => 5,Entity::Source => 6,}}fn from_name(name: &str) -> Option<Self> {match name {"GROUP" => Some(Entity::Group),"TITLE" => Some(Entity::Title),"SEASON" => Some(Entity::Season),"EPISODE" => Some(Entity::Episode),"SPECIAL" => Some(Entity::Special),"RESOLUTION" => Some(Entity::Resolution),"SOURCE" => Some(Entity::Source),_ => None,}}1 unmodified linefn b_label(self) -> &'static str {match self {Entity::Group => "B-GROUP",Entity::Title => "B-TITLE",Entity::Season => "B-SEASON",Entity::Episode => "B-EPISODE",Entity::Special => "B-SPECIAL",Entity::Resolution => "B-RESOLUTION",Entity::Source => "B-SOURCE",}}fn i_label(self) -> &'static str {match self {Entity::Group => "I-GROUP",Entity::Title => "I-TITLE",Entity::Season => "I-SEASON",Entity::Episode => "I-EPISODE",Entity::Special => "I-SPECIAL",Entity::Resolution => "I-RESOLUTION",Entity::Source => "I-SOURCE",}}}435 unmodified lines);}let filename = row.filename.clone().unwrap_or_else(|| row.tokens.join(""));let fields = extract_fields(&row.tokens, &row.labels);samples.push(SourceSample {row_index: idx,filename,tokens: row.tokens,labels: row.labels,fields,});}Ok(samples)}fn extract_fields(tokens: &[String], labels: &[String]) -> Vec<Vec<String>> {let mut fields: Vec<Vec<String>> = (0..ENTITIES.len()).map(|_| Vec::new()).collect();let mut seen: Vec<HashSet<String>> = (0..ENTITIES.len()).map(|_| HashSet::new()).collect();6 unmodified linesseen: &mut Vec<HashSet<String>>| {if let Some(entity) = entity {let value = text.trim().to_string();if !value.is_empty() && seen[entity.index()].insert(value.clone()) {fields[entity.index()].push(value);}}text.clear();};20 unmodified linesfields}fn count_variants(sample: &SourceSample, cfg: &GenConfig) -> u128 {let mut count = if cfg.include_original { 1 } else { 0 };count += count_path_variants(sample, cfg) as u128;let available = ENTITIES.iter().copied().filter(|entity| !sample.fields[entity.index()].is_empty()).collect::<Vec<_>>();let n = available.len();if n == 0 || !cfg.include_bio_variants {return count;34 unmodified linesif cfg.path_samples_per_source == 0 || cfg.path_styles.is_empty() {return 0;}if sample.fields[Entity::Title.index()].is_empty() {return 0;}if sample.fields[Entity::Episode.index()].is_empty()41 unmodified linesreturn Ok(());}let available = ENTITIES.iter().copied().filter(|entity| !sample.fields[entity.index()].is_empty()).collect::<Vec<_>>();let n = available.len();for mask in 1usize..(1usize << n) {let mut selected = available20 unmodified lineslet mut rng = StdRng::seed_from_u64(cfg.seed ^ ((sample.row_index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)),);let available = ENTITIES.iter().copied().filter(|entity| !sample.fields[entity.index()].is_empty()).collect::<Vec<_>>();if available.is_empty() {return Ok(());}5 unmodified lineslet mut attempts = 0usize;let mut templates: Vec<Vec<PartChoice>> = Vec::new();if let Some(title) = sample.fields[Entity::Title.index()].first() {templates.push(vec![PartChoice {entity: Entity::Title,value: title.clone(),}]);if let Some(season) = sample.fields[Entity::Season.index()].first() {templates.push(vec![PartChoice {entity: Entity::Title,value: title.clone(),},PartChoice {15 unmodified linesvalue: special.clone(),}]);}if let (Some(title), Some(special)) = (sample.fields[Entity::Title.index()].first(),sample.fields[Entity::Special.index()].first(),) {templates.push(vec![PartChoice {entity: Entity::Title,value: title.clone(),},PartChoice {36 unmodified lines.copied().collect::<Vec<_>>();chosen.shuffle(&mut rng);if !chosen.iter().any(|entity| matches!(entity, Entity::Title | Entity::Episode | Entity::Special)){if let Some(fallback) = available.iter().copied().find(|entity| matches!(entity, Entity::Title | Entity::Episode | Entity::Special)){if !chosen.contains(&fallback) {chosen.push(fallback);}35 unmodified lines.copied().collect::<Vec<_>>();chosen.shuffle(&mut rng);if !chosen.iter().any(|entity| matches!(entity, Entity::Title | Entity::Episode | Entity::Special)){if let Some(fallback) = available.iter().copied().find(|entity| matches!(entity, Entity::Title | Entity::Episode | Entity::Special)){if !chosen.contains(&fallback) {chosen.push(fallback);}158 unmodified linescfg: &GenConfig,rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> {let title = choose_field(sample, Entity::Title, rng)?;let style = *cfg.path_styles.choose(rng)?;let sep = style.separator();let mut components = path_prefix_components(style, rng);components.push(vec![entity_piece(title.clone(), Entity::Title)]);let season_component = choose_path_season_component(sample, rng);if let Some(season) = season_component {27 unmodified linescomponents.push(meta_file_component(sample, rng));}3 => components.push(compact_file_component(endpoint, sample, rng)),4 => components.push(grouped_release_file_component(&title, endpoint, sample, rng)),_ => {components.push(vec![endpoint]);if rng.gen_bool(0.55) {65 unmodified linessample: &SourceSample,rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> {let season = if let Some(source_season) = choose_field(sample, Entity::Season, rng) {random_season_path_text(&source_season, rng)} else {let synthetic = ["Season 1", "Season 01", "S01", "第1季"];synthetic.choose(rng).copied().unwrap_or("Season 1").to_string()};Some(vec![entity_piece(season, Entity::Season)])}fn path_file_component(82 unmodified lines}}}}fn random_episode_path_text(value: &str, rng: &mut StdRng) -> String {24 unmodified linesfn random_season_path_text(value: &str, rng: &mut StdRng) -> String {let mut variants = vec![value.trim().to_string()];if let Some(number) = first_ascii_number(value) {variants.push(format!("Season {number}"));variants.push(format!("Season {number:02}"));variants.push(format!("S{number:02}"));412 unmodified lines}fn label_id(label: &str) -> Option<i16> {Some(match label {"O" => 0,"B-TITLE" => 1,"I-TITLE" => 2,"B-SEASON" => 3,"I-SEASON" => 4,"B-EPISODE" => 5,"I-EPISODE" => 6,"B-SPECIAL" => 7,"I-SPECIAL" => 8,"B-GROUP" => 9,"I-GROUP" => 10,"B-RESOLUTION" => 11,"I-RESOLUTION" => 12,"B-SOURCE" => 13,"I-SOURCE" => 14,_ => return None,})}fn built_in_specials() -> Vec<String> {97 unmodified linesfn sample_without_season() -> SourceSample {let mut fields = vec![Vec::new(); ENTITIES.len()];fields[Entity::Title.index()] = vec!["Example Show".to_string()];fields[Entity::Episode.index()] = vec!["1".to_string()];fields[Entity::Resolution.index()] = vec!["1080P".to_string()];fields[Entity::Source.index()] = vec!["WEB-DL".to_string()];25 unmodified linesassert!(non_empty_components >= 2,"expected at least two noise directories for {style:?}: {}",render_labeled_pieces(&join_path_components(&components,style.separator())));assert!(components.iter()3 unmodified lines}}#[test]fn path_context_synthesizes_season_between_title_and_episode() {let sample = sample_without_season();5 unmodified lineslet text = render_labeled_pieces(&pieces);assert!(text.contains("Example Show"));assert!(text.contains("Season") || text.contains("S01") || text.contains("第1季"),"missing synthetic season directory in {text}");3 unmodified linesfor piece in &pieces {match piece.entity {None if !seen_title => {}Some(Entity::Title) => seen_title = true,Some(Entity::Season) if seen_title => seen_season_after_title = true,Some(Entity::Episode) if seen_season_after_title => {seen_episode_after_season = true}5 unmodified linesassert!(seen_episode_after_season);}#[test]fn grouped_path_file_labels_group_but_not_duplicate_title() {let sample = sample_with_group();5 unmodified linesassert!(text.contains("[Erai-raws]"));assert!(text.contains("Example Show"));assert!(text.contains("01"));assert!(pieces.iter().any(|piece| piece.entity == Some(Entity::Group)));assert!(pieces.iter().any(|piece| piece.entity == Some(Entity::Episode)));assert!(pieces.iter().any(|piece| piece.text == "Example Show" && piece.entity.is_none()));10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103102 unmodified lines2062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572581 unmodified line260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363435 unmodified lines7998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378386 unmodified lines84584684784884985085120 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394434 unmodified lines97998098198298398498598698798841 unmodified lines103010311032103310341035103620 unmodified lines10571058105910601061106210635 unmodified lines10691070107110721073107410751076107710781079108010811082108315 unmodified lines109911001101110211031104110511061107110811091110111136 unmodified lines11481149115011511152115311541155115611571158115935 unmodified lines119511961197119811991200120112021203120412051206158 unmodified lines13651366136713681369137013711372137313741375137627 unmodified lines14041405140614071408140914101411141265 unmodified lines147814791480148114821483148414851486148714881489149014911492149314941495149682 unmodified lines1579158015811582158315841585158615871588158915901591159224 unmodified lines1617161816191620162116221623412 unmodified lines203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209097 unmodified lines2188218921902191219221932194219525 unmodified lines22212222222322242225222622273 unmodified lines2231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622875 unmodified lines22932294229522962297229822992300230123023 unmodified lines230623072308230923102311231223135 unmodified lines23192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623675 unmodified lines23732374237523762377237823792380238123822383238410 unmodified linesuse std::fs::{self, File};use std::io::{BufRead, BufReader, BufWriter, Write};use std::path::{Path, PathBuf};use std::sync::OnceLock;use std::time::Instant;const FILE_TITLE_ENTITIES: [Entity; 5] = [Entity::TitleChs,Entity::TitleCht,Entity::TitleJpn,Entity::TitleLatin,Entity::TitleMixed,];const PATH_TITLE_ENTITIES: [Entity; 5] = [Entity::PathTitleChs,Entity::PathTitleCht,Entity::PathTitleJpn,Entity::PathTitleLatin,Entity::PathTitleMixed,];const ENTITIES: [Entity; 18] = [Entity::Group,Entity::TitleChs,Entity::TitleCht,Entity::TitleJpn,Entity::TitleLatin,Entity::TitleMixed,Entity::PathTitleChs,Entity::PathTitleCht,Entity::PathTitleJpn,Entity::PathTitleLatin,Entity::PathTitleMixed,Entity::PathSeason,Entity::Season,Entity::Episode,Entity::Special,Entity::Resolution,Entity::Source,Entity::Tag,];const FALLBACK_LABELS: [&str; 37] = ["O","B-TITLE_CHS","I-TITLE_CHS","B-TITLE_CHT","I-TITLE_CHT","B-TITLE_JPN","I-TITLE_JPN","B-TITLE_LATIN","I-TITLE_LATIN","B-TITLE_MIXED","I-TITLE_MIXED","B-PATH_TITLE_CHS","I-PATH_TITLE_CHS","B-PATH_TITLE_CHT","I-PATH_TITLE_CHT","B-PATH_TITLE_JPN","I-PATH_TITLE_JPN","B-PATH_TITLE_LATIN","I-PATH_TITLE_LATIN","B-PATH_TITLE_MIXED","I-PATH_TITLE_MIXED","B-PATH_SEASON","I-PATH_SEASON","B-SEASON","I-SEASON","B-EPISODE","I-EPISODE","B-SPECIAL","I-SPECIAL","B-GROUP","I-GROUP","B-RESOLUTION","I-RESOLUTION","B-SOURCE","I-SOURCE","B-TAG","I-TAG",];static LABEL_IDS: OnceLock<HashMap<String, i16>> = OnceLock::new();#[derive(Debug, Deserialize)]struct LabelSchema {labels: Vec<String>,}#[derive(Parser, Debug)]#[command(about = "Generate pre-encoded AniFileBERT virtual BIO permutation shards",102 unmodified lines#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize)]enum Entity {Group,TitleChs,TitleCht,TitleJpn,TitleLatin,TitleMixed,PathTitleChs,PathTitleCht,PathTitleJpn,PathTitleLatin,PathTitleMixed,PathSeason,Season,Episode,Special,Resolution,Source,Tag,}impl Entity {fn index(self) -> usize {ENTITIES.iter().position(|entity| *entity == self).expect("entity missing from ENTITIES")}fn from_name(name: &str) -> Option<Self> {match name {"GROUP" => Some(Entity::Group),"TITLE" | "TITLE_MIXED" => Some(Entity::TitleMixed),"TITLE_CHS" => Some(Entity::TitleChs),"TITLE_CHT" => Some(Entity::TitleCht),"TITLE_JPN" => Some(Entity::TitleJpn),"TITLE_LATIN" => Some(Entity::TitleLatin),"PATH_TITLE" | "PATH_TITLE_MIXED" => Some(Entity::PathTitleMixed),"PATH_TITLE_CHS" => Some(Entity::PathTitleChs),"PATH_TITLE_CHT" => Some(Entity::PathTitleCht),"PATH_TITLE_JPN" => Some(Entity::PathTitleJpn),"PATH_TITLE_LATIN" => Some(Entity::PathTitleLatin),"PATH_SEASON" => Some(Entity::PathSeason),"SEASON" => Some(Entity::Season),"EPISODE" => Some(Entity::Episode),"SPECIAL" => Some(Entity::Special),"RESOLUTION" => Some(Entity::Resolution),"SOURCE" => Some(Entity::Source),"TAG" => Some(Entity::Tag),_ => None,}}1 unmodified linefn b_label(self) -> &'static str {match self {Entity::Group => "B-GROUP",Entity::TitleChs => "B-TITLE_CHS",Entity::TitleCht => "B-TITLE_CHT",Entity::TitleJpn => "B-TITLE_JPN",Entity::TitleLatin => "B-TITLE_LATIN",Entity::TitleMixed => "B-TITLE_MIXED",Entity::PathTitleChs => "B-PATH_TITLE_CHS",Entity::PathTitleCht => "B-PATH_TITLE_CHT",Entity::PathTitleJpn => "B-PATH_TITLE_JPN",Entity::PathTitleLatin => "B-PATH_TITLE_LATIN",Entity::PathTitleMixed => "B-PATH_TITLE_MIXED",Entity::PathSeason => "B-PATH_SEASON",Entity::Season => "B-SEASON",Entity::Episode => "B-EPISODE",Entity::Special => "B-SPECIAL",Entity::Resolution => "B-RESOLUTION",Entity::Source => "B-SOURCE",Entity::Tag => "B-TAG",}}fn i_label(self) -> &'static str {match self {Entity::Group => "I-GROUP",Entity::TitleChs => "I-TITLE_CHS",Entity::TitleCht => "I-TITLE_CHT",Entity::TitleJpn => "I-TITLE_JPN",Entity::TitleLatin => "I-TITLE_LATIN",Entity::TitleMixed => "I-TITLE_MIXED",Entity::PathTitleChs => "I-PATH_TITLE_CHS",Entity::PathTitleCht => "I-PATH_TITLE_CHT",Entity::PathTitleJpn => "I-PATH_TITLE_JPN",Entity::PathTitleLatin => "I-PATH_TITLE_LATIN",Entity::PathTitleMixed => "I-PATH_TITLE_MIXED",Entity::PathSeason => "I-PATH_SEASON",Entity::Season => "I-SEASON",Entity::Episode => "I-EPISODE",Entity::Special => "I-SPECIAL",Entity::Resolution => "I-RESOLUTION",Entity::Source => "I-SOURCE",Entity::Tag => "I-TAG",}}fn is_file_title(self) -> bool {matches!(self,Entity::TitleChs| Entity::TitleCht| Entity::TitleJpn| Entity::TitleLatin| Entity::TitleMixed)}fn is_path_title(self) -> bool {matches!(self,Entity::PathTitleChs| Entity::PathTitleCht| Entity::PathTitleJpn| Entity::PathTitleLatin| Entity::PathTitleMixed)}fn is_ordinary_variant_entity(self) -> bool {!self.is_path_title() && self != Entity::PathSeason}fn as_path_title(self) -> Option<Self> {match self {Entity::TitleChs => Some(Entity::PathTitleChs),Entity::TitleCht => Some(Entity::PathTitleCht),Entity::TitleJpn => Some(Entity::PathTitleJpn),Entity::TitleLatin => Some(Entity::PathTitleLatin),Entity::TitleMixed => Some(Entity::PathTitleMixed),Entity::PathTitleChs| Entity::PathTitleCht| Entity::PathTitleJpn| Entity::PathTitleLatin| Entity::PathTitleMixed => Some(self),_ => None,}}fn as_file_title(self) -> Option<Self> {match self {Entity::PathTitleChs => Some(Entity::TitleChs),Entity::PathTitleCht => Some(Entity::TitleCht),Entity::PathTitleJpn => Some(Entity::TitleJpn),Entity::PathTitleLatin => Some(Entity::TitleLatin),Entity::PathTitleMixed => Some(Entity::TitleMixed),Entity::TitleChs| Entity::TitleCht| Entity::TitleJpn| Entity::TitleLatin| Entity::TitleMixed => Some(self),_ => None,}}}435 unmodified lines);}let filename = row.filename.clone().unwrap_or_else(|| row.tokens.join(""));let labels = row.labels.iter().map(|label| canonical_bio_label(label)).collect::<Vec<_>>();let fields = extract_fields(&row.tokens, &labels);samples.push(SourceSample {row_index: idx,filename,tokens: row.tokens,labels,fields,});}Ok(samples)}fn canonical_bio_label(label: &str) -> String {if label == "O" {return "O".to_string();}let Some((prefix, entity_name)) = label.split_once('-') else {return label.to_string();};let Some(entity) = Entity::from_name(entity_name) else {return label.to_string();};match prefix {"B" => entity.b_label().to_string(),"I" => entity.i_label().to_string(),_ => label.to_string(),}}fn extract_fields(tokens: &[String], labels: &[String]) -> Vec<Vec<String>> {let mut fields: Vec<Vec<String>> = (0..ENTITIES.len()).map(|_| Vec::new()).collect();let mut seen: Vec<HashSet<String>> = (0..ENTITIES.len()).map(|_| HashSet::new()).collect();6 unmodified linesseen: &mut Vec<HashSet<String>>| {if let Some(entity) = entity {let value = text.trim().to_string();push_extracted_field(fields, seen, entity, value);}text.clear();};20 unmodified linesfields}fn push_extracted_field(fields: &mut [Vec<String>],seen: &mut [HashSet<String>],entity: Entity,value: String,) {fn add(fields: &mut [Vec<String>], seen: &mut [HashSet<String>], entity: Entity, value: &str) {if !value.is_empty() && seen[entity.index()].insert(value.to_string()) {fields[entity.index()].push(value.to_string());}}let value = value.trim();if value.is_empty() {return;}add(fields, seen, entity, value);if let Some(path_title) = entity.as_path_title() {add(fields, seen, path_title, value);}if let Some(file_title) = entity.as_file_title() {add(fields, seen, file_title, value);}match entity {Entity::Season => add(fields, seen, Entity::PathSeason, value),Entity::PathSeason => add(fields, seen, Entity::Season, value),_ => {}}}fn ordinary_available_entities(sample: &SourceSample) -> Vec<Entity> {ENTITIES.iter().copied().filter(|entity| {entity.is_ordinary_variant_entity() && !sample.fields[entity.index()].is_empty()}).collect()}fn first_file_title_field(sample: &SourceSample) -> Option<(Entity, String)> {FILE_TITLE_ENTITIES.iter().copied().find_map(|entity| {sample.fields[entity.index()].iter().find(|value| !value.trim().is_empty()).map(|value| (entity, value.trim().to_string()))})}fn choose_path_title_field(sample: &SourceSample, rng: &mut StdRng) -> Option<(Entity, String)> {let mut candidates = Vec::new();for entity in PATH_TITLE_ENTITIES {for value in &sample.fields[entity.index()] {let value = value.trim();if !value.is_empty() {candidates.push((entity, value.to_string()));}}}candidates.choose(rng).cloned()}fn count_variants(sample: &SourceSample, cfg: &GenConfig) -> u128 {let mut count = if cfg.include_original { 1 } else { 0 };count += count_path_variants(sample, cfg) as u128;let available = ordinary_available_entities(sample);let n = available.len();if n == 0 || !cfg.include_bio_variants {return count;34 unmodified linesif cfg.path_samples_per_source == 0 || cfg.path_styles.is_empty() {return 0;}if !PATH_TITLE_ENTITIES.iter().any(|entity| !sample.fields[entity.index()].is_empty()){return 0;}if sample.fields[Entity::Episode.index()].is_empty()41 unmodified linesreturn Ok(());}let available = ordinary_available_entities(sample);let n = available.len();for mask in 1usize..(1usize << n) {let mut selected = available20 unmodified lineslet mut rng = StdRng::seed_from_u64(cfg.seed ^ ((sample.row_index as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)),);let available = ordinary_available_entities(sample);if available.is_empty() {return Ok(());}5 unmodified lineslet mut attempts = 0usize;let mut templates: Vec<Vec<PartChoice>> = Vec::new();if let Some((title_entity, title)) = first_file_title_field(sample) {templates.push(vec![PartChoice {entity: title_entity,value: title.clone(),}]);if let Some(season) = sample.fields[Entity::Season.index()].first() {templates.push(vec![PartChoice {entity: title_entity,value: title.clone(),},PartChoice {15 unmodified linesvalue: special.clone(),}]);}if let (Some((title_entity, title)), Some(special)) = (first_file_title_field(sample),sample.fields[Entity::Special.index()].first(),) {templates.push(vec![PartChoice {entity: title_entity,value: title.clone(),},PartChoice {36 unmodified lines.copied().collect::<Vec<_>>();chosen.shuffle(&mut rng);if !chosen.iter().any(|entity| {entity.is_file_title() || matches!(entity, Entity::Episode | Entity::Special)}) {if let Some(fallback) = available.iter().copied().find(|entity| {entity.is_file_title() || matches!(entity, Entity::Episode | Entity::Special)}) {if !chosen.contains(&fallback) {chosen.push(fallback);}35 unmodified lines.copied().collect::<Vec<_>>();chosen.shuffle(&mut rng);if !chosen.iter().any(|entity| {entity.is_file_title() || matches!(entity, Entity::Episode | Entity::Special)}) {if let Some(fallback) = available.iter().copied().find(|entity| {entity.is_file_title() || matches!(entity, Entity::Episode | Entity::Special)}) {if !chosen.contains(&fallback) {chosen.push(fallback);}158 unmodified linescfg: &GenConfig,rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> {let (title_entity, title) = choose_path_title_field(sample, rng)?;let style = *cfg.path_styles.choose(rng)?;let sep = style.separator();let mut components = path_prefix_components(style, rng);components.push(vec![entity_piece(title.clone(), title_entity)]);let season_component = choose_path_season_component(sample, rng);if let Some(season) = season_component {27 unmodified linescomponents.push(meta_file_component(sample, rng));}3 => components.push(compact_file_component(endpoint, sample, rng)),4 => components.push(grouped_release_file_component(&title, endpoint, sample, rng,)),_ => {components.push(vec![endpoint]);if rng.gen_bool(0.55) {65 unmodified linessample: &SourceSample,rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> {let season = if let Some(source_season) = choose_field(sample, Entity::PathSeason, rng).or_else(|| choose_field(sample, Entity::Season, rng)){random_season_path_text(&source_season, rng)} else {let synthetic = ["01", "Season 1", "Season 01", "S01", "第1季"];synthetic.choose(rng).copied().unwrap_or("Season 1").to_string()};Some(vec![entity_piece(season, Entity::PathSeason)])}fn path_file_component(82 unmodified lines}}}if let Some(tag) = choose_field(sample, Entity::Tag, rng) {if rng.gen_bool(0.55) {pieces.push(o_piece("[".to_string()));pieces.push(entity_piece(tag, Entity::Tag));pieces.push(o_piece("]".to_string()));}}}fn random_episode_path_text(value: &str, rng: &mut StdRng) -> String {24 unmodified linesfn random_season_path_text(value: &str, rng: &mut StdRng) -> String {let mut variants = vec![value.trim().to_string()];if let Some(number) = first_ascii_number(value) {variants.push(format!("{number:02}"));variants.push(format!("Season {number}"));variants.push(format!("Season {number:02}"));variants.push(format!("S{number:02}"));412 unmodified lines}fn label_id(label: &str) -> Option<i16> {label_ids().get(label).copied()}fn label_ids() -> &'static HashMap<String, i16> {LABEL_IDS.get_or_init(load_label_ids)}fn load_label_ids() -> HashMap<String, i16> {let labels = read_schema_labels().unwrap_or_else(|| {FALLBACK_LABELS.iter().map(|label| (*label).to_string()).collect()});labels.into_iter().enumerate().map(|(idx, label)| (label, idx as i16)).collect()}fn read_schema_labels() -> Option<Vec<String>> {for path in label_schema_candidates() {let Ok(text) = fs::read_to_string(path) else {continue;};let Ok(schema) = serde_json::from_str::<LabelSchema>(&text) else {continue;};if schema.labels.is_empty() || schema.labels.iter().any(|label| label.trim().is_empty()) {continue;}return Some(schema.labels);}None}fn label_schema_candidates() -> Vec<PathBuf> {let mut candidates = Vec::new();if let Ok(current_dir) = std::env::current_dir() {candidates.push(current_dir.join("label_schema.json"));}candidates.push(Path::new(env!("CARGO_MANIFEST_DIR")).join("..").join("..").join("label_schema.json"),);candidates}fn built_in_specials() -> Vec<String> {97 unmodified linesfn sample_without_season() -> SourceSample {let mut fields = vec![Vec::new(); ENTITIES.len()];fields[Entity::TitleLatin.index()] = vec!["Example Show".to_string()];fields[Entity::PathTitleLatin.index()] = vec!["Example Show".to_string()];fields[Entity::Episode.index()] = vec!["1".to_string()];fields[Entity::Resolution.index()] = vec!["1080P".to_string()];fields[Entity::Source.index()] = vec!["WEB-DL".to_string()];25 unmodified linesassert!(non_empty_components >= 2,"expected at least two noise directories for {style:?}: {}",render_labeled_pieces(&join_path_components(&components, style.separator())));assert!(components.iter()3 unmodified lines}}#[test]fn fixed_label_schema_ids_match_v2_order() {assert_eq!(label_id("O"), Some(0));assert_eq!(label_id("B-TITLE_CHS"), Some(1));assert_eq!(label_id("I-TITLE_MIXED"), Some(10));assert_eq!(label_id("B-PATH_TITLE_CHS"), Some(11));assert_eq!(label_id("I-PATH_TITLE_MIXED"), Some(20));assert_eq!(label_id("B-PATH_SEASON"), Some(21));assert_eq!(label_id("B-SEASON"), Some(23));assert_eq!(label_id("B-EPISODE"), Some(25));assert_eq!(label_id("B-GROUP"), Some(29));assert_eq!(label_id("B-SOURCE"), Some(33));assert_eq!(label_id("B-TAG"), Some(35));assert_eq!(label_id("I-TAG"), Some(36));assert_eq!(label_id("B-TITLE"), None);}#[test]fn legacy_source_title_labels_canonicalize_to_mixed_schema() {assert_eq!(canonical_bio_label("B-TITLE"), "B-TITLE_MIXED");assert_eq!(canonical_bio_label("I-TITLE"), "I-TITLE_MIXED");assert_eq!(canonical_bio_label("B-PATH_TITLE"), "B-PATH_TITLE_MIXED");assert_eq!(canonical_bio_label("B-SEASON"), "B-SEASON");}#[test]fn generated_entities_do_not_emit_legacy_title_labels() {for entity in ENTITIES {assert_ne!(entity.b_label(), "B-TITLE");assert_ne!(entity.i_label(), "I-TITLE");}}#[test]fn extraction_preserves_file_and_path_title_candidates() {let tokens = ["A", "/", "僕", "ら"].iter().map(|value| value.to_string()).collect::<Vec<_>>();let labels = ["B-TITLE_LATIN", "O", "B-PATH_TITLE_JPN", "I-PATH_TITLE_JPN"].iter().map(|value| value.to_string()).collect::<Vec<_>>();let fields = extract_fields(&tokens, &labels);assert_eq!(fields[Entity::TitleLatin.index()], vec!["A"]);assert_eq!(fields[Entity::PathTitleLatin.index()], vec!["A"]);assert_eq!(fields[Entity::PathTitleJpn.index()], vec!["僕ら"]);assert_eq!(fields[Entity::TitleJpn.index()], vec!["僕ら"]);}#[test]fn path_context_synthesizes_season_between_title_and_episode() {let sample = sample_without_season();5 unmodified lineslet text = render_labeled_pieces(&pieces);assert!(text.contains("Example Show"));assert!(text.contains("Season")|| text.contains("S01")|| text.contains("第1季")|| text.contains("01"),"missing synthetic season directory in {text}");3 unmodified linesfor piece in &pieces {match piece.entity {None if !seen_title => {}Some(Entity::PathTitleLatin) => seen_title = true,Some(Entity::PathSeason) if seen_title => seen_season_after_title = true,Some(Entity::Episode) if seen_season_after_title => {seen_episode_after_season = true}5 unmodified linesassert!(seen_episode_after_season);}#[test]fn path_context_can_label_bare_numeric_path_season() {let mut sample = sample_without_season();sample.fields[Entity::Episode.index()] = vec!["3".to_string()];let mut cfg = test_config();cfg.path_styles = vec![PathStyle::Unix];let mut found = None;for seed in 0..2048 {let mut rng = StdRng::seed_from_u64(seed);let pieces = build_path_context_pieces(&sample, &cfg, &mut rng).expect("expected path context pieces");let text = render_labeled_pieces(&pieces);if text.contains("Example Show/01/03.mkv") {found = Some(pieces);break;}}let pieces = found.expect("expected a Title/01/03.mkv-style path context");assert!(pieces.iter().any(|piece| piece.text == "01" && piece.entity == Some(Entity::PathSeason)));assert!(pieces.iter().any(|piece| piece.text == "03" && piece.entity == Some(Entity::Episode)));}#[test]fn path_season_variants_include_common_directory_forms() {let mut variants = HashSet::new();for seed in 0..128 {let mut rng = StdRng::seed_from_u64(seed);variants.insert(random_season_path_text("S01", &mut rng));}assert!(variants.contains("S01"));assert!(variants.contains("01"));assert!(variants.contains("Season 1"));assert!(variants.contains("Season 01"));}#[test]fn grouped_path_file_labels_group_but_not_duplicate_title() {let sample = sample_with_group();5 unmodified linesassert!(text.contains("[Erai-raws]"));assert!(text.contains("Example Show"));assert!(text.contains("01"));assert!(pieces.iter().any(|piece| piece.entity == Some(Entity::Group)));assert!(pieces.iter().any(|piece| piece.entity == Some(Entity::Episode)));assert!(pieces.iter().any(|piece| piece.text == "Example Show" && piece.entity.is_none()));
anifilebert/config.py+8-13
anifilebert/dataset.py+2-1
anifilebert/inference.py+99-35
anifilebert/label_repairs.py+11-9
anifilebert/labels.pyAdded+205
anifilebert/model.py+116
anifilebert/train.py+54-9
data/parser_regression_cases.json+21
label_schema.jsonAdded+80
tools/build_path_focus_dataset.py+40-12
tools/build_path_prefix_dataset.py+110-12
tools/build_repair_focus_dataset.py+29-18
tools/evaluate_parser_cases.py+15-1
tools/rust_dmhy_template_apply/src/main.rs+886-235
tools/virtual_dataset_generator/src/bin/case_combo_generator.rs+129-50
tools/virtual_dataset_generator/src/main.rs+477-94