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
Add Rust DMHY template recipe applier
Browse filesFiles changed (5)
1/target/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911# This file is automatically @generated by Cargo.# It is not intended for manual editing.version = 4
[[package]]name = "aho-corasick"version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"dependencies = [ "memchr",]
[[package]]name = "android_system_properties"version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"dependencies = [ "libc",]
[[package]]name = "anstream"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"dependencies = [ "anstyle", "anstyle-parse", "anstyle-query", "anstyle-wincon", "colorchoice", "is_terminal_polyfill", "utf8parse",]
[[package]]name = "anstyle"version = "1.0.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]name = "anstyle-parse"version = "1.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"dependencies = [ "utf8parse",]
[[package]]name = "anstyle-query"version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [ "windows-sys",]
[[package]]name = "anstyle-wincon"version = "3.0.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = [ "anstyle", "once_cell_polyfill", "windows-sys",]
[[package]]name = "anyhow"version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]name = "autocfg"version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]name = "bitflags"version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
[[package]]name = "bumpalo"version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]name = "cc"version = "1.2.62"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"dependencies = [ "find-msvc-tools", "shlex",]
[[package]]name = "cfg-if"version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]name = "chrono"version = "0.4.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"dependencies = [ "iana-time-zone", "num-traits", "windows-link",]
[[package]]name = "clap"version = "4.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"dependencies = [ "clap_builder", "clap_derive",]
[[package]]name = "clap_builder"version = "4.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"dependencies = [ "anstream", "anstyle", "clap_lex", "strsim",]
[[package]]name = "clap_derive"version = "4.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"dependencies = [ "heck", "proc-macro2", "quote", "syn",]
[[package]]name = "clap_lex"version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
[[package]]name = "colorchoice"version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]name = "core-foundation-sys"version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]name = "crossbeam-deque"version = "0.8.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"dependencies = [ "crossbeam-epoch", "crossbeam-utils",]
[[package]]name = "crossbeam-epoch"version = "0.9.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"dependencies = [ "crossbeam-utils",]
[[package]]name = "crossbeam-utils"version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
[[package]]name = "either"version = "1.16.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
[[package]]name = "equivalent"version = "1.0.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]name = "errno"version = "0.3.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = [ "libc", "windows-sys",]
[[package]]name = "fastrand"version = "2.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]name = "find-msvc-tools"version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]name = "foldhash"version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]name = "futures-core"version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
[[package]]name = "futures-task"version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]name = "futures-util"version = "0.3.32"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"dependencies = [ "futures-core", "futures-task", "pin-project-lite", "slab",]
[[package]]name = "getrandom"version = "0.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"dependencies = [ "cfg-if", "libc", "r-efi", "wasip2", "wasip3",]
[[package]]name = "hashbrown"version = "0.15.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"dependencies = [ "foldhash",]
[[package]]name = "hashbrown"version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]name = "heck"version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]name = "iana-time-zone"version = "0.1.65"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "log", "wasm-bindgen", "windows-core",]
[[package]]name = "iana-time-zone-haiku"version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"dependencies = [ "cc",]
[[package]]name = "id-arena"version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]name = "indexmap"version = "2.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"dependencies = [ "equivalent", "hashbrown 0.17.1", "serde", "serde_core",]
[[package]]name = "is_terminal_polyfill"version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]name = "itoa"version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]name = "js-sys"version = "0.3.99"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"dependencies = [ "cfg-if", "futures-util", "once_cell", "wasm-bindgen",]
[[package]]name = "leb128fmt"version = "0.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]name = "libc"version = "0.2.186"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]name = "linux-raw-sys"version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]name = "log"version = "0.4.30"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5"
[[package]]name = "memchr"version = "2.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
[[package]]name = "num-traits"version = "0.2.19"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"dependencies = [ "autocfg",]
[[package]]name = "once_cell"version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]name = "once_cell_polyfill"version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]name = "pin-project-lite"version = "0.2.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]name = "prettyplease"version = "0.2.37"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"dependencies = [ "proc-macro2", "syn",]
[[package]]name = "proc-macro2"version = "1.0.106"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"dependencies = [ "unicode-ident",]
[[package]]name = "quote"version = "1.0.45"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"dependencies = [ "proc-macro2",]
[[package]]name = "r-efi"version = "6.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]name = "rayon"version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"dependencies = [ "either", "rayon-core",]
[[package]]name = "rayon-core"version = "1.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"dependencies = [ "crossbeam-deque", "crossbeam-utils",]
[[package]]name = "regex"version = "1.12.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax",]
[[package]]name = "regex-automata"version = "0.4.14"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"dependencies = [ "aho-corasick", "memchr", "regex-syntax",]
[[package]]name = "regex-syntax"version = "0.8.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]]name = "rust_dmhy_template_apply"version = "0.1.0"dependencies = [ "anyhow", "chrono", "clap", "once_cell", "rayon", "regex", "serde", "serde_json", "tempfile",]
[[package]]name = "rustix"version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys",]
[[package]]name = "rustversion"version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]name = "semver"version = "1.0.28"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]name = "serde"version = "1.0.228"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"dependencies = [ "serde_core", "serde_derive",]
[[package]]name = "serde_core"version = "1.0.228"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"dependencies = [ "serde_derive",]
[[package]]name = "serde_derive"version = "1.0.228"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"dependencies = [ "proc-macro2", "quote", "syn",]
[[package]]name = "serde_json"version = "1.0.150"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"dependencies = [ "itoa", "memchr", "serde", "serde_core", "zmij",]
[[package]]name = "shlex"version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]name = "slab"version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]name = "strsim"version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]name = "syn"version = "2.0.117"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"dependencies = [ "proc-macro2", "quote", "unicode-ident",]
[[package]]name = "tempfile"version = "3.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys",]
[[package]]name = "unicode-ident"version = "1.0.24"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]name = "unicode-xid"version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]name = "utf8parse"version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]name = "wasip2"version = "1.0.3+wasi-0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"dependencies = [ "wit-bindgen 0.57.1",]
[[package]]name = "wasip3"version = "0.4.0+wasi-0.3.0-rc-2026-01-06"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"dependencies = [ "wit-bindgen 0.51.0",]
[[package]]name = "wasm-bindgen"version = "0.2.122"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", "wasm-bindgen-shared",]
[[package]]name = "wasm-bindgen-macro"version = "0.2.122"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"dependencies = [ "quote", "wasm-bindgen-macro-support",]
[[package]]name = "wasm-bindgen-macro-support"version = "0.2.122"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"dependencies = [ "bumpalo", "proc-macro2", "quote", "syn", "wasm-bindgen-shared",]
[[package]]name = "wasm-bindgen-shared"version = "0.2.122"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"dependencies = [ "unicode-ident",]
[[package]]name = "wasm-encoder"version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"dependencies = [ "leb128fmt", "wasmparser",]
[[package]]name = "wasm-metadata"version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"dependencies = [ "anyhow", "indexmap", "wasm-encoder", "wasmparser",]
[[package]]name = "wasmparser"version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"dependencies = [ "bitflags", "hashbrown 0.15.5", "indexmap", "semver",]
[[package]]name = "windows-core"version = "0.62.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"dependencies = [ "windows-implement", "windows-interface", "windows-link", "windows-result", "windows-strings",]
[[package]]name = "windows-implement"version = "0.60.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"dependencies = [ "proc-macro2", "quote", "syn",]
[[package]]name = "windows-interface"version = "0.59.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"dependencies = [ "proc-macro2", "quote", "syn",]
[[package]]name = "windows-link"version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]name = "windows-result"version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"dependencies = [ "windows-link",]
[[package]]name = "windows-strings"version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"dependencies = [ "windows-link",]
[[package]]name = "windows-sys"version = "0.61.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"dependencies = [ "windows-link",]
[[package]]name = "wit-bindgen"version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"dependencies = [ "wit-bindgen-rust-macro",]
[[package]]name = "wit-bindgen"version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
[[package]]name = "wit-bindgen-core"version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"dependencies = [ "anyhow", "heck", "wit-parser",]
[[package]]name = "wit-bindgen-rust"version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"dependencies = [ "anyhow", "heck", "indexmap", "prettyplease", "syn", "wasm-metadata", "wit-bindgen-core", "wit-component",]
[[package]]name = "wit-bindgen-rust-macro"version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"dependencies = [ "anyhow", "prettyplease", "proc-macro2", "quote", "syn", "wit-bindgen-core", "wit-bindgen-rust",]
[[package]]name = "wit-component"version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"dependencies = [ "anyhow", "bitflags", "indexmap", "log", "serde", "serde_derive", "serde_json", "wasm-encoder", "wasm-metadata", "wasmparser", "wit-parser",]
[[package]]name = "wit-parser"version = "0.244.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"dependencies = [ "anyhow", "id-arena", "indexmap", "log", "semver", "serde", "serde_derive", "serde_json", "unicode-xid", "wasmparser",]
[[package]]name = "zmij"version = "1.0.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"1234567891011121314151617[package]name = "rust_dmhy_template_apply"version = "0.1.0"edition = "2021"
[dependencies]anyhow = "1"chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }clap = { version = "4", features = ["derive"] }once_cell = "1"rayon = "1"regex = "1"serde = { version = "1", features = ["derive"] }serde_json = "1"
[dev-dependencies]tempfile = "3"123456789101112131415161718192021222324252627282930# Rust DMHY Template Apply
Multi-core Rust implementation of the DMHY template recipe apply stage.
Run from the repository root:
```powershellcargo run --release --manifest-path tools\rust_dmhy_template_apply\Cargo.toml -- ` --input datasets\AnimeName\dmhy_list.jsonl ` --recipes reports\dmhy_template_recipes.full_top5000.seed.jsonl ` --output reports\dmhy_weak.template_generated.top5000.rust.jsonl ` --manifest-output reports\dmhy_weak.template_generated.top5000.rust.manifest.json```
Optional controls:
```powershell--threads 24--limit 50000--limit-templates 1000--min-count 10--confidence high--expand sample --sample-per-template 100--keep-encoding-noise```
The output is intended to match `tools/apply_dmhy_template_recipes.py` at therecord schema level: `filename`, `tokens`, `labels`, `template_id`, `template`,plus optional `source_filename`, `path_trimmed`, and`dropped_title_candidate_positions`.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490use anyhow::{bail, Context, Result};use chrono::Utc;use clap::Parser;use once_cell::sync::Lazy;use rayon::prelude::*;use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::collections::{HashMap, HashSet};use std::fs::{self, File};use std::io::{BufRead, BufReader, BufWriter, Write};use std::path::PathBuf;use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Parser, Debug)]#[command(about = "Apply DMHY template recipes with a multi-core Rust pipeline")]struct Args { #[arg(long, default_value = "datasets/AnimeName/dmhy_list.jsonl")] input: PathBuf, #[arg(long, default_value = "reports/dmhy_template_recipes.seed.jsonl")] recipes: PathBuf, #[arg( long, default_value = "reports/dmhy_weak.template_generated.rust.jsonl" )] output: PathBuf, #[arg( long, default_value = "reports/dmhy_weak.template_generated.rust.manifest.json" )] manifest_output: PathBuf, #[arg(long)] limit: Option<usize>, #[arg(long)] limit_templates: Option<usize>, #[arg(long, default_value_t = 1)] min_count: u64, #[arg(long, default_value = "high")] confidence: String, #[arg(long, default_value = "all")] expand: String, #[arg(long, default_value_t = 100)] sample_per_template: usize, #[arg(long)] keep_encoding_noise: bool, #[arg(long)] threads: Option<usize>,}
#[derive(Debug, Clone, Deserialize)]struct Recipe { template_id: String, template: String, roles: Vec<String>, confidence: Option<String>, count: Option<u64>,}
#[derive(Debug, Clone, Serialize)]struct Record { filename: String, tokens: Vec<String>, labels: Vec<String>, template_id: String, template: String, #[serde(skip_serializing_if = "Option::is_none")] source_filename: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] path_trimmed: Option<bool>, #[serde(skip_serializing_if = "Option::is_none")] dropped_title_candidate_positions: Option<Vec<String>>,}
#[derive(Debug, Clone)]struct Group { indices: Vec<usize>, class_name: String,}
#[derive(Debug, Default, Clone, Serialize)]struct Stats { seen: usize, skipped_encoding_noise: usize, trimmed_parent_path: usize, skipped_no_recipe: usize, skipped_sample_cap: usize, skipped_role_mismatch: usize, written: usize,}
#[derive(Debug)]enum Processed { Written { record: Record, trimmed_parent: bool, }, Skipped { reason: &'static str, trimmed_parent: bool, },}
static HASH_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[A-Fa-f0-9]{8,}$").unwrap());static RESOLUTION_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:\d{3,4}p|\dK|\d{3,4}[xX×]\d{3,4})$").unwrap());static EPISODE_VERSION_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:EP?)?\d{1,4}(?:v|ver|version|rev)\d{1,3}$").unwrap());static EPISODE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}(?:END)?$").unwrap());static EPISODE_CJK_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^第?\d{1,4}[话話回集]$").unwrap());static EPISODE_RANGE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^\d{1,4}\s*[-~]\s*\d{1,4}(?:\s*END)?$").unwrap());static EPISODE_BATCH_RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"(?i)^\d{1,4}\s*[-~]\s*\d{1,4}(?:\s*(?:TV|全集|全|END|Fin|Complete|SP|OVA|OAD|NCOP|NCED)|[+_./-])*.{0,16}$").unwrap()});static SXE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^S\d{1,2}E\d{1,4}(?:v\d+)?$").unwrap());static SXE_VALUE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^S(\d{1,2})E(\d{1,4})(?:v(\d+))?$").unwrap());static SEASON_RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"(?i)^(?:S\d{1,2}|Season\s*\d{1,2}|第[一二三四五六七八九十\d]+[季期部])$").unwrap()});static CJK_SEASON_TOKEN_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^第[一二三四五六七八九十\d]+[季期部]$").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|SP|OVA|OAD|IV|Menu|Preview|Trailer|Teaser)(?:[\s_.-]?(?:\d{0,4}|Ep\d{1,4}|[A-Z]))?$").unwrap()});static VOLUME_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:Vol(?:ume)?\.?|Disc|CD|BD|DVD|D)\s*\d{1,3}$").unwrap());static DATE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(?:19|20)\d{2}(?:[._-]\d{1,2}){0,2}$").unwrap());static LANG_RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"(?i)^(?:CHS|CHT|ZHS|ZHT|GB|BIG5|JPN?|JP|JA|JAP|ENG|EN|SC|TC|简[体體]?|繁[体體]?|简日|繁日|字幕|内封|外挂|Sub|Subs|MSubs?)$").unwrap()});static MEDIA_RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"(?i)^(?:WEB[-_. ]?DL|WEB[-_. ]?Rip|BDRip|BluRay|BDMV|BD|DVDRip|DVD|HDTV|TVRip|REMUX|x26[45]|h\.?26[45]|HEVC|AVC|AV1|AAC\d*(?:\.\d+)?|FLAC|MP3|DTS|DTS-HDMA|AC3|Opus|10[-_. ]?bit|8[-_. ]?bit|Hi10p|Ma10p|ASSx?\d*|SRTx?\d*|R\d[A-Z]*|NoSub|MKV|MP4|AVI|RAW|Raws?)$").unwrap()});static SPECIAL_TITLE_PHRASE_RE: Lazy<Regex> = Lazy::new(|| { Regex::new(r"(?i)\b(?:theater\s+greeting\s+event|world\s+prem(?:eie|iere)|picture\s+drama)\b") .unwrap()});static YEAR_RANGE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"^\(?\s*(?:19|20)\d{2}\s*[-~]\s*(?:19|20)\d{2}\s*\)?$").unwrap());static TOKEN_REGEXES: Lazy<Vec<Regex>> = Lazy::new(|| { [ r"^\d{3,4}[xX×]\d{3,4}", r"^[\\/]+", r"^[-_.::+&|]+", r"^\s+", r"(?i)^Season\s*\d{1,2}", r"^[A-Za-z]+(?:\d+[A-Za-z]*)*", r"^\d+[A-Za-z]+\d*", r"^\d{1,4}(?:[._-]\d{1,4})*", r"^[\p{Hiragana}\p{Katakana}\p{Han}]+", ] .into_iter() .map(|pattern| Regex::new(pattern).unwrap()) .collect()});static SIMPLE_EPISODE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)^(?:EP?|#)?\d{1,4}$").unwrap());static SPECIAL_SPACE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"[\s_.-]+").unwrap());
fn main() -> Result<()> { let args = Args::parse(); if let Some(threads) = args.threads { rayon::ThreadPoolBuilder::new() .num_threads(threads) .build_global() .context("failed to configure rayon thread pool")?; } if args.expand != "all" && args.expand != "sample" { bail!("--expand must be all or sample"); }
let recipes = load_recipes(&args)?; if recipes.is_empty() { bail!("no recipes selected; adjust --recipes/--confidence/--min-count/--limit-templates"); } let inputs = load_input(&args.input, args.limit)?; let sample_counters: HashMap<String, AtomicUsize> = recipes .values() .map(|recipe| (recipe.template_id.clone(), AtomicUsize::new(0))) .collect();
let processed: Vec<Processed> = inputs .par_iter() .map(|filename| process_filename(filename, &args, &recipes, &sample_counters)) .collect();
if let Some(parent) = args.output.parent() { fs::create_dir_all(parent)?; } if let Some(parent) = args.manifest_output.parent() { fs::create_dir_all(parent)?; }
let mut stats = Stats { seen: inputs.len(), ..Stats::default() }; 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 writer = BufWriter::new(File::create(&args.output)?); for item in processed { match item { Processed::Written { record, trimmed_parent, } => { if trimmed_parent { stats.trimmed_parent_path += 1; } for label in &record.labels { *label_counts.entry(label.clone()).or_default() += 1; } *template_counts .entry(record.template_id.clone()) .or_default() += 1; if examples.len() < 20 { examples.push(serde_json::to_value(&record)?); } serde_json::to_writer(&mut writer, &record)?; writer.write_all(b"\n")?; stats.written += 1; } Processed::Skipped { reason, trimmed_parent, } => { if trimmed_parent { stats.trimmed_parent_path += 1; } match reason { "encoding_noise" => stats.skipped_encoding_noise += 1, "no_recipe" => stats.skipped_no_recipe += 1, "sample_cap" => stats.skipped_sample_cap += 1, "role_mismatch" => stats.skipped_role_mismatch += 1, _ => {} } } } } writer.flush()?;
let mut top_template_counts: Vec<_> = template_counts.into_iter().collect(); top_template_counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); top_template_counts.truncate(20);
let manifest = json!({ "generated_at": Utc::now().to_rfc3339(), "input": args.input.to_string_lossy(), "recipes": args.recipes.to_string_lossy(), "output": args.output.to_string_lossy(), "selected_templates": recipes.len(), "confidence": args.confidence, "min_count": args.min_count, "expand": args.expand, "sample_per_template": if args.expand == "sample" { Some(args.sample_per_template) } else { None }, "stats": stats, "label_counts": label_counts, "top_template_counts": top_template_counts, "examples": examples, "implementation": "rust_dmhy_template_apply" }); fs::write( &args.manifest_output, serde_json::to_string_pretty(&manifest)?, )?; println!("{}", serde_json::to_string_pretty(&manifest)?); Ok(())}
fn load_recipes(args: &Args) -> Result<HashMap<String, Recipe>> { let file = File::open(&args.recipes) .with_context(|| format!("recipe JSONL not found: {}", args.recipes.display()))?; let mut recipes = HashMap::new(); for (line_number, line) in BufReader::new(file).lines().enumerate() { let line = line?; if line.trim().is_empty() { continue; } let row: Recipe = serde_json::from_str(&line).with_context(|| { format!( "invalid recipe JSON at {}:{}", args.recipes.display(), line_number + 1 ) })?; if !args.confidence.is_empty() && row.confidence.as_deref() != Some(args.confidence.as_str()) { continue; } if row.count.unwrap_or(0) < args.min_count { continue; } recipes.insert(row.template.clone(), row); if args .limit_templates .is_some_and(|limit| recipes.len() >= limit) { break; } } Ok(recipes)}
fn load_input(path: &PathBuf, limit: Option<usize>) -> Result<Vec<String>> { let file = File::open(path).with_context(|| format!("input JSONL not found: {}", path.display()))?; let mut values = Vec::new(); for (line_number, line) in BufReader::new(file).lines().enumerate() { if limit.is_some_and(|limit| values.len() >= limit) { break; } let line = line?; if line.trim().is_empty() { continue; } let row: Value = serde_json::from_str(&line) .with_context(|| format!("invalid JSON at {}:{}", path.display(), line_number + 1))?; if let Some(value) = row.get("value").and_then(Value::as_str) { let value = value.trim(); if !value.is_empty() { values.push(value.to_string()); } } } Ok(values)}
fn process_filename( original: &str, args: &Args, recipes: &HashMap<String, Recipe>, sample_counters: &HashMap<String, AtomicUsize>,) -> Processed { if !args.keep_encoding_noise && (has_encoding_noise(original) || has_non_anime_noise(original) || has_abstract_path_noise(original)) { return Processed::Skipped { reason: "encoding_noise", trimmed_parent: false, }; } let (training_filename, trimmed_parent) = training_filename_for(original); let (key, _tokens, _classes, groups) = template_key_for_filename(&training_filename); let recipe = match recipes.get(&key) { Some(recipe) => recipe, None => { return Processed::Skipped { reason: "no_recipe", trimmed_parent, } } }; if args.expand == "sample" { let counter = sample_counters.get(&recipe.template_id).unwrap(); if counter.fetch_add(1, Ordering::Relaxed) >= args.sample_per_template { return Processed::Skipped { reason: "sample_cap", trimmed_parent, }; } } if recipe.roles.len() != groups.len() { return Processed::Skipped { reason: "role_mismatch", trimmed_parent, }; } let mut record = match dmhy_record(&training_filename, &recipe.template_id, &recipe.roles) { Some(record) => record, None => { return Processed::Skipped { reason: "role_mismatch", trimmed_parent, } } }; if trimmed_parent { record.source_filename = Some(original.to_string()); record.path_trimmed = Some(true); return Processed::Written { record, trimmed_parent: true, }; } Processed::Written { record, trimmed_parent: false, }}
fn tokenize(value: &str) -> Vec<String> { let mut output = Vec::new(); let mut index = 0; while index < value.len() { let rest = &value[index..]; if let Some((token, len)) = next_token(rest) { output.push(token); index += len; } else { let ch = rest.chars().next().unwrap(); output.push(ch.to_string()); index += ch.len_utf8(); } } output}
fn next_token(rest: &str) -> Option<(String, usize)> { let first = rest.chars().next()?; if first == '[' { if let Some(end) = rest.find(']') { if end <= 121 { return Some((rest[..=end].to_string(), end + 1)); } } } if first == '(' { if let Some(end) = rest.find(')') { if end <= 121 { return Some((rest[..=end].to_string(), end + 1)); } } } if first == '【' { if let Some(end) = rest.find('】') { if rest[..end].chars().count() <= 120 { return Some(( rest[..end + '】'.len_utf8()].to_string(), end + '】'.len_utf8(), )); } } } for re in TOKEN_REGEXES.iter() { if let Some(mat) = re.find(rest) { if mat.start() == 0 && mat.end() > 0 { return Some((mat.as_str().to_string(), mat.end())); } } } None}
fn strip_wrapper(token: &str) -> String { let chars: Vec<char> = token.chars().collect(); if chars.len() >= 2 { let first = chars[0]; let last = chars[chars.len() - 1]; if (first == '[' && last == ']') || (first == '(' && last == ')') || (first == '【' && last == '】') { return chars[1..chars.len() - 1] .iter() .collect::<String>() .trim() .to_string(); } } token.trim().to_string()}
fn split_inner(inner: &str) -> Vec<String> { let mut parts = Vec::new(); let mut current = String::new(); for ch in inner.chars() { if ch.is_whitespace() || "_.,+/&|-".contains(ch) { if !current.is_empty() { parts.push(std::mem::take(&mut current)); } } else { current.push(ch); } } if !current.is_empty() { parts.push(current); } parts}
fn compact_for_classify(text: &str) -> String { text.chars() .filter(|ch| !ch.is_whitespace() && !matches!(ch, '_' | '.' | ',' | '-')) .collect()}
fn classify_atom(text: &str) -> String { let cleaned = strip_wrapper(text); let compact = compact_for_classify(&cleaned); if cleaned.is_empty() { return "EMPTY".to_string(); } if HASH_RE.is_match(&cleaned) { return "HASH".to_string(); } if RESOLUTION_RE.is_match(&cleaned) { return "RESOLUTION".to_string(); } if DATE_RE.is_match(&cleaned) { return "DATE".to_string(); } if EPISODE_VERSION_RE.is_match(&compact) { return "EPISODE_VERSION".to_string(); } if SXE_RE.is_match(&compact) { return "SXE".to_string(); } if EPISODE_RE.is_match(&compact) { return "EPISODE".to_string(); } if EPISODE_CJK_RE.is_match(&cleaned) { return "EPISODE".to_string(); } if EPISODE_BATCH_RE.is_match(&cleaned) { return "EPISODE_RANGE".to_string(); } if EPISODE_RANGE_RE.is_match(&cleaned) { return "EPISODE_RANGE".to_string(); } if EPISODE_RE.is_match(&cleaned) { return "EPISODE".to_string(); } if SEASON_RE.is_match(&cleaned) { return "SEASON".to_string(); } if SPECIAL_RE.is_match(&cleaned) { return "SPECIAL".to_string(); } if VOLUME_RE.is_match(&cleaned) { return "VOLUME".to_string(); } if LANG_RE.is_match(&cleaned) || lang_block_matches(&cleaned) { return "LANG".to_string(); } if MEDIA_RE.is_match(&cleaned) { return "MEDIA".to_string(); } "TEXT".to_string()}
fn lang_block_matches(text: &str) -> bool { let upper = text.to_ascii_uppercase(); if ["CHS", "CHT", "ZHS", "ZHT", "BIG5"] .iter() .any(|marker| upper.contains(marker)) { return true; } if upper.contains("GB") { return true; } if [ "简繁", "简日", "繁日", "简体", "繁体", "雙語", "双语", "内封", "外挂", ] .iter() .any(|marker| text.contains(marker)) { return true; } let chars: Vec<char> = text.chars().collect(); chars.windows(2).enumerate().any(|(index, pair)| { pair[0] == '字' && pair[1] == '幕' && !matches!(chars.get(index + 2), Some('组' | '組')) })}
fn classify_token(token: &str) -> String { if token.is_empty() { return "EMPTY".to_string(); } if token.chars().all(char::is_whitespace) { return "SPACE".to_string(); } if token.chars().all(|ch| ch == '/' || ch == '\\') { return "PATH".to_string(); } if token.chars().all(|ch| "-_.::+&|".contains(ch)) { return "SEP".to_string(); } if token.starts_with('[') || token.starts_with('(') || token.starts_with('【') { let inner = strip_wrapper(token); let whole_class = classify_atom(&inner); let parts = split_inner(&inner); let inner_class = if whole_class != "TEXT" { whole_class } else if parts.is_empty() { "EMPTY".to_string() } else { let part_classes: Vec<String> = parts.iter().map(|part| classify_atom(part)).collect(); if part_classes.iter().all(|item| item == &part_classes[0]) { part_classes[0].clone() } else if part_classes.iter().all(|item| is_media_block_class(item)) { "MEDIA_BLOCK".to_string() } else if part_classes.iter().any(|item| is_media_block_class(item)) && parts.iter().zip(part_classes.iter()).all(|(part, item)| { is_media_block_class(item) || matches!(part.to_ascii_lowercase().as_str(), "anime" | "アニメ") }) { "MEDIA_BLOCK".to_string() } else if part_classes.iter().any(|item| item == "TEXT") { "TEXT".to_string() } else { let mut set: Vec<String> = part_classes .into_iter() .collect::<HashSet<_>>() .into_iter() .collect(); set.sort(); set.join("_") } }; return format!("BRACKET_{inner_class}"); } classify_atom(token)}
fn is_media_block_class(value: &str) -> bool { matches!(value, "MEDIA" | "RESOLUTION" | "LANG" | "HASH" | "DATE")}
fn compact_token_groups(_tokens: &[String], classes: &[String]) -> Vec<Group> { let mut groups: Vec<Group> = Vec::new(); let mut previous: Option<String> = None; for (index, token_class) in classes.iter().enumerate() { let current = if token_class == "SPACE" { "SEP" } else { token_class } .to_string(); if previous.as_deref() == Some(current.as_str()) && matches!(current.as_str(), "SEP" | "TEXT") { groups.last_mut().unwrap().indices.push(index); } else { groups.push(Group { indices: vec![index], class_name: current.clone(), }); } previous = Some(current); } groups}
fn template_key_for_filename(filename: &str) -> (String, Vec<String>, Vec<String>, Vec<Group>) { let tokens = tokenize(filename); let classes: Vec<String> = tokens.iter().map(|token| classify_token(token)).collect(); let groups = compact_token_groups(&tokens, &classes); let key = groups .iter() .map(|group| group.class_name.as_str()) .collect::<Vec<_>>() .join(" "); (key, tokens, classes, groups)}
fn suggested_roles(template: &str) -> Vec<String> { let items: Vec<&str> = template.split_whitespace().collect(); let mut roles = vec!["O".to_string(); items.len()]; let mut segment_starts = vec![0usize]; for (index, item) in items.iter().enumerate() { if *item == "PATH" { segment_starts.push(index + 1); } } for (index, item) in items.iter().enumerate() { roles[index] = if item.contains("EPISODE_VERSION") { "EPISODE_VERSION" } else if item.contains("EPISODE_RANGE") { "EPISODE_RANGE" } else if item.contains("EPISODE") || *item == "SXE" { "EPISODE" } else if item.contains("RESOLUTION") { "RESOLUTION" } else if item.contains("HASH") { "HASH" } else if item.contains("LANG") || item.contains("MEDIA") { "SOURCE" } else if item.contains("SPECIAL") { "SPECIAL" } else if item.contains("SEASON") { "SEASON" } else if item.contains("VOLUME") { "VOLUME" } else { "O" } .to_string(); } for (offset, start) in segment_starts.iter().enumerate() { let end = if offset + 1 < segment_starts.len() { segment_starts[offset + 1] - 1 } else { items.len() }; if *start >= end { continue; } let first_structural = (*start..end) .find(|&index| { items[index].contains("EPISODE") || matches!(items[index], "SXE" | "SPECIAL" | "SEASON") }) .unwrap_or(end); let bracket_text: Vec<usize> = (*start..first_structural) .filter(|&index| items[index] == "BRACKET_TEXT" && roles[index] == "O") .collect(); let text: Vec<usize> = (*start..first_structural) .filter(|&index| items[index] == "TEXT" && roles[index] == "O") .collect(); if bracket_text.len() >= 2 { roles[bracket_text[0]] = "GROUP".to_string(); for index in bracket_text.iter().skip(1) { roles[*index] = "TITLE".to_string(); } } else if bracket_text.len() == 1 { roles[bracket_text[0]] = if text.is_empty() { "TITLE" } else { "GROUP" }.to_string(); } for index in text { roles[index] = "TITLE".to_string(); } if !roles[*start..end].iter().any(|role| role == "TITLE") && !items[*start..end].is_empty() && items[*start].contains("EPISODE") { let mut run = Vec::new(); for index in (*start + 1)..end { if items[index] == "TEXT" && roles[index] == "O" { run.push(index); continue; } if items[index] == "SEP" { continue; } if !run.is_empty() { break; } } if run.len() >= 2 { for index in run { roles[index] = "TITLE".to_string(); } } } } roles}
fn filename_has_title(filename: &str) -> bool { let (key, _, _, _) = template_key_for_filename(filename); suggested_roles(&key).iter().any(|role| role == "TITLE")}
fn training_filename_for(original: &str) -> (String, bool) { let parts: Vec<&str> = original .split(|ch| ch == '/' || ch == '\\') .map(str::trim) .filter(|part| !part.is_empty()) .collect(); if parts.len() >= 2 && filename_has_title(parts[parts.len() - 1]) { (parts[1..].join("/"), true) } else { (original.to_string(), false) }}
fn has_encoding_noise(value: &str) -> bool { if value.contains('\u{fffd}') { return true; } let markers = [ "譁", "蜈", "螟", "蟄", "謇", "邱", "荳", "縺", "繧", "莨", "鬆", "髯", ]; let marker_hits = markers .iter() .map(|marker| value.matches(marker).count()) .sum::<usize>(); let halfwidth_hits = value .chars() .filter(|ch| ('\u{ff61}'..='\u{ff9f}').contains(ch)) .count(); marker_hits >= 2 || (marker_hits >= 1 && halfwidth_hits >= 1)}
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/")}
fn normalized_path_segment(value: &str) -> String { value .split_whitespace() .collect::<String>() .to_ascii_lowercase()}
fn path_segment_is_episodeish(value: &str) -> bool { let (_, _, _, groups) = template_key_for_filename(value); let structural: Vec<&String> = groups .iter() .map(|group| &group.class_name) .filter(|item| item.as_str() != "SEP") .collect(); !structural.is_empty() && structural .iter() .all(|item| item.starts_with("EPISODE") || item.as_str() == "SPECIAL")}
fn has_abstract_path_noise(value: &str) -> bool { let parts: Vec<&str> = value .split(|ch| ch == '/' || ch == '\\') .map(str::trim) .filter(|part| !part.is_empty()) .collect(); if parts.len() < 3 { return false; } if normalized_path_segment(parts[0]) == normalized_path_segment(parts[parts.len() - 1]) { return true; } path_segment_is_episodeish(parts[0]) && path_segment_is_episodeish(parts[parts.len() - 1])}
fn role_label(role: &str) -> String { let entity = match role { "GROUP" => Some("GROUP"), "TITLE" => Some("TITLE"), "EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" => Some("EPISODE"), "SEASON" => Some("SEASON"), "SPECIAL" | "VOLUME" => Some("SPECIAL"), "RESOLUTION" => Some("RESOLUTION"), "SOURCE" | "HASH" => Some("SOURCE"), _ => None, }; entity.map_or_else(|| "O".to_string(), |entity| format!("B-{entity}"))}
fn is_separator(piece: &str) -> bool { piece.is_empty() || piece .chars() .all(|ch| ch.is_whitespace() || !ch.is_alphanumeric())}
fn char_kind(ch: char) -> &'static str { if ch.is_whitespace() || !ch.is_alphanumeric() { "sep" } else if ch.is_ascii_digit() { "digit" } else if ch.is_ascii_alphabetic() { "alpha" } else { "text" }}
fn split_refined_token(token: &str) -> Vec<String> { let whole_class = classify_atom(token); let is_wrapped = { let chars: Vec<char> = token.chars().collect(); chars.len() >= 2 && ((chars[0] == '[' && chars[chars.len() - 1] == ']') || (chars[0] == '(' && chars[chars.len() - 1] == ')') || (chars[0] == '【' && chars[chars.len() - 1] == '】')) }; if !is_wrapped && matches!( whole_class.as_str(), "RESOLUTION" | "MEDIA" | "LANG" | "HASH" | "SXE" | "EPISODE_VERSION" ) && token.chars().all(char::is_alphanumeric) { return vec![token.to_string()]; } if !is_wrapped && whole_class == "EPISODE" && SIMPLE_EPISODE_RE.is_match(token) { return vec![token.to_string()]; } let mut pieces = Vec::new(); let mut current = String::new(); let mut current_kind: Option<&str> = None; for ch in token.chars() { let kind = char_kind(ch); if kind == "sep" { if !current.is_empty() { pieces.push(std::mem::take(&mut current)); current_kind = None; } pieces.push(ch.to_string()); continue; } if !current.is_empty() && current_kind != Some(kind) { pieces.push(std::mem::take(&mut current)); } current.push(ch); current_kind = Some(kind); } if !current.is_empty() { pieces.push(current); } let mut merged = Vec::new(); let mut index = 0; while index < pieces.len() { if !is_separator(&pieces[index]) { let mut end = index; let mut combined = String::new(); while end < pieces.len() && !is_separator(&pieces[end]) { combined.push_str(&pieces[end]); end += 1; } if end > index + 1 && is_mergeable_refined_class(&classify_atom(&combined)) { merged.push(combined); index = end; continue; } } if index + 1 < pieces.len() && !is_separator(&pieces[index]) && !is_separator(&pieces[index + 1]) { let combined = format!("{}{}", pieces[index], pieces[index + 1]); if is_mergeable_refined_class(&classify_atom(&combined)) { merged.push(combined); index += 2; continue; } } merged.push(pieces[index].clone()); index += 1; } merged}
fn is_mergeable_refined_class(value: &str) -> bool { matches!( value, "RESOLUTION" | "MEDIA" | "LANG" | "HASH" | "SXE" | "EPISODE_VERSION" | "SEASON" )}
fn label_for_refined_piece(piece: &str, role: &str, token_class: &str) -> String { if is_separator(piece) { return "O".to_string(); } let atom_class = classify_atom(piece); let upper = piece.to_ascii_uppercase(); if matches!(role, "EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE") { if atom_class == "SEASON" { return "B-SEASON".to_string(); } if matches!(atom_class.as_str(), "EPISODE" | "EPISODE_VERSION" | "SXE") || piece.chars().all(|ch| ch.is_ascii_digit()) { return "B-EPISODE".to_string(); } if matches!(atom_class.as_str(), "SPECIAL" | "VOLUME") || matches!( upper.as_str(), "OVA" | "OAD" | "SP" | "PV" | "CM" | "OP" | "ED" | "NCOP" | "NCED" ) { return "B-SPECIAL".to_string(); } return "O".to_string(); } if role == "SOURCE" || matches!(token_class, "BRACKET_MEDIA_BLOCK" | "MEDIA_BLOCK") { if atom_class == "RESOLUTION" { return "B-RESOLUTION".to_string(); } if matches!(atom_class.as_str(), "MEDIA" | "LANG" | "HASH") { return "B-SOURCE".to_string(); } if matches!(atom_class.as_str(), "SPECIAL" | "VOLUME") { return "B-SPECIAL".to_string(); } return if matches!( upper.as_str(), "END" | "FIN" | "COMPLETE" | "TV" | "全集" | "全" ) { "O".to_string() } else { "B-SOURCE".to_string() }; } if role == "RESOLUTION" { return if atom_class == "RESOLUTION" || piece.chars().all(|ch| ch.is_ascii_digit()) { "B-RESOLUTION".to_string() } else { "O".to_string() }; } role_label(role)}
fn split_sxe_token(token: &str) -> Option<(Vec<String>, Vec<String>)> { let caps = SXE_VALUE_RE.captures(token)?; let mut pieces = vec![ "S".to_string(), caps[1].to_string(), "E".to_string(), caps[2].to_string(), ]; let mut labels = vec![ "O".to_string(), "B-SEASON".to_string(), "O".to_string(), "B-EPISODE".to_string(), ]; if let Some(version) = caps.get(3) { pieces.push("v".to_string()); pieces.push(version.as_str().to_string()); labels.push("O".to_string()); labels.push("O".to_string()); } Some((pieces, labels))}
fn split_season_token(token: &str) -> Option<(Vec<String>, Vec<String>)> { let caps = SEASON_VALUE_RE.captures(token)?; Some(( vec!["S".to_string(), caps[1].to_string()], vec!["O".to_string(), "B-SEASON".to_string()], ))}
fn group_text(tokens: &[String], group: &Group) -> String { strip_wrapper( &group .indices .iter() .map(|&index| tokens[index].as_str()) .collect::<String>(), )}
fn is_special_title_phrase(text: &str) -> bool { let normalized = SPECIAL_SPACE_RE .replace_all(text, " ") .trim() .to_ascii_uppercase(); matches!( normalized.as_str(), "CM" | "EVENT" | "EIZOU" | "LOGO" | "MENU" | "OMAKE" | "PREVIEW" | "PV" | "THEATER GREETING EVENT" | "TOKUTEN" | "TRAILER" | "WORLD PREMIERE" ) || SPECIAL_TITLE_PHRASE_RE.is_match(text)}
fn adjust_contextual_roles(tokens: &[String], groups: &[Group], roles: &[String]) -> Vec<String> { let mut output = roles.to_vec(); let ep_markers = ["EP", "E", "Episode", "ep", "episode"]; let roman = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"]; if !output.iter().any(|role| role == "TITLE") && roles .first() .is_some_and(|role| role.starts_with("EPISODE")) { let mut title_run = Vec::new(); for index in 1..roles.len() { if groups[index].class_name == "TEXT" && output[index] == "O" { title_run.push(index); continue; } if groups[index].class_name == "SEP" { continue; } if !title_run.is_empty() { break; } } if title_run.len() >= 2 { for index in title_run { output[index] = "TITLE".to_string(); } } } for index in 0..roles.len() { let text = group_text(tokens, &groups[index]); if roles[index].starts_with("EPISODE") && YEAR_RANGE_RE.is_match(&text) { output[index] = "O".to_string(); continue; } if roles[index] == "TITLE" && is_special_title_phrase(&text) { output[index] = "SPECIAL".to_string(); continue; } if roles[index] == "TITLE" && matches!(text.to_ascii_lowercase().as_str(), "season" | "saison") && index + 2 < roles.len() && groups[index + 1].class_name == "SEP" && roles[index + 2].starts_with("EPISODE") { output[index] = "O".to_string(); output[index + 2] = "SEASON".to_string(); continue; } if roles[index] == "TITLE" && roman.contains(&text.to_ascii_uppercase().as_str()) { let previous_title = output[..index].iter().any(|role| role == "TITLE"); let next_structural = roles[index + 1..] .iter() .any(|role| role.starts_with("EPISODE") || role == "SPECIAL"); if previous_title && next_structural { output[index] = "SEASON".to_string(); continue; } } if roles[index].starts_with("EPISODE") && index + 4 < roles.len() { if groups[index + 1].class_name == "SEP" && ep_markers.contains(&group_text(tokens, &groups[index + 2]).as_str()) && groups[index + 3].class_name == "SEP" && roles[index + 4].starts_with("EPISODE") { output[index] = "TITLE".to_string(); output[index + 2] = "O".to_string(); } } } output}
fn title_candidates(groups: &[Group], roles: &[String]) -> Vec<(usize, usize)> { let mut candidates = Vec::new(); let mut index = 0; while index < roles.len() { if roles[index] != "TITLE" { index += 1; continue; } if groups[index].class_name == "BRACKET_TEXT" { candidates.push((index, index + 1)); index += 1; continue; } let start = index; index += 1; while index + 1 < roles.len() && roles[index] == "O" && groups[index].class_name == "SEP" && roles[index + 1] == "TITLE" { index += 2; } candidates.push((start, index)); } candidates}
fn enforce_single_title_candidate( groups: &[Group], roles: &[String],) -> (Vec<String>, Vec<String>) { let candidates = title_candidates(groups, roles); if candidates.len() <= 1 { return (roles.to_vec(), Vec::new()); } let first_anchor = roles .iter() .position(|role| { role.starts_with("EPISODE") || matches!( role.as_str(), "SEASON" | "SPECIAL" | "SOURCE" | "RESOLUTION" ) }) .unwrap_or(roles.len()); let before_anchor: Vec<(usize, usize)> = candidates .iter() .copied() .filter(|(_, end)| *end <= first_anchor) .collect(); let selected = (if before_anchor.is_empty() { &candidates } else { &before_anchor }) .iter() .max_by_key(|(start, end)| (*end, end - start)) .copied() .unwrap(); let mut output = roles.to_vec(); let mut dropped = Vec::new(); for (start, end) in candidates { if (start, end) == selected { continue; } for index in start..end { if output[index] == "TITLE" { output[index] = "O".to_string(); dropped.push(index.to_string()); } } } (output, dropped)}
fn normalize_generated_tokens(tokens: &[String], labels: &[String]) -> (Vec<String>, Vec<String>) { let mut output_tokens = Vec::new(); let mut output_labels = Vec::new(); for (token, label) in tokens.iter().zip(labels.iter()) { for piece in split_generated_token(token) { output_labels.push(if label == "O" || is_standalone_separator(&piece) { "O".to_string() } else { label.clone() }); output_tokens.push(piece); } } (output_tokens, output_labels)}
fn normalize_title_token(token: &str) -> (Vec<String>, Vec<String>) { let pieces = split_generated_token(token); let labels = pieces .iter() .map(|piece| { if is_standalone_separator(piece) { "O".to_string() } else if CJK_SEASON_TOKEN_RE.is_match(piece) { "B-SEASON".to_string() } else { "B-TITLE".to_string() } }) .collect(); (pieces, labels)}
fn split_generated_token(token: &str) -> Vec<String> { let mut pieces = Vec::new(); let mut current = String::new(); for ch in token.chars() { if ch.is_whitespace() || !ch.is_alphanumeric() { if !current.is_empty() { pieces.push(std::mem::take(&mut current)); } pieces.push(ch.to_string()); } else { current.push(ch); } } if !current.is_empty() { pieces.push(current); } pieces}
fn is_standalone_separator(token: &str) -> bool { token.chars().count() == 1 && token .chars() .next() .is_some_and(|ch| ch.is_whitespace() || !ch.is_alphanumeric())}
fn project_refined_tokens( tokens: &[String], groups: &[Group], roles: &[String],) -> (Vec<String>, Vec<String>) { let mut output_tokens = Vec::new(); let mut output_labels = Vec::new(); for (group_index, group) in groups.iter().enumerate() { let mut role = roles.get(group_index).map(String::as_str).unwrap_or("O"); if matches!(group.class_name.as_str(), "SEP" | "PATH" | "EMPTY") { role = "O"; } for &index in &group.indices { let token = &tokens[index]; if matches!( role, "EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE" | "SOURCE" | "RESOLUTION" | "SEASON" ) { if role == "SEASON" { if let Some((pieces, labels)) = split_season_token(token) { output_tokens.extend(pieces); output_labels.extend(labels); continue; } } if matches!(role, "EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE") { if let Some((pieces, labels)) = split_sxe_token(token) { output_tokens.extend(pieces); output_labels.extend(labels); continue; } } for piece in split_refined_token(token) { if matches!(role, "EPISODE" | "EPISODE_VERSION" | "EPISODE_RANGE") { if let Some((pieces, labels)) = split_season_token(&piece) { output_tokens.extend(pieces); output_labels.extend(labels); continue; } } output_labels.push(label_for_refined_piece(&piece, role, &group.class_name)); output_tokens.push(piece); } } else { if role == "TITLE" && matches!(token.as_str(), "第" | "話" | "话" | "回" | "集") { output_tokens.push(token.clone()); output_labels.push("O".to_string()); continue; } if role == "TITLE" && token.ends_with('第') && token.chars().count() > 1 { let trimmed = token.trim_end_matches('第').to_string(); let (pieces, labels) = normalize_generated_tokens( &[trimmed, "第".to_string()], &["B-TITLE".to_string(), "O".to_string()], ); output_tokens.extend(pieces); output_labels.extend(labels); continue; } if role == "TITLE" { let (pieces, labels) = normalize_title_token(token); output_tokens.extend(pieces); output_labels.extend(labels); continue; } let (pieces, labels) = normalize_generated_tokens(&[token.clone()], &[role_label(role)]); output_tokens.extend(pieces); output_labels.extend(labels); } } } (output_tokens, output_labels)}
fn smooth_title_spans(tokens: &[String], labels: &[String]) -> Vec<String> { let joiners = [" ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":"]; let entity_joiners = [ " ", ".", "-", "_", "·", "・", "×", "/", "/", "'", "’", ":", "&", ]; let mut output = labels.to_vec(); for (index, (token, label)) in tokens.iter().zip(labels.iter()).enumerate() { if label != "O" || !entity_joiners.contains(&token.as_str()) { continue; } let mut left = index as isize - 1; while left >= 0 && joiners.contains(&tokens[left as usize].as_str()) && labels[left as usize] == "O" { left -= 1; } let mut right = index + 1; while right < tokens.len() && joiners.contains(&tokens[right].as_str()) && labels[right] == "O" { right += 1; } if left >= 0 && right < tokens.len() { let left_label = &output[left as usize]; let right_label = &labels[right]; if left_label == right_label && matches!(left_label.as_str(), "B-TITLE" | "B-GROUP") { output[index] = left_label.clone(); } } } output}
fn dmhy_record(filename: &str, template_id: &str, roles: &[String]) -> Option<Record> { let (key, tokens, _classes, groups) = template_key_for_filename(filename); if groups.len() != roles.len() { return None; } let roles = adjust_contextual_roles(&tokens, &groups, roles); let (roles, dropped) = enforce_single_title_candidate(&groups, &roles); let (tokens, labels) = project_refined_tokens(&tokens, &groups, &roles); let labels = smooth_title_spans(&tokens, &labels); if tokens.len() != labels.len() { return None; } Some(Record { filename: filename.to_string(), tokens, labels, template_id: template_id.to_string(), template: key, source_filename: None, path_trimmed: None, dropped_title_candidate_positions: if dropped.is_empty() { None } else { Some(dropped) }, })}
#[cfg(test)]mod tests { use super::*;
fn labels_for(filename: &str) -> Vec<(String, String)> { let (key, _, _, _) = template_key_for_filename(filename); let roles = suggested_roles(&key); let record = dmhy_record(filename, "tpl_test", &roles).unwrap(); record.tokens.into_iter().zip(record.labels).collect() }
#[test] fn required_regressions() { let title_91 = labels_for("Title 91 EP 01 [1080p]"); assert!(title_91.contains(&("91".to_string(), "B-TITLE".to_string()))); assert!(title_91.contains(&("EP".to_string(), "O".to_string()))); assert!(title_91.contains(&("01".to_string(), "B-EPISODE".to_string())));
let event = labels_for("[HYSUB]Dragon Ball Super Broly[Theater Greeting Event][1080P]"); assert!(event.contains(&("Theater".to_string(), "B-SPECIAL".to_string()))); assert!(!event.contains(&("Theater".to_string(), "B-TITLE".to_string())));
let roman = labels_for("Chibi Maruko-chan I 001"); assert!(roman.contains(&("I".to_string(), "B-SEASON".to_string()))); assert!(roman.contains(&("001".to_string(), "B-EPISODE".to_string())));
let dxd = labels_for("High School D×D"); assert!(dxd.contains(&("×".to_string(), "B-TITLE".to_string())));
let sxe = labels_for("S01E02"); assert_eq!( sxe, vec![ ("S".to_string(), "O".to_string()), ("01".to_string(), "B-SEASON".to_string()), ("E".to_string(), "O".to_string()), ("02".to_string(), "B-EPISODE".to_string()) ] );
let sky = labels_for("[Skytree][海贼王][One_Piece][918][GB_JP][1080P]"); assert!(sky.contains(&("One".to_string(), "B-TITLE".to_string()))); assert!(!sky.contains(&("海贼王".to_string(), "B-TITLE".to_string()))); assert!(sky.contains(&("918".to_string(), "B-EPISODE".to_string()))); }
#[test] fn updated_python_alignment_regressions() { let original = "The New Woody Woodpecker Show (Season 1-4) (1999-2002) WEB-DL 720p [Hurtom]/Season 4/E07 - The New Woody Woodpecker Show (Season 1-4) (1999-2002) WEB-DL 720p"; let (trimmed, was_trimmed) = training_filename_for(original); assert!(was_trimmed); assert_eq!( trimmed, "Season 4/E07 - The New Woody Woodpecker Show (Season 1-4) (1999-2002) WEB-DL 720p" ); let woody = labels_for(&trimmed); assert!(woody.contains(&("4".to_string(), "B-SEASON".to_string()))); assert!(woody.contains(&("E07".to_string(), "B-EPISODE".to_string()))); assert!(woody.contains(&("The".to_string(), "B-TITLE".to_string()))); assert!(woody.contains(&("Show".to_string(), "B-TITLE".to_string()))); assert!(!woody.contains(&("1999".to_string(), "B-EPISODE".to_string())));
let group = labels_for("[DBD-Raws][Title][01][1080P]"); assert!(group.contains(&("-".to_string(), "B-GROUP".to_string()))); let amp_group = labels_for("[SumiSora&CASO][Title][01][1080P]"); assert!(amp_group.contains(&("&".to_string(), "B-GROUP".to_string())));
let cjk_season = labels_for("[DBD-Raws][魔道祖师 第一季][08][1080P][BDRip][HEVC-10bit][FLAC]"); assert!(cjk_season.contains(&("魔道祖师".to_string(), "B-TITLE".to_string()))); assert!(cjk_season.contains(&("第一季".to_string(), "B-SEASON".to_string()))); assert!(!cjk_season.contains(&("第一季".to_string(), "B-TITLE".to_string()))); }}tools/rust_dmhy_template_apply/.gitignoreAdded+1
tools/rust_dmhy_template_apply/Cargo.lockAdded+911
tools/rust_dmhy_template_apply/Cargo.tomlAdded+17
tools/rust_dmhy_template_apply/README.mdAdded+30
tools/rust_dmhy_template_apply/src/main.rsAdded+1490