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 lines456778910111239 unmodified lines52535453555657585960616259606162636465666768636470656667683 unmodified lines"""
from dataclasses import dataclass, fieldfrom dataclasses import dataclass
from .labels import LABEL_SCHEMA_VERSION, make_id2label, make_label2id
@dataclass39 unmodified lines cls_token: str = "[CLS]" sep_token: str = "[SEP]"
# BIO label scheme (8 entity types + O) # BIO label scheme label_schema_version: int = LABEL_SCHEMA_VERSION label2id: dict = None id2label: dict = None
def __post_init__(self): using_default_labels = self.label2id is None 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, } self.label2id = make_label2id() if self.id2label is None: self.id2label = {v: k for k, v in self.label2id.items()} self.id2label = make_id2label() if using_default_labels else {v: k for k, v in self.label2id.items()}
@property def num_labels(self) -> int:13 unmodified lines1415161718192013 unmodified lines343536363738394013 unmodified lines
from .config import Configfrom .label_repairs import repair_sequel_season_labelsfrom .labels import canonical_bio_labelfrom .tokenizer import AnimeTokenizer
13 unmodified lines input_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.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 lines19202122232425264 unmodified lines2902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433445 unmodified lines3503513523033043053063073083093103113533543553563573163583593603613183193203213223233243623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923323333343353933943953963973983383393403994004014024033433444044054064073473483494084094104114124134144154164176 unmodified lines42442542642742842943010 unmodified lines44144244344444544644744825 unmodified lines47447547640941041147747847948036 unmodified lines51751851945445545652052152252318 unmodified lines
from .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_tokenizer
264 unmodified lines return decoded
def 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: return kind = 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 None return min(spans, key=lambda item: (title_entity_priority(item[0]), item[2]))[1]
def postprocess( tokens: List[str], labels: List[str],5 unmodified lines Merges 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, } result: Dict = empty_parse_result()
entities = labels_to_entities(tokens, labels, tokenizer)
grouped_entities: Dict[str, List[str]] = {} for entity_type, text in entities: 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_fragments = [ cleaned for text in grouped_entities.get("TITLE", []) if (cleaned := normalize_field_text(text)) ] if title_fragments: result["title"] = " ".join(title_fragments) title = normalize_field_text(text) if not title: continue if 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_num break if 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_num break
for 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_num ep_num = extract_episode_number(text) if ep_num is not None: if result["episode"] is None: result["episode"] = ep_num
for text in grouped_entities.get("GROUP", []): group = normalize_field_text(text) if result["group"] is None: result["group"] = group group = normalize_field_text(text) if result["group"] is None: result["group"] = group
for text in grouped_entities.get("SPECIAL", []): special = normalize_field_text(text) result["special"] = special special = normalize_field_text(text) result["special"] = special
for text in grouped_entities.get("RESOLUTION", []): res = extract_resolution(text) if res: result["resolution"] = res res = extract_resolution(text) if res: result["resolution"] = res
for 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 lines or "月番" in result["title"] ): result["title"] = new_show_title append_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 # Tokenize tokens = tokenizer.tokenize(filename) if not tokens: return {"title": None, "season": None, "episode": None, "group": None, "resolution": None, "source": None, "special": None} return empty_parse_result()
# Convert to input IDs input_ids = tokenizer.convert_tokens_to_ids(tokens)36 unmodified lines # Truncate real tokens if we had to truncate available = 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} return empty_parse_result()
with torch.no_grad(): logits = model(input_ids=input_tensor, attention_mask=mask_tensor).logits5 unmodified lines678910111213270 unmodified lines2842852862852872882892904 unmodified lines2952962972962982993003011 unmodified line3033043053043063073083096 unmodified lines3163173183173193203213227 unmodified lines3303313323313333343353363373363383393403411 unmodified line343344345344346347348349117 unmodified lines4674684694684704714724734724744754764775 unmodified linesfrom dataclasses import dataclassfrom typing import Dict, Iterable, List, Optional, Sequence, Tuple
from .labels import is_same_entity_label, is_season_like_label, is_title_like_label, label_entity
SEPARATOR_CHARS = set(" \t-_.|~~")
270 unmodified lines
def 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)) 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 lines
def 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) 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_entity for idx in indices: labels[idx] = f"B-{entity}" if first else f"I-{entity}"1 unmodified line
def 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) 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 lines if not indices: return False return not any( labels[idx].endswith(("GROUP", "EPISODE", "SEASON")) label_entity(labels[idx]) in {"GROUP", "EPISODE", "SEASON", "PATH_SEASON"} for idx in indices )
7 unmodified lines return
idx = marker_indices[0] - 1 while idx >= 0 and "".join(tokens[idx]).strip() == "" and labels[idx].endswith("TITLE"): while idx >= 0 and "".join(tokens[idx]).strip() == "" and is_title_like_label(labels[idx]): labels[idx] = "O" idx -= 1
idx = marker_indices[-1] + 1 while idx < len(tokens) and tokens[idx] in SEPARATOR_CHARS and labels[idx].endswith("TITLE"): while idx < len(tokens) and tokens[idx] in SEPARATOR_CHARS and is_title_like_label(labels[idx]): labels[idx] = "O" idx += 1
1 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 label_entity(label) == "EPISODE" ] if ends: return min(ends)117 unmodified lines continue existing = [repaired_labels[idx] for idx in indices] if any( label.endswith(("GROUP", "EPISODE", "RESOLUTION", "SOURCE", "SPECIAL")) label_entity(label) in {"GROUP", "EPISODE", "RESOLUTION", "SOURCE", "SPECIAL", "TAG", "PATH_SEASON"} for label in existing ): continue if not any(label.endswith("TITLE") for label in existing): if not any(is_title_like_label(label) for label in existing): continue
label_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 lines18192021222324242 unmodified lines26726826927027127227342 unmodified lines31631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443517 unmodified linesfrom transformers.modeling_utils import PreTrainedModel
from .config import Configfrom .labels import infer_legacy_id2label, label_migration_sources
class LinearChainCRF(nn.Module):242 unmodified lines attention_probs_dropout_prob=config.attention_probs_dropout_prob, id2label=config.id2label, label2id=config.label2id, label_schema_version=config.label_schema_version, )
42 unmodified lines return 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 inferred return normalized
def 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 all title-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_labels and 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_labels model.config.id2label = target_id2label model.config.label2id = target_label2id return {"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 None new_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 = 0 for 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: continue new_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_id copied += 1 break
model.classifier = new_classifier model.num_labels = new_num_labels model.config.num_labels = new_num_labels model.config.id2label = target_id2label model.config.label2id = target_label2id
if hasattr(model, "crf"): old_crf = model.crf new_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_crf
return { "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 lines3334353636373839404142434445464748495051525354287 unmodified lines34234334434534634734833534935035133733835235335435535635735835936036136236336416 unmodified lines38138238338438538638722 unmodified lines4104114124134144154165 unmodified lines42242342442542642742815 unmodified lines4444454464474484494504518 unmodified lines46046146243546346446546619 unmodified lines486487488461489490491492553 unmodified lines104610471048104910501051105210531054105510561057105832 unmodified lines1091109210931059106010611094109510961097109810991100264 unmodified lines13651366136713681369137013711372137313741375137613771378137913801381187 unmodified lines156915701571157215731574157532 unmodified lines
from .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 .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, ShardedEncodedDataset
287 unmodified lines active_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)) active_entity = label[2:] 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-") and active_entity == label[2:]: active_tokens.append(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 = entity active_tokens = [str(token)] else: if active_entity and active_tokens: entities.setdefault(active_entity, []).append("".join(active_tokens))16 unmodified lines for text, entity in spans: if not text: continue entity = 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 lines special = 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 lines specs.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 lines entities = extract_entities_from_labels(item.get("tokens", []), item.get("labels", [])) available = [ entity for entity in ("GROUP", "TITLE", "SEASON", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE") for entity in ("GROUP", "TITLE", "SEASON", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE", "TAG") if entities.get(entity) ] if not available:19 unmodified lines if not values: continue value = rng.choice(values) if entity in {"GROUP", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE"} and rng.random() < 0.35: 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 None if isinstance(value, list): normalized_items = [ normalize_field_value(field, item) for item in value if 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 lines gold_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] = None if "EPISODE" not in gold_entities: gold["episode"] = None if not any(is_season_like_label(label) for label in gold_labels): gold["season"] = None pred = parse_filename( filename, model,264 unmodified lines f" 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_labels model.config.id2label = config.id2label model.config.label2id = config.label2id model.config.label_schema_version = config.label_schema_version else: 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 saving model.config.id2label = config.id2label model.config.label2id = config.label2id model.config.label_schema_version = config.label_schema_version model.config.tokenizer_variant = tokenizer_variant model.config.max_seq_length = config.max_seq_length save_model_head_config(model, selected_model_head)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 lines121314151617181920212223242526272829303117 unmodified lines49505143525354553 unmodified lines596061535462636465661 unmodified line686970717273747576777879808182838485868788899091656692939495963 unmodified lines10010110276771031041051068010710810911011111211387881141151161171183 unmodified lines122123124989912512612712812913011 unmodified linesfrom pathlib import Path
def canonical_entity(entity: str) -> str: if entity == "TITLE": return "TITLE_MIXED" if entity == "PATH_TITLE": return "PATH_TITLE_MIXED" return entity
def char_item(filename: str, spans: list[tuple[str, str]], source: str) -> dict[str, object]: tokens = list(filename) labels = ["O"] * len(tokens) cursor = 0 for text, entity in spans: entity = canonical_entity(entity) start = filename.find(text, cursor) if start < 0: start = filename.find(text)17 unmodified lines char_item( r"Z:\Library\Anime\Shinsekai Yori\Extras\NCED02 [Ma10p_1080p][x265_flac].mkv", [ ("Shinsekai Yori", "TITLE"), ("Shinsekai Yori", "PATH_TITLE_LATIN"), ("NCED02", "SPECIAL"), ("1080p", "RESOLUTION"), ("x265_flac", "SOURCE"),3 unmodified lines char_item( r"O:\115open\Anime\Sousou no Frieren\Season 01\31 [1080P][Baha][WEB-DL].mkv", [ ("Sousou no Frieren", "TITLE"), ("Season 01", "SEASON"), ("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", "TITLE"), ("Season 21", "SEASON"), ("One Piece", "PATH_TITLE_LATIN"), ("Season 21", "PATH_SEASON"), ("1110", "EPISODE"), ("1080p", "RESOLUTION"), ("WEB-DL", "SOURCE"),3 unmodified lines char_item( r"D:\Media\Anime\completed\Witch Watch\S01\15 [1080p][CHS].mkv", [ ("Witch Watch", "TITLE"), ("S01", "SEASON"), ("Witch Watch", "PATH_TITLE_LATIN"), ("S01", "PATH_SEASON"), ("15", "EPISODE"), ("1080p", "RESOLUTION"), ("CHS", "SOURCE"), ("CHS", "TAG"), ], source, ), char_item( r"O:\115open\Anime\Kakuriyo no Yadomeshi\Season 02\12 [WebRip 1080p].mkv", [ ("Kakuriyo no Yadomeshi", "TITLE"), ("Season 02", "SEASON"), ("Kakuriyo no Yadomeshi", "PATH_TITLE_LATIN"), ("Season 02", "PATH_SEASON"), ("12", "EPISODE"), ("WebRip", "SOURCE"), ("1080p", "RESOLUTION"),3 unmodified lines char_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"), ("One Piece", "PATH_TITLE_LATIN"), ("Season 21", "PATH_SEASON"), ("One.Piece", "TITLE_LATIN"), ("1110", "EPISODE"), ("1080p", "RESOLUTION"), ("WEB-DL", "SOURCE"),1 unmodified line23455677891011 unmodified lines22232425262728292630313233343536373839404142434461 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551562 unmodified lines1591601611081621631641652 unmodified lines16816917011717117217312017417517617717 unmodified lines19519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623724 unmodified lines26226326417426526626717726826927027138 unmodified lines31031131231331431531631731831932032111 unmodified lines3333343352392403363373383393403413426 unmodified lines3493503512542553523533543553561 unmodified line
The generated rows look like:
noise/noise/TITLE/Season 01/03 [1080P][WEB-DL].mkv noise/noise/PATH_TITLE_LATIN/PATH_SEASON/03 [1080P][WEB-DL].mkv
Prefix directories are always labeled ``O``. The title directory, seasonPrefix 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, Optional
TITLE_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 = { "TITLE", *FILE_TITLE_ENTITIES, *PATH_TITLE_ENTITIES, "PATH_SEASON", "SEASON", "EPISODE", "SPECIAL", "RESOLUTION", "SOURCE", "GROUP", "TAG", "TITLE", "PATH_TITLE",}
PREFIX_COMPONENTS = {61 unmodified lines raise ValueError(f"{path}:{line_no}: invalid JSON") from exc
def 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 entity return None
def file_title_to_path_title(entity: str) -> Optional[str]: if entity.startswith("TITLE_"): return "PATH_TITLE_" + entity.removeprefix("TITLE_") return None
def path_title_to_file_title(entity: str) -> Optional[str]: if entity.startswith("PATH_TITLE_"): return "TITLE_" + entity.removeprefix("PATH_TITLE_") return None
def append_entity_value(entities: dict[str, list[str]], entity: str, value: str) -> None: value = value.strip() if not value: return
def 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 lines def flush() -> None: nonlocal active_entity, active_tokens if active_entity and active_tokens: entities.setdefault(active_entity, []).append("".join(active_tokens).strip()) append_entity_value(entities, active_entity, "".join(active_tokens)) active_entity = None active_tokens = []
2 unmodified lines token = str(token) if label.startswith("B-"): flush() active_entity = label.split("-", 1)[1] active_entity = canonical_entity(label.split("-", 1)[1]) active_tokens = [token] elif label.startswith("I-"): entity = label.split("-", 1)[1] entity = canonical_entity(label.split("-", 1)[1]) if active_entity == entity: active_tokens.append(token) else:17 unmodified lines return 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: continue for 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 None return 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 None return rng.choice(values)
def choose_group( entities: dict[str, list[str]], rng: random.Random,24 unmodified lines number = 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}季"]) 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"Season {number}", f"Season {number:02}", f"S{number:02}", f"第{number}季"]) 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 lines if 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 lines if len(tokens) != len(labels): return None entities = extract_entities(tokens, labels) title = choose_entity(entities, "TITLE", rng) if not title: title_choice = choose_path_title(entities, rng) if not title_choice: return None title, path_title_entity = title_choice group = choose_group(entities, rng, max_group_length) if require_group and not group: return None6 unmodified lines style = 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")]) 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 lines64656667676869702 unmodified lines73747576767778793 unmodified lines8384858686878889903 unmodified lines949596979698991001013 unmodified lines1051061071061081091101114 unmodified lines1161171181171191201211224 unmodified lines1271281291281301311321337 unmodified lines1411421431421441451461477 unmodified lines1551561571561581591601616 unmodified lines1681691701691711721731746 unmodified lines1811821831821841851861875 unmodified lines1931941951961941971981992002012022034 unmodified lines2082092102062112122132142152162172184 unmodified lines2232242252182262272282292302312322334 unmodified lines2382392402302412422432443 unmodified lines2482492502402512522532542 unmodified lines2572582592492602612622635 unmodified lines26927027126127227327427563 unmodified lines yield char_item( "One.Piece.1110.1080p.WEB-DL.AAC2.0.H.264", [ ("One.Piece", "TITLE"), ("One.Piece", "TITLE_LATIN"), ("1110", "EPISODE"), ("1080p", "RESOLUTION"), ("WEB-DL", "SOURCE"),2 unmodified lines yield char_item( "One.Piece.1111.1080p.WEB-DL.AAC2.0.H.264", [ ("One.Piece", "TITLE"), ("One.Piece", "TITLE_LATIN"), ("1111", "EPISODE"), ("1080p", "RESOLUTION"), ("WEB-DL", "SOURCE"),3 unmodified lines "【喵萌奶茶屋】★04月新番★[葬送的芙莉莲][01][1080P][HEVC]", [ ("喵萌奶茶屋", "GROUP"), ("★04月新番★", "TAG"), ("葬送的芙莉莲", "TITLE"), ("葬送的芙莉莲", "TITLE_CHS"), ("01", "EPISODE"), ("1080P", "RESOLUTION"), ("HEVC", "SOURCE"),3 unmodified lines "【喵萌奶茶屋】★10月新番★[药屋少女的呢喃][02][1080P][HEVC]", [ ("喵萌奶茶屋", "GROUP"), ("★10月新番★", "TAG"), ("药屋少女的呢喃", "TITLE"), ("药屋少女的呢喃", "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"), ("魔法姊妹露露莉莉 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"), ("魔法姊妹露露莉莉 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"), ("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"), ("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"), ("炎炎の消防隊", "TITLE_JPN"), ("弐ノ章", "SEASON"), ("13", "EPISODE"), ("BD", "SOURCE"),6 unmodified lines "[AI-Raws] 炎炎の消防隊 弐ノ章 #01 (BD HEVC 1920x1080 FLAC).mkv", [ ("AI-Raws", "GROUP"), ("炎炎の消防隊", "TITLE"), ("炎炎の消防隊", "TITLE_JPN"), ("弐ノ章", "SEASON"), ("01", "EPISODE"), ("BD", "SOURCE"),6 unmodified lines "[DBD-Raws][炎炎消防队 貳之章][01][1080P][BDRip][HEVC-10bit][FLAC]", [ ("DBD-Raws", "GROUP"), ("炎炎消防队", "TITLE"), ("炎炎消防队", "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"), ("逆天邪神", "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"), ("剑来", "TITLE"), ("国漫", "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"), ("大主宰", "TITLE"), ("国漫", "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"), ("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"), ("Shinsekai Yori", "TITLE_LATIN"), ("NCED02", "SPECIAL"), ("1080p", "RESOLUTION"), ("x265_flac", "SOURCE"),2 unmodified lines yield char_item( "InuYasha.2000.NCED02.BDrip.AV1.10Bit.DTS.1080p-CalChi", [ ("InuYasha", "TITLE"), ("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"), ("Yamada-kun to 7-nin no Majo", "TITLE_LATIN"), ("NCED", "SPECIAL"), ("1080p", "RESOLUTION"), ("x265_flac", "SOURCE"),19 unmodified lines2021222324252627282930313219 unmodified lines5253545556575859526061626352 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 None if isinstance(value, list): normalized_items = [ normalize_field_value(field, item) for item in value if 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 lines tokenizer_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("cuda" if torch.cuda.is_available() else "cpu") 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 lines case_file: str, tokenizer_variant: Optional[str], max_length: Optional[int], force_cpu: bool = False,) -> Dict: modes = { "model_only": {"constrain_bio": False},6 unmodified lines tokenizer_variant=tokenizer_variant, max_length=max_length, constrain_bio=settings["constrain_bio"], force_cpu=force_cpu, ) for name, settings in modes.items() }26 unmodified lines parser.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 lines case_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 lines tokenizer_variant=args.tokenizer, max_length=args.max_length, constrain_bio=constrain_bio, force_cpu=args.cpu, ) print_metrics(args.mode, metrics)
134 unmodified lines13513613713813914014120 unmodified lines1621631641651661671681699 unmodified lines17918018117918018218318418514 unmodified lines2002012022012022032032042052062076 unmodified lines2142152162162172182192172182192202212222233 unmodified lines22722822922923023123223323423523645 unmodified lines28228328428528628728828929029129229349 unmodified lines34334434534634734834935035135220 unmodified lines37337437537637737837938038138238338438538638738838939039139239339439537239639739839940040140240340440540640740840941041141236 unmodified lines44945045145245345445545645734 unmodified lines49249349445545649549649749849984 unmodified lines584585586587588589590212 unmodified lines803804805806807808809153 unmodified lines96396496596696796896960 unmodified lines103010311032103310341035103631 unmodified lines1068106910701027107110721073107410751 unmodified line1077107810791035108010811082108315 unmodified lines10991100110111021103110411051106110711081109111011111112111311141115111611171118111941 unmodified lines1161116211631164116511661167116832 unmodified lines120112021203114212041205120612071146120812091210121136 unmodified lines124812491250118912511252125312541255125612571258125911951196126012611262126313 unmodified lines127712781279121612801281128212831284122012211285128612871223122412251288128912901291129212931294129512961297129812992 unmodified lines13021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132512391240132613271328132953 unmodified lines138313841385138613871388138913901391139213931394139513962 unmodified lines139914001401140214031404140514064 unmodified lines141114121413141414151416141714183 unmodified lines142214231424142514261427142814291 unmodified line143114321433143414351436143714382 unmodified lines144114421443144414451446144714482 unmodified lines14511452145314541455145614571458415 unmodified lines187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918177319191920192119228 unmodified lines1931193219331788178917901791179217931794193419351936193717951938193917981799180018011802194019411942194389 unmodified lines20332034203518981899190019011902190319042036203720382039204020412042204320444 unmodified lines2049205020512052191520532054205520561 unmodified line20582059206019232061206220632064206520668 unmodified lines20752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402 unmodified lines2243224422451946194719481949195019511952195322462247224822492250225122522253225485 unmodified lines234023412342204523432344234523462347234823492350235123522353336 unmodified lines26902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733121 unmodified lines28552856285725202858285928602861286298 unmodified lines29612962296326252964296529662967296826272969297029712972297329744 unmodified lines29792980298126382982298329842985298629876 unmodified lines2994299529962651265229972998299930003001265726583002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430252670267126722673267426753026302730283029303030312680303230333034303530363037303830393040304131 unmodified lines3073307430752718271927202721272227233076307730783079308030812728308230833084308530863087308830893090309127 unmodified lines3119312031212762312231233124312531263127312831293130313131323133313431353136277127722773313731382775313931403141314231433144314531463147314831493150315131523153278127822783278431543155278631563157315831593160316173 unmodified lines32353236323728662867286832383239324032413242324332449 unmodified lines32543255325628842885288632573258325932606 unmodified lines3267326832692899327032713272327332743275107 unmodified lines3383338433853013301433863387338833894 unmodified lines33943395339633973398339930253400340130273028302930303031340234033404340526 unmodified lines343234333434306434353436343734381 unmodified line344034413442307234433444344534463 unmodified lines3450345134523082345334543455345620 unmodified lines347734783479310934803481348234832 unmodified lines34863487348834893490349134923493311834943495349634973498312331243125312631273128349935003501350235033504350531303131313231333506350735083509351035113512351335143515351635173518351931373520352135223523314135243525352635272 unmodified lines35303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555131 unmodified lines368736883689369036913692369336943695369636973698369981 unmodified lines378137823783378437853375378637873788378938 unmodified lines3828382938303420383138323833383438353836342638373838383938403 unmodified lines3844384538463436384738483849385011 unmodified lines386238633864345434553456345738653866386738683869387038713461346234633464387238733874387538763877387830 unmodified lines39093910391135013912391339143915391610 unmodified lines3927392839293518393039313932393339343935393639373525352635273528352935303531393839393940394139423943394439453946394714 unmodified lines3962396339643965355239663967396839693970355735583559356039713972397339743975397653 unmodified lines40304031403236203621362236233624362536263627403340344035403640374038403940404041404244 unmodified lines40874088408936784090409140924093409440953681368236833684409640974098409941004101410227 unmodified lines41304131413237183719372037214133413441354136413741383727372841394140414141424143414441452 unmodified lines41484149415041513737415241534154415522 unmodified lines4178417941803766376741814182418341844185418612 unmodified lines41994200420137863787420242034204420557 unmodified lines42634264426538513852426642674268426942704271427229 unmodified lines43024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440617 unmodified lines442444254426392144274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944606 unmodified lines446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445553943455645574558455942 unmodified lines460246034604399239933994460546064607460836 unmodified lines464546464647464840374649465046514040404146524653465446554656465723 unmodified lines468146824683407140724073468446854686468746884689407640774078469046914692469346949 unmodified lines4704470547064094409547074708470947104711471215 unmodified lines472847294730411741184731473247334734473547369 unmodified lines474647474748474941344750475147524753475447554756475747584141475947604761476211 unmodified lines47744775477647774159477847794780478139 unmodified lines4821482248234824420548254826482748281 unmodified line483048314832421348334834483548364837483848394840484148424220484348444845484672 unmodified lines4919492049214922429949234924492549268 unmodified lines493549364937431449384939494049414942494349444945431949464947494849494950495150 unmodified lines5002500350045005437650065007500850095 unmodified lines501550165017438843894390439150185019502050212 unmodified lines50245025502644005027502850295030503150324402503350345035503612 unmodified lines5049505050514421442250525053505450555056505739 unmodified lines509750985099446851005101510251035104510549 unmodified lines5155515651575158452451595160516151628 unmodified lines5171517251734539454051745175517651775178517951804545454651815182518351845185518651874550518851895190519113 unmodified lines520552065207457045715208520952105211521252134575457652145215521652175218521913 unmodified lines5233523452355236459652375238523952404 unmodified lines524552465247460746084609524852495250525152521 unmodified line525452555256461752575258525952605261526218 unmodified lines52815282528352844642528552865287528816 unmodified lines5305530653075308466553095310531153128 unmodified lines532153225323468046815324532553265327532853295330468853315332533353345335533653375338533943 unmodified lines5383538453854738538653875388538953905391539247425393539453955396134 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 lines Skipped { 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 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_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 lines Regex::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_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() 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 lines let 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 lines Processed::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 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 lines if !path.exists() { return Ok(Vec::new()); } let file = File::open(path) .with_context(|| format!("failed to open whitelist {}", path.display()))?; 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 lines if !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 lines if !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 lines if !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 lines let (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 lines continue; } output.push(json!({ "role": fine_title_role(segment, &text, is_leaf, candidate_index, title_ranges.len()), "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 role == "TITLE" || role == "O" || role == "HASH" { if is_title_role(role) || role == "O" || role == "HASH" { continue; } let text = group_text(tokens, &groups[group_index]);15 unmodified lines output}
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 lines
fn audit_warnings(record: &Record) -> Vec<String> { let mut warnings = Vec::new(); let title_texts = entity_texts(&record.tokens, &record.labels, "TITLE"); 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 title_spans > 1 { } 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 lines warnings.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 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") 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> {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); if entity == Some(target) { 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(); } 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 lines spans}
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" "tv" | "movie" | "mov" | "sample" | "commercial"53 unmodified lines recipes: &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 lines return Processed::Skipped { reason: "encoding_noise", trimmed_parent: false, example: None, warnings: Vec::new(), }; } let (training_filename, trimmed_parent) = training_filename_for(original);4 unmodified lines return Processed::Skipped { reason: "no_recipe", trimmed_parent, example: None, warnings: Vec::new(), } } };3 unmodified lines return Processed::Skipped { reason: "sample_cap", trimmed_parent, example: None, warnings: Vec::new(), }; } }1 unmodified line return 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 lines return Processed::Skipped { reason: "role_mismatch", trimmed_parent, example: None, warnings: Vec::new(), } } };2 unmodified lines return Processed::Skipped { reason: "low_frequency_audit_warning", trimmed_parent, example: Some(record.filename.clone()), warnings, }; } if trimmed_parent {415 unmodified lines roles}
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| role == "TITLE") 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) }) 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() ), format!("{} {}", parent, parts[parts.len() - 1].trim()), true, ); }89 unmodified lines return 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() part.chars().any(|ch| matches!(ch, '帽' | '茅' | '脳' | '锛')) .any(|ch| matches!(ch, '帽' | '茅' | '脳' | '锛')) && part.chars().any(|ch| ch.is_ascii_alphabetic()) }); marker_hits >= 2 || (marker_hits >= 1 && halfwidth_hits >= 1) || latin_mojibake1 unmodified line
fn has_non_anime_noise(value: &str) -> bool { let normalized = value.replace('\\', "/").trim().to_ascii_lowercase(); normalized == "mtv" || normalized.starts_with("mtv/") || normalized.contains("/mtv/") 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" }) && 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"), 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[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") && 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")) && !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 lines continue; } if roles[index].starts_with("EPISODE") && !output[..index].iter().any(|role| role.starts_with("EPISODE")) && !output[..index] .iter() .any(|role| role.starts_with("EPISODE")) && group_text( tokens, &groups[(0..index)6 unmodified lines output[index] = "TITLE".to_string(); continue; } if output[index] == "TITLE" && matches!(text.as_str(), "中日" | "日中" | "英日" | "日英") 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('语') 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 || (text.len() <= 3 && group_text(tokens, &groups[index - 1]) .chars() .any(|ch| !ch.is_ascii()) && !group_text(tokens, &groups[index - 1]).ends_with('第'))) && text.len() <= 2 && roles[index + 1..] .iter() .any(|role| role.starts_with("EPISODE")) && !group_followed_by_quote(tokens, groups, index) { output[index] = "TITLE".to_string(); 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 || (text.len() <= 3 && group_text(tokens, &groups[index - 1]) .chars() .any(|ch| !ch.is_ascii()) && !group_text(tokens, &groups[index - 1]).ends_with('第'))) && text.len() <= 2 && roles[index + 1..] .iter() .any(|role| role.starts_with("EPISODE")) && !group_followed_by_quote(tokens, groups, index) { output[index] = "TITLE".to_string(); 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() <= 3 && 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()))))) && previous_text.chars().all(|ch| ch.is_ascii_alphabetic()))))) { output[index] = "TITLE".to_string(); 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" )) || 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")) && !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 .iter() .enumerate() .any(|(other, role)| other != index && role == "TITLE") { output[index] = "O".to_string(); continue;9 unmodified lines continue; } if output[index] == "TITLE" && text.eq_ignore_ascii_case("Creditless") { let later_special = output[index + 1..] .iter() .any(|role| role == "SPECIAL"); 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")) && 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 lines if matches!( previous_real_text.to_ascii_lowercase().as_str(), "lesson" | "part" | "no" ) { ) { output[index] = "O".to_string(); continue; }4 unmodified lines continue; } 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] && !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")) .any(|role| role.starts_with("EPISODE")) && text.chars().all(|ch| ch.is_ascii_digit()) && text.len() <= 3 {26 unmodified lines let mut candidates = Vec::new(); let mut index = 0; while index < roles.len() { if roles[index] != "TITLE" { if !is_title_role(&roles[index]) { index += 1; continue; }1 unmodified line index += 1; loop { if index < roles.len() && roles[index] == "TITLE" && is_title_role(&roles[index]) && !(groups[index - 1].class_name == "BRACKET_TEXT" && groups[index].class_name == "BRACKET_TEXT") {3 unmodified lines if index + 1 < roles.len() && roles[index] == "O" && groups[index].class_name == "SEP" && roles[index + 1] == "TITLE" && is_title_role(&roles[index + 1]) { index += 2; continue;20 unmodified lines role.starts_with("EPISODE") || matches!( role.as_str(), "SEASON" | "SPECIAL" | "SOURCE" | "RESOLUTION" "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() { let selected_pool = if before_anchor.is_empty() || before_anchor_only_path_titles { &candidates } else { &before_anchor }; let selected = selected_pool .iter() .max_by_key(|(start, end)| { ( title_candidate_score(tokens, groups, *start, *end), *end, 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, ) }) .copied() .unwrap(); ); 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 (start, end) == selected { if selected.contains(&(start, end)) { continue; } for index in start..end { if output[index] == "TITLE" { 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 lines if 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 role == "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 lines output_labels.extend(labels); } } else { if role == "TITLE" && matches!(token.as_str(), "第" | "話" | "话" | "回" | "集") if is_title_role(role) && 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 { 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 lines output_labels.extend(labels); continue; } if role == "TITLE" { if is_title_role(role) { let (pieces, labels) = normalize_title_token(token); output_tokens.extend(pieces); output_labels.extend(labels);11 unmodified lines
fn 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 tokens[cursor].chars().all(|ch| ch.is_ascii_digit()) && tokens[cursor].len() <= 2 }) { output[index] = "B-SEASON".to_string();10 unmodified lines let mut cursor = index + 1; while cursor < tokens.len() { output[cursor] = "O".to_string(); if matches!(tokens[cursor].as_str(), "」" | "」" | "\"" | "'") && cursor > index + 1 { 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('语') }) { 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 = let later_episode = (index + 1..tokens.len()).any(|cursor| labels[cursor] == "B-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")) { 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 lines continue; } 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('集') }) && 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 lines let followed_by_title_word = (index + 1..tokens.len()) .find(|&cursor| { !joiners.contains(&tokens[cursor].as_str()) && !matches!(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") !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 lines continue; } } if label == "O" && token.chars().all(|ch| ch.is_ascii_digit()) && token.len() <= 3 { 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(), "]" | "】")) 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 lines output[index] = "B-EPISODE".to_string(); continue; } if previous_non_space if previous_non_space.is_some_and(|cursor| matches!(tokens[cursor].as_str(), "-" | "-")) .is_some_and(|cursor| matches!(tokens[cursor].as_str(), "-" | "-")) && output[..index].iter().any(|label| label == "B-TITLE") && output[index + 1..] .iter()22 unmodified lines 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| tokens[cursor] == "第") && next_non_space .is_some_and(|cursor| matches!(tokens[cursor].as_str(), "话" | "話" | "回" | "集")) && 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 lines if 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()) labels[cursor] == "O" && tokens[cursor].chars().any(|ch| ch.is_alphabetic()) }) { output[next_word] = "B-TITLE".to_string(); }57 unmodified lines output[index] = "B-TITLE".to_string(); } } if matches!(token.as_str(), "]" | "】" | ")" | ")" | ">" | ">" | "」" | "」") && index > 0 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 labels_for(filename: &str) -> Vec<(String, String)> { 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-TITLE".to_string()))); 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 lines assert!(!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(&("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 lines let 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 = let cm_version = labels_for("[U2-Rip]Inari, Konkon, Koi Iroha[CMv2][Hi10p_1080p][x264_flac]"); 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]"); 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 lines assert!(!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()))); 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", ); 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 lines assert!(!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梦归来了"); 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 lines assert!(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]"); 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 lines assert!(full.contains(&("01".to_string(), "B-EPISODE".to_string()))); assert!(!full.contains(&("01".to_string(), "B-TITLE".to_string())));
let r18 = let r18 = labels_for("[HYSUB]Skirt no Naka wa Kedamono Deshita.[01_R18][BIG5_MP4][1280X720]"); 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() assert!(ddp.iter().any(|(token, label)| token.starts_with("DDP") && label == "B-SOURCE")); .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 lines assert!(air_episode.contains(&("Air".to_string(), "B-TITLE".to_string()))); assert!(air_episode.contains(&("01".to_string(), "B-EPISODE".to_string())));
let decimal_episode = let decimal_episode = labels_for("[HoneyGod] Usagi Drop [02.5][x264_10bit][粤日双语][BDrip_1080p]"); 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 lines assert!(gundam.contains(&("00".to_string(), "B-TITLE".to_string()))); assert!(gundam.contains(&("01".to_string(), "B-EPISODE".to_string())));
let spy = let spy = labels_for("[Studio GreenTea] Spy x Family [38][WebRip][HEVC-10bit 1080p AAC ASSx2]"); 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 line assert!(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]"); 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 = let slime = labels_for("[Nekomoe kissaten&VCB-Studio] Slime 300 [Menu01][Ma10p_1080p][x265_flac]"); 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 lines assert!(was_trimmed); assert_eq!(trimmed, "Avatar The Last Airbender S2 14 [1080p]");
let plain_season_dir = let plain_season_dir = "Season 1/[Kamigami] Junjou Romantica 1 - 01 [BD 1280x720 x264 AAC Sub(Chs,Jap)]"; "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_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( "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 = let najica = "[2001] Najica_七虹香電擊作戰(ナジカ電撃作戦)_TV/SourceUnknown.RMVB.640x480.twHard/01"; "[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 lines let 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" ); 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 lines let 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"); assert_eq!( trimmed, "[BDrip] Ao no Exorcist Yuki no Hate Hen S04 [343-Labs] NCED" );
let sakura = let sakura = "Card Captor Sakura Chinese/魔卡少女樱(台配国语)/第01集 小樱与不可思议的魔法书"; "Card Captor Sakura Chinese/魔卡少女樱(台配国语)/第01集 小樱与不可思议的魔法书"; let (trimmed, was_trimmed) = training_filename_for(sakura); assert!(was_trimmed); assert_eq!(12 unmodified lines assert!(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)"); 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 lines assert!(!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 異次元妖怪かまなり"); 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 lines assert!(ghiblies.contains(&("2".to_string(), "B-TITLE".to_string()))); assert!(!ghiblies.contains(&("2".to_string(), "B-EPISODE".to_string())));
let tv_spot = let tv_spot = labels_for("[RUELL-Next] Fruits Basket TV Spot 1 (DVD 768x576 x264 AAC) [49531416]"); 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 lines assert!(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]"); 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)"); 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 = let durarara = labels_for("[VCB-Studio] Durarara!!×2 Ketsu [Menu01][Ma10p_1080p][x265_flac]"); 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 lines assert!(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]"); 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]"); 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 lines assert!(lapis.contains(&("꞉".to_string(), "B-TITLE".to_string()))); assert!(lapis.contains(&("LiGHTs".to_string(), "B-TITLE".to_string())));
let rezero = let rezero = labels_for("TVアニメ『Re:ゼロから始める異世界生活』第10話「鬼がかったやり方」予告"); 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 lines assert!(!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)", ); 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 line assert!(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]"); 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 lines assert!(one_room.contains(&("Second".to_string(), "B-SEASON".to_string()))); assert!(one_room.contains(&("Season".to_string(), "B-SEASON".to_string())));
let jade = let jade = labels_for("[GM-Team][国漫][诛仙 第2季][Jade Dynasty Ⅱ][2024][12][AVC][GB][1080P]"); 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 lines assert!(fox.contains(&("Fox".to_string(), "B-TITLE".to_string()))); assert!(fox.contains(&("Ⅷ".to_string(), "B-SEASON".to_string())));
let kage = let kage = labels_for("[LKSUB][Kage no Jitsuryokusha ni Naritakute! 2nd Season][03][GB][720P]"); 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 lines assert!(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]"); 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(); let roman_leaf = dmhy_record( "Ⅰ 001 魯邦燃起了鬥志", "tpl_test", &suggested_roles("TEXT SEP EPISODE SEP TEXT"), ) .unwrap(); assert!(roman_leaf .tokens .iter()43 unmodified lines assert!(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]"); 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 = let ep_only = dmhy_record("Ep.25", "tpl_test", &suggested_roles("TEXT SEP EPISODE")).unwrap(); dmhy_record("Ep.25", "tpl_test", &suggested_roles("TEXT SEP EPISODE")).unwrap(); assert!(audit_warnings(&ep_only).contains(&"no_title".to_string())); }}50 unmodified lines51525354555657585960616263646566676869707172158 unmodified lines2312322332182342352362371 unmodified line2392402412262422432442292452462472482492502512362522532542552 unmodified lines2582592602452612622632643 unmodified lines26826927025527127227327435 unmodified lines3103113122973133143153163013173183193202 unmodified lines3233243253103263273283294 unmodified lines3343353363213373383393402 unmodified lines34334434533034634734834935035133635235335435522 unmodified lines37837938038138238338438538638738838939039139239336736836937037137237337437539439539639737839839940040138138238338438538638738838940240340440540639339439539639739839940040140740840941040540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246341346446546646746846947047147247347447547647747847948048148211 unmodified lines494495496497498499500501101 unmodified lines60360460553860660760860913 unmodified lines62362462555855962662762862963063163263363463563663728 unmodified lines66666766866967067167267367450 unmodified lines source: 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 lines
fn 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 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 line let source = first_value(&entities, "SOURCE");
let mut specs: Vec<(String, Vec<(String, String)>, &'static str)> = Vec::new(); if let Some(title) = title.clone() { if let Some((title, title_entity)) = title.clone() { specs.push(( title.clone(), vec![(title.clone(), "TITLE".to_string())], vec![(title.clone(), title_entity.clone())], "combo_title", )); if let Some(season) = season.clone() { specs.push(( format!("{title} {season}"), vec![ (title.clone(), "TITLE".to_string()), (title.clone(), title_entity.clone()), (season.clone(), "SEASON".to_string()), ], "combo_title_season",2 unmodified lines specs.push(( format!("{title} {season} {episode}"), vec![ (title.clone(), "TITLE".to_string()), (title.clone(), title_entity.clone()), (season.clone(), "SEASON".to_string()), (episode.clone(), "EPISODE".to_string()), ],3 unmodified lines specs.push(( format!("{title} {season} {episode} [{resolution}][{source}]"), vec![ (title.clone(), "TITLE".to_string()), (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), Some(special)) = (title.clone(), special.clone()) { if let (Some((title, title_entity)), Some(special)) = (title.clone(), special.clone()) { specs.push(( format!("{title} - {special}"), vec![ (title.clone(), "TITLE".to_string()), (title.clone(), title_entity.clone()), (special.clone(), "SPECIAL".to_string()), ], "combo_title_special",2 unmodified lines specs.push(( format!("{title} - {special} [{episode}]"), vec![ (title.clone(), "TITLE".to_string()), (title.clone(), title_entity.clone()), (special.clone(), "SPECIAL".to_string()), (episode, "EPISODE".to_string()), ],4 unmodified lines specs.push(( format!("{title} - {special} [{resolution}][{source}]"), vec![ (title, "TITLE".to_string()), (title, title_entity), (special, "SPECIAL".to_string()), (resolution.clone(), "RESOLUTION".to_string()), (source, "SOURCE".to_string()),2 unmodified lines )); } } if let (Some(title), Some(resolution), Some(source)) = 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".to_string()), (title.clone(), title_entity), (resolution.clone(), "RESOLUTION".to_string()), (source, "SOURCE".to_string()), ],22 unmodified lines let 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-") { 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()); 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-") { if active_entity.as_deref() == Some(rest) { let entity = canonical_entity(rest); if active_entity == entity { 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()); flush(&mut entities, &mut active_entity, &mut active_tokens); active_entity = entity; 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(); flush(&mut entities, &mut active_entity, &mut active_tokens); } }
if let Some(entity) = active_entity.take() { if !active_tokens.is_empty() { entities .entry(entity) .or_default() .push(active_tokens.join("")); 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()); } entities}
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 lines if 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 lines let row = make_row( "One Piece Season 21 1110 [1080p][WEB-DL].mkv", &[ ("One Piece".to_string(), "TITLE".to_string()), ("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 lines assert_eq!( &combo.labels[0..9], &[ "B-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE", "I-TITLE" "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 lines assert_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 lines11121314151617181920212223242526272829303132163334183536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103102 unmodified lines2062072081342092102112122132142152162172182192202212222232242252262272282291441451461471481491501511522302312322332342352362372381582392402412422432442452462472482492502512522532542552562572581 unmodified line260261262171263264265266267268269270271272273274275276277278279280281282283284285183286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363435 unmodified lines7998008018028038048058066308078088098108116358128138148158168178188198208218228238248258268278288298308318328338348358368378386 unmodified lines84584684765465565684884985085120 unmodified lines87287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994068668768868969094194294394434 unmodified lines97998098173198298398498598698798841 unmodified lines103010311032779780781782783103310341035103620 unmodified lines10571058105981081181281381410601061106210635 unmodified lines10691070107182610721073828107410751076107710781079834108010811082108315 unmodified lines109911001101856857110211031104110511061107862110811091110111136 unmodified lines11481149115090590690790890991091191291311511152115311541155115611571158115935 unmodified lines119511961197955956957958959960961962963119811991200120112021203120412051206158 unmodified lines1365136613671128136813691370137113721133137313741375137627 unmodified lines140414051406116714071408140914101411141265 unmodified lines147814791480123914811482148314841485124214861487148814891490149114921249149314941495149682 unmodified lines1579158015811582158315841585158615871588158915901591159224 unmodified lines1617161816191620162116221623412 unmodified lines203620372038178617871788178917901791179217931794179517961797179817991800180118021803203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209097 unmodified lines21882189219019072191219221932194219525 unmodified lines222122222223193919401941194222242225222622273 unmodified lines2231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622875 unmodified lines229322942295196322962297229822992300230123023 unmodified lines23062307230819731974230923102311231223135 unmodified lines23192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623675 unmodified lines2373237423751997199823762377237823792380238123822383238410 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; 7] = [const ENTITIES: [Entity; 18] = [ Entity::Group, Entity::Title, 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, Title, TitleChs, TitleCht, TitleJpn, TitleLatin, TitleMixed, PathTitleChs, PathTitleCht, PathTitleJpn, PathTitleLatin, PathTitleMixed, PathSeason, Season, Episode, Special, Resolution, Source, Tag,}
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, } 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" => Some(Entity::Title), "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 line fn b_label(self) -> &'static str { match self { Entity::Group => "B-GROUP", Entity::Title => "B-TITLE", 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::Title => "I-TITLE", 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, &row.labels); let fields = extract_fields(&row.tokens, &labels); samples.push(SourceSample { row_index: idx, filename, tokens: row.tokens, labels: row.labels, 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 lines seen: &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); } push_extracted_field(fields, seen, entity, value); } text.clear(); };20 unmodified lines fields}
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 = ENTITIES .iter() .copied() .filter(|entity| !sample.fields[entity.index()].is_empty()) .collect::<Vec<_>>(); let available = ordinary_available_entities(sample); let n = available.len(); if n == 0 || !cfg.include_bio_variants { return count;34 unmodified lines if cfg.path_samples_per_source == 0 || cfg.path_styles.is_empty() { return 0; } if sample.fields[Entity::Title.index()].is_empty() { 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 lines return Ok(()); }
let available = ENTITIES .iter() .copied() .filter(|entity| !sample.fields[entity.index()].is_empty()) .collect::<Vec<_>>(); let available = ordinary_available_entities(sample); let n = available.len(); for mask in 1usize..(1usize << n) { let mut selected = available20 unmodified lines let 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<_>>(); let available = ordinary_available_entities(sample); if available.is_empty() { return Ok(()); }5 unmodified lines let mut attempts = 0usize;
let mut templates: Vec<Vec<PartChoice>> = Vec::new(); if let Some(title) = sample.fields[Entity::Title.index()].first() { if let Some((title_entity, title)) = first_file_title_field(sample) { templates.push(vec![PartChoice { entity: Entity::Title, entity: title_entity, value: title.clone(), }]); if let Some(season) = sample.fields[Entity::Season.index()].first() { templates.push(vec![ PartChoice { entity: Entity::Title, entity: title_entity, value: title.clone(), }, PartChoice {15 unmodified lines value: special.clone(), }]); } if let (Some(title), Some(special)) = ( sample.fields[Entity::Title.index()].first(), if let (Some((title_entity, title)), Some(special)) = ( first_file_title_field(sample), sample.fields[Entity::Special.index()].first(), ) { templates.push(vec![ PartChoice { entity: Entity::Title, entity: title_entity, 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.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| 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.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 lines cfg: &GenConfig, rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> { let title = choose_field(sample, Entity::Title, rng)?; 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(), Entity::Title)]); 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 lines components.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)), 4 => components.push(grouped_release_file_component( &title, endpoint, sample, rng, )), _ => { components.push(vec![endpoint]); if rng.gen_bool(0.55) {65 unmodified lines sample: &SourceSample, rng: &mut StdRng,) -> Option<Vec<LabeledPiece>> { let season = if let Some(source_season) = choose_field(sample, Entity::Season, rng) { 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 = ["Season 1", "Season 01", "S01", "第1季"]; 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::Season)]) 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> { 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, }) 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 lines
fn sample_without_season() -> SourceSample { let mut fields = vec![Vec::new(); ENTITIES.len()]; fields[Entity::Title.index()] = vec!["Example Show".to_string()]; 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 lines assert!( non_empty_components >= 2, "expected at least two noise directories for {style:?}: {}", render_labeled_pieces(&join_path_components( &components, style.separator() )) 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 lines let text = render_labeled_pieces(&pieces); assert!(text.contains("Example Show")); assert!( text.contains("Season") || text.contains("S01") || text.contains("第1季"), text.contains("Season") || text.contains("S01") || text.contains("第1季") || text.contains("01"), "missing synthetic season directory in {text}" );
3 unmodified lines for 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::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 lines assert!(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 lines assert!(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.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