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
Organize parser modules and tools
Browse filesFiles changed (41)
- AGENTS.md+27-27
- README.md+18-24
- anifilebert/__init__.pyAdded+2
- config.py → anifilebert/config.pyRenamed+1
- dataset.py → anifilebert/dataset.pyRenamed+4-4
- inference.py → anifilebert/inference.pyRenamed+6-5
- label_repairs.py → anifilebert/label_repairs.pyRenamed+1
- model.py → anifilebert/model.pyRenamed+2-1
- tokenizer.py → anifilebert/tokenizer.pyRenamed+1
- train.py → anifilebert/train.pyRenamed+7-6
- colab/README.md+5-4
- colab/start_worker.ipynb+1-1
- ANDROID.md → docs/android.mdRenamed+7-6
- MAINTENANCE.md → docs/maintenance.mdRenamed+26-15
- docs/onnx.md+9-8
- docs/training.md+21-19
- benchmark_results.json → reports/benchmark_results.jsonRenamed+1-1
- case_metrics.json → reports/case_metrics.jsonRenamed
- parse_eval_metrics.json → reports/parse_eval_metrics.jsonRenamed
- run_metadata.json → reports/run_metadata.jsonRenamed
- trainer_eval_metrics.json → reports/trainer_eval_metrics.jsonRenamed
- training_lineage.json → reports/training_lineage.jsonRenamed
- tools/__init__.pyAdded+2
- benchmark_inference.py → tools/benchmark_inference.pyRenamed+13-10
- build_repair_focus_dataset.py → tools/build_repair_focus_dataset.pyRenamed+2-1
- colab_client.py → tools/colab_client.pyRenamed+3-2
- colab_train.py → tools/colab_train.pyRenamed+7-4
- colab_worker.py → tools/colab_worker.pyRenamed+3-2
- convert_to_char_dataset.py → tools/convert_to_char_dataset.pyRenamed+1
- data_generator.py → tools/data_generator.pyRenamed+3-2
- diagnose_pipeline.py → tools/diagnose_pipeline.pyRenamed+5-4
- dmhy_dataset.py → tools/dmhy_dataset.pyRenamed+4-3
- evaluate_parser_cases.py → tools/evaluate_parser_cases.pyRenamed+9-8
- export_onnx.py → tools/export_onnx.pyRenamed+2-1
- llm_labeler.py → tools/llm_labeler.pyRenamed+5-4
- mix_datasets.py → tools/mix_datasets.pyRenamed+1
- onnx_inference.py → tools/onnx_inference.pyRenamed+5-4
- relabel_dataset_from_filenames.py → tools/relabel_dataset_from_filenames.pyRenamed+4-3
- repair_dataset_labels.py → tools/repair_dataset_labels.pyRenamed+2-1
- semantic_labeler.py → tools/semantic_labeler.pyRenamed+1
- test_train_small.py → tools/test_train_small.pyRenamed+23-17
7 unmodified lines891011121314151112131415161721 unmodified lines3940414342434445464749484950515253555455565758596160616263646567666768694 unmodified lines74757678777879805 unmodified lines86878890899091922 unmodified lines9596979998991001011021031051041051061071081091111101111121131141151171181191201211161171181191201211221234 unmodified lines12812913013213113213413313413513713813613713814014113914014114214315 unmodified lines1591601611631621631641659 unmodified lines1751761771787 unmodified lines- Root model artifacts (`config.json`, `model.safetensors`, `vocab.json`, `tokenizer_config.json`, `training_args.bin`) are the published default checkpoint.- Core code lives in `train.py`, `dataset.py`, `tokenizer.py`, `model.py`, `inference.py`, and `export_onnx.py`.- Dataset generation and labeling helpers live in `data_generator.py`, `dmhy_dataset.py`, `mix_datasets.py`, `llm_labeler.py`, `semantic_labeler.py`, and `convert_to_char_dataset.py`.- Core parser/training code lives in `anifilebert/`.- Command-line tools live in `tools/`, including ONNX export, fixed-case evaluation, benchmarks, dataset relabeling, dataset generation, and Colab helpers.- `datasets/AnimeName` is a nested dataset submodule and should be treated as the authoritative dataset snapshot when present. Use either `dmhy_weak.jsonl` for the regex tokenizer or `dmhy_weak_char.jsonl` for the21 unmodified linesRun a parser smoke check:
```bashuv run python inference.py --model-dir . "Witch.Hat.Atelier.S01E07.1080p.NF.WEB-DL.JPN.AAC2.0.H.264.MSubs-ToonsHub"uv run python -m anifilebert.inference --model-dir . "Witch.Hat.Atelier.S01E07.1080p.NF.WEB-DL.JPN.AAC2.0.H.264.MSubs-ToonsHub"```
Run fixed real-world parser regression:
```bashuv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output case_metrics.jsonuv run python -m tools.evaluate_parser_cases --model-dir . --case-file data/parser_regression_cases.json --output reports/case_metrics.json```
Benchmark PyTorch and ONNX Runtime inference:
```bashuv run python benchmark_inference.py --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output benchmark_results.jsonuv run python -m tools.benchmark_inference --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output reports/benchmark_results.json```
Train the current default character tokenizer:
```bashuv run python train.py --tokenizer char --data-file datasets/AnimeName/dmhy_weak_char.jsonl --vocab-file datasets/AnimeName/vocab.char.json --save-dir checkpoints/dmhy-char-full --init-model-dir . --epochs 2 --batch-size 256 --learning-rate 0.00008 --warmup-steps 300 --max-seq-length 128 --train-split 0.98 --num-workers 4 --checkpoint-steps 1000 --save-total-limit 3 --parse-eval-limit 2048 --case-eval-file data/parser_regression_cases.json --seed 52 --experiment-name dmhy-char-fulluv run python -m anifilebert.train --tokenizer char --data-file datasets/AnimeName/dmhy_weak_char.jsonl --vocab-file datasets/AnimeName/vocab.char.json --save-dir checkpoints/dmhy-char-full --init-model-dir . --epochs 2 --batch-size 256 --learning-rate 0.00008 --warmup-steps 300 --max-seq-length 128 --train-split 0.98 --num-workers 4 --checkpoint-steps 1000 --save-total-limit 3 --parse-eval-limit 2048 --case-eval-file data/parser_regression_cases.json --seed 52 --experiment-name dmhy-char-full```
Export for Android:
```bashuv run python export_onnx.py --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parseruv run python -m tools.export_onnx --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parser```
## Codex-Controlled Colab Training4 unmodified lines
Before relying on the Colab flow, make sure the Colab helper files have beenpushed to the Hugging Face model repo, or the user has uploaded them manually:`colab_worker.py`, `colab_client.py`, `colab_train.py`, and `colab/`.`tools/colab_worker.py`, `tools/colab_client.py`, `tools/colab_train.py`, and `colab/`.
Ask the user to start a Colab GPU runtime with:
5 unmodified lines%cd /content/AniFileBERT!git pull --ff-only || true!git submodule update --init --recursive!python colab_worker.py!python -m tools.colab_worker```
The worker prints `COLAB_WORKER_URL=...` and `COLAB_WORKER_TOKEN=...`. After2 unmodified lines```powershell$env:ANIFILEBERT_COLAB_URL="https://...trycloudflare.com"$env:ANIFILEBERT_COLAB_TOKEN="..."python colab_client.py healthpython -m tools.colab_client health```
Submit the default regex fine-tune:
```powershellpython colab_client.py submit --profile dmhy_regex_finetune --waitpython -m tools.colab_client submit --profile dmhy_regex_finetune --wait```
Submit the character tokenizer run only when intentional:
```powershellpython colab_client.py submit --profile dmhy_char_train --waitpython -m tools.colab_client submit --profile dmhy_char_train --wait```
Useful follow-up commands:
```powershellpython colab_client.py jobspython colab_client.py status <job-id>python colab_client.py logs <job-id> --tail 200python colab_client.py manifest <job-id>python colab_client.py cancel <job-id>python -m tools.colab_client jobspython -m tools.colab_client status <job-id>python -m tools.colab_client logs <job-id> --tail 200python -m tools.colab_client manifest <job-id>python -m tools.colab_client cancel <job-id>```
The default Colab profiles save checkpoints to Google Drive every 1000 steps4 unmodified lines
## Validation Expectations
- For parser or tokenizer changes, run `python inference.py --model-dir . ...`- For parser or tokenizer changes, run `python -m anifilebert.inference --model-dir . ...` with at least one realistic filename.- Run `uv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output case_metrics.json`- Run `uv run python -m tools.evaluate_parser_cases --model-dir . --case-file data/parser_regression_cases.json --output reports/case_metrics.json` before publishing parser changes.- For dataset alignment, tokenizer, model, or training-loop changes, run `python test_train_small.py --limit-samples 5000 --epochs 2` when practical.- For export changes, run `python export_onnx.py ...` and confirm the exporter `python -m tools.test_train_small --limit-samples 5000 --epochs 2` when practical.- For export changes, run `python -m tools.export_onnx ...` and confirm the exporter reports a small PyTorch/ONNX logits difference.- For performance-sensitive inference changes, run `uv run python benchmark_inference.py ...` and update `benchmark_results.json` plus the README performance table.- For performance-sensitive inference changes, run `uv run python -m tools.benchmark_inference ...` and update `reports/benchmark_results.json` plus the README performance table.- Full training is expensive; do not start long multi-epoch runs unless the task explicitly requires it.
15 unmodified lines Preserve LFS handling for `.safetensors`, `.onnx`, `.bin`, and related model files.- When publishing a new checkpoint, copy the final checkpoint files to the repository root as described in `MAINTENANCE.md`. repository root and reports as described in `docs/maintenance.md`.- When updating `datasets/AnimeName`, commit the submodule pointer in this repo and then update the parent MiruPlay submodule pointer.- Push LFS objects before pushing Git commits when model or ONNX artifacts9 unmodified lines- Prefer deterministic dataset and training changes. Keep seed handling intact.- Use UTF-8 for files that contain Japanese, Chinese, or release-name examples.- Keep command examples Windows-friendly where paths reference MiruPlay.
44 unmodified lines45464748484950512 unmodified lines545556575758596030 unmodified lines919293949495969710 unmodified lines1081091101111111121131131141151166 unmodified lines1231241251261261271281292 unmodified lines1321331341351351361371389 unmodified lines1481491501511511521531531541551561571581581591601613 unmodified lines16516616716816816917017119 unmodified lines19119219319419419519619713 unmodified lines21121221321421421521621735 unmodified lines2532542552562572582592602612622632642652562572582592602612622632642652662742672682692708 unmodified lines27928028128244 unmodified lines| Item | Value || --- | --- || Architecture / 架构 | `BertForTokenClassification` || Tokenizer / 分词器 | Custom character tokenizer in `tokenizer.py` || Tokenizer / 分词器 | Custom character tokenizer in `anifilebert/tokenizer.py` || Parameters / 参数量 | 4,783,631 || Hidden size / 隐层维度 | 256 || Layers / 层数 | 4 |2 unmodified lines| Labels / 标签 | BIO labels for `TITLE`, `SEASON`, `EPISODE`, `GROUP`, `RESOLUTION`, `SOURCE`, `SPECIAL` || Default checkpoint / 默认权重 | Repository root files (`config.json`, `model.safetensors`, `vocab.json`, `tokenizer_config.json`) || ONNX export / ONNX 导出 | `exports/anime_filename_parser.onnx` || Training lineage / 训练链路 | `training_lineage.json` || Training lineage / 训练链路 | `reports/training_lineage.json` |
**中文**:根目录就是发布 checkpoint,不再保留旧的 `model/` 重复副本。默认解析路径是“模型 logits + 约束 BIO + 薄字段规范化”,不再默认启用重结构规则;直接 `from_pretrained()` 只能加载 token-classification 权重。
30 unmodified linesRun the Python parser:
```powershelluv run python inference.py --model-dir . "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python -m anifilebert.inference --model-dir . "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"```
Expected output:10 unmodified linesmodel = BertForTokenClassification.from_pretrained("ModerRAS/AniFileBERT")```
**中文**:如果需要完整字段解析,请 clone 本仓库并使用 `inference.py`,因为分词器和后处理是自定义的。**中文**:如果需要完整字段解析,请 clone 本仓库并使用 `python -m anifilebert.inference`,因为分词器和后处理是自定义的。
**English**: For complete field parsing, clone this repo and use `inference.py`; the tokenizer and postprocessing are custom.**English**: For complete field parsing, clone this repo and use `python -m anifilebert.inference`; the tokenizer and postprocessing are custom.
## ONNX Usage / ONNX 使用
6 unmodified lines本仓库提供最小可运行示例:
```powershelluv run python onnx_inference.py "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"uv run python -m tools.onnx_inference "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"```
Static graph shapes:2 unmodified lines- `attention_mask`: `int64[1,128]`- `logits`: `float32[1,128,15]`
More details: [`docs/onnx.md`](docs/onnx.md) and [`ANDROID.md`](ANDROID.md).More details: [`docs/onnx.md`](docs/onnx.md) and [`docs/android.md`](docs/android.md).
## Evaluation / 评估
9 unmodified lines| ONNX parity / ONNX 误差 | max abs diff `4.0531e-05` || CPU thin-runtime latency / CPU 薄层运行时延迟 | ONNX avg `13.18 ms`, P95 `16.70 ms` |
**中文**:当前发布模型是“两阶段训练”产物:先在 `datasets/AnimeName/dmhy_weak_char.jsonl` 上全量 CUDA 重训,再做 thin hard-case focus 微调。细节见 `training_lineage.json`。README 主指标以 `model-only` 和默认薄层 `normalized-only` 为准;旧版结构规则辅助层已移除,不再作为运行时或质量对照。**中文**:当前发布模型是“两阶段训练”产物:先在 `datasets/AnimeName/dmhy_weak_char.jsonl` 上全量 CUDA 重训,再做 thin hard-case focus 微调。细节见 `reports/training_lineage.json`。README 主指标以 `model-only` 和默认薄层 `normalized-only` 为准;旧版结构规则辅助层已移除,不再作为运行时或质量对照。
**English**: The published checkpoint was trained in two stages: a full CUDA fine-tune on `datasets/AnimeName/dmhy_weak_char.jsonl`, followed by a thin hard-case focus fine-tune. See `training_lineage.json` for details. README quality numbers prioritize `model-only` and the default thin `normalized-only` runtime; structural filename assists have been removed from the runtime and quality reports.**English**: The published checkpoint was trained in two stages: a full CUDA fine-tune on `datasets/AnimeName/dmhy_weak_char.jsonl`, followed by a thin hard-case focus fine-tune. See `reports/training_lineage.json` for details. README quality numbers prioritize `model-only` and the default thin `normalized-only` runtime; structural filename assists have been removed from the runtime and quality reports.
Run regression:
```powershelluv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output case_metrics.jsonuv run python -m tools.evaluate_parser_cases --model-dir . --case-file data/parser_regression_cases.json --output reports/case_metrics.json```
## Performance / 性能3 unmodified lines性能测试命令:
```powershelluv run python benchmark_inference.py --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output benchmark_results.jsonuv run python -m tools.benchmark_inference --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output reports/benchmark_results.json```
Local CPU benchmark on the 26 fixed real-world cases, single-threaded, using the19 unmodified linesRecommended full character-token run:
```powershelluv run python train.py --tokenizer char `uv run python -m anifilebert.train --tokenizer char ` --data-file datasets/AnimeName/dmhy_weak_char.jsonl ` --vocab-file datasets/AnimeName/vocab.char.json ` --save-dir checkpoints/dmhy-char-full `13 unmodified lines --experiment-name dmhy-char-full```
`train.py` writes:`python -m anifilebert.train` writes:
- Hugging Face checkpoints under `--save-dir`,- `final/run_metadata.json`,35 unmodified linestokenizer_config.jsonvocab.jsontraining_args.bininference.pyonnx_inference.pyexport_onnx.pytrain.pydataset.pytokenizer.pydmhy_dataset.pylabel_repairs.pyrelabel_dataset_from_filenames.pyconvert_to_char_dataset.pyanifilebert/tools/data/parser_regression_cases.jsondatasets/AnimeName/exports/anime_filename_parser.onnxdocs/reports/```
## Maintenance / 维护
See [`MAINTENANCE.md`](MAINTENANCE.md) for release steps, LFS order, dataset submodule updates, and MiruPlay integration notes.See [`docs/maintenance.md`](docs/maintenance.md) for release steps, LFS order, dataset submodule updates, and MiruPlay integration notes.
## Limitations / 局限
8 unmodified lines- Anime release names are not standardized; extreme OCR noise, mojibake, or non-anime names can still fail.- ONNX contains logits only. Mobile runtimes must keep tokenizer, vocabulary, config, BIO decode, and thin normalization in sync.- `source` is currently a single field, while real filenames may contain platform, release source, codec, and language tags together.
12"""AniFileBERT parser package."""
71 unmodified lines7273747571 unmodified lines @property def num_labels(self) -> int: return len(self.label2id)
10 unmodified lines111213141516141516171819312 unmodified lines33233333433533533633717 unmodified lines35535635735810 unmodified linesfrom torch.utils.data import Datasetfrom typing import Dict, List, Optional, Tuple
from config import Configfrom label_repairs import repair_sequel_season_labelsfrom tokenizer import AnimeTokenizerfrom .config import Configfrom .label_repairs import repair_sequel_season_labelsfrom .tokenizer import AnimeTokenizer
class AnimeDataset(Dataset):312 unmodified lines
if __name__ == "__main__": # Quick test from config import Config cfg = Config()
tok = AnimeTokenizer()17 unmodified lines print(f"input_ids: {sample['input_ids'].tolist()}") print(f"labels: {sample['labels'].tolist()}") print(f"attention_mask: {sample['attention_mask'].tolist()}")
4 unmodified lines56789891011125 unmodified lines181920212223212223242526492 unmodified lines5195205215224 unmodified linesand outputs structured metadata.
Usage: python inference.py "[ANi] 葬送的芙莉莲 S2 - 03 [1080P][WEB-DL]" python inference.py --input-file filenames.txt --output-file results.jsonl python -m anifilebert.inference "[ANi] 葬送的芙莉莲 S2 - 03 [1080P][WEB-DL]" python -m anifilebert.inference --input-file filenames.txt --output-file results.jsonl"""
import argparse5 unmodified linesimport torchfrom transformers import BertForTokenClassification
from config import Configfrom label_repairs import season_marker_numberfrom tokenizer import AnimeTokenizer, load_tokenizerfrom .config import Configfrom .label_repairs import season_marker_numberfrom .tokenizer import AnimeTokenizer, load_tokenizer
# Chinese number mapping492 unmodified lines
if __name__ == "__main__": main()
514 unmodified lines515516517518514 unmodified lines normalized.append(f"{prefix}-{entity}") previous_entity = entity return normalized
3 unmodified lines45677891046 unmodified lines575859603 unmodified lines"""
from transformers import BertConfig, BertForTokenClassificationfrom config import Configfrom .config import Config
def create_model(config: Config) -> BertForTokenClassification:46 unmodified lines cfg.vocab_size = 3000 model = create_model(cfg) print_model_summary(model)
407 unmodified lines408409410411407 unmodified lines print(f"Input: {case}") print(f"Tokens: {toks}") print()
24 unmodified lines25262728293031322829303132333435623 unmodified lines65966066166266266366466520 unmodified lines68668768868924 unmodified lines)from seqeval.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score
from config import Configfrom tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerfrom model import create_model, print_model_summary, count_parametersfrom dataset import AnimeDataset, labels_for_tokenizerfrom inference import parse_filename, postprocessfrom .config import Configfrom .tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerfrom .model import create_model, print_model_summary, count_parametersfrom .dataset import AnimeDataset, labels_for_tokenizerfrom .inference import parse_filename, postprocess
def compute_metrics(p):623 unmodified lines
if not args.no_case_eval: if args.case_eval_file and os.path.isfile(args.case_eval_file): from evaluate_parser_cases import evaluate_case_modes from tools.evaluate_parser_cases import evaluate_case_modes
case_metrics = evaluate_case_modes( model_dir=final_save_path,20 unmodified lines
if __name__ == "__main__": main()
19 unmodified lines202122232324252614 unmodified lines414243444544454647489 unmodified lines58596061616263648 unmodified lines7374757619 unmodified lines%cd /content/AniFileBERT!git pull --ff-only || true!git submodule update --init --recursive!python colab_worker.py!python -m tools.colab_worker```
The cell prints:14 unmodified lines```powershell$env:ANIFILEBERT_COLAB_URL="https://...trycloudflare.com"$env:ANIFILEBERT_COLAB_TOKEN="..."python colab_client.py healthpython colab_client.py submit --profile dmhy_regex_finetune --waitpython -m tools.colab_client healthpython -m tools.colab_client submit --profile dmhy_regex_finetune --wait```
Codex can run the same commands from this repository after you provide the URL9 unmodified linesYou can submit a local edited profile instead of a remote profile:
```powershellpython colab_client.py submit --config colab/configs/dmhy_regex_finetune.json --waitpython -m tools.colab_client submit --config colab/configs/dmhy_regex_finetune.json --wait```
The worker writes per-job logs under:8 unmodified linesMyDrive/AniFileBERT/checkpoints/<profile-name>/MyDrive/AniFileBERT/last_run_manifest.json```
37 unmodified lines383940414142434437 unmodified lines "%cd /content/AniFileBERT\n", "!git pull --ff-only || true\n", "!git submodule update --init --recursive\n", "!python colab_worker.py\n" "!python -m tools.colab_worker\n" ] } ]11 unmodified lines121314151516171823 unmodified lines42434445454647485 unmodified lines545556575758596013 unmodified lines747576777778798028 unmodified lines10911011111211211311411511411 unmodified lines
```powershelluv syncuv run python export_onnx.py --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parseruv run python -m tools.export_onnx --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parser```
The exporter writes:23 unmodified lines## Local ONNX Smoke Test / 本地 ONNX 冒烟测试
```powershelluv run python onnx_inference.py "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"```
Expected fields / 期望字段:5 unmodified linesSpecial-code example / 特典编号示例:
```powershelluv run python onnx_inference.py "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"uv run python -m tools.onnx_inference "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"```
Expected fields / 期望字段:13 unmodified lines- fixed-length padding to 128 / padding 到固定长度 128- constrained BIO decoding / 约束 BIO 解码- field aggregation / 字段聚合- high-confidence structural cleanup / 高置信结构修正- thin string/number normalization / 轻量字符串和数字规范化
The Android runtime implementation lives in MiruPlay:
28 unmodified lines
## More Details / 更多说明
See [`docs/onnx.md`](docs/onnx.md) for a minimal Python ONNX Runtime reference.See [`onnx.md`](onnx.md) for a minimal Python ONNX Runtime reference.
最小 Python ONNX Runtime 参考见 [`onnx.md`](onnx.md)。
最小 Python ONNX Runtime 参考见 [`docs/onnx.md`](docs/onnx.md)。45 unmodified lines46474849505152535455495051525657585960616263643 unmodified lines686970627172647374757677697879808126 unmodified lines10810911010210310410511111211311411511611711811912012111212212312412512612711811912012812913013113213369 unmodified lines20320420520645 unmodified linestraining_args.binvocab.jsonvocab.char.json```
Release reports are kept under `reports/`:
发布报告保存在 `reports/`:
```textrun_metadata.jsontrainer_eval_metrics.jsonparse_eval_metrics.jsoncase_metrics.jsonreports/run_metadata.jsonreports/trainer_eval_metrics.jsonreports/parse_eval_metrics.jsonreports/case_metrics.jsonreports/benchmark_results.jsonreports/training_lineage.json```
There is no tracked `model/` duplicate. Ignored `checkpoints/` directories are3 unmodified lines
## Standard Training / 标准训练
For full details, see [`docs/training.md`](docs/training.md).For full details, see [`training.md`](training.md).
完整流程见 [`docs/training.md`](docs/training.md)。完整流程见 [`training.md`](training.md)。
Recommended full training command / 推荐全量训练命令:
```powershelluv run python train.py --tokenizer char `uv run python -m anifilebert.train --tokenizer char ` --data-file datasets/AnimeName/dmhy_weak_char.jsonl ` --vocab-file datasets/AnimeName/vocab.char.json ` --save-dir checkpoints/dmhy-char-full `26 unmodified linesCopy-Item "$final/tokenizer_config.json" . -ForceCopy-Item "$final/training_args.bin" . -ForceCopy-Item "$final/vocab.json" . -ForceCopy-Item "$final/run_metadata.json" . -ForceCopy-Item "$final/trainer_eval_metrics.json" . -ForceCopy-Item "$final/parse_eval_metrics.json" . -ForceCopy-Item "$final/case_metrics.json" . -ForceNew-Item -ItemType Directory -Path reports -Force | Out-NullCopy-Item "$final/run_metadata.json" reports/run_metadata.json -ForceCopy-Item "$final/trainer_eval_metrics.json" reports/trainer_eval_metrics.json -ForceCopy-Item "$final/parse_eval_metrics.json" reports/parse_eval_metrics.json -ForceCopy-Item "$final/case_metrics.json" reports/case_metrics.json -ForceCopy-Item datasets/AnimeName/vocab.char.json .\vocab.char.json -Force```
Export ONNX / 导出 ONNX:
```powershelluv run python export_onnx.py --model-dir . --output exports/anime_filename_parser.onnx --max-length 128uv run python -m tools.export_onnx --model-dir . --output exports/anime_filename_parser.onnx --max-length 128```
Validate / 验证:
```powershelluv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output case_metrics.jsonuv run python onnx_inference.py "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python benchmark_inference.py --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output benchmark_results.jsonuv run python -m tools.evaluate_parser_cases --model-dir . --case-file data/parser_regression_cases.json --output reports/case_metrics.jsonuv run python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python -m tools.benchmark_inference --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output reports/benchmark_results.json```
The default parser path is thin runtime: model logits, constrained BIO, entity69 unmodified linesscraper/src/main/assets/anime_parser/config.jsonscraper/src/main/assets/anime_parser/vocab.json```
25 unmodified lines2627282929303132323334353637383839404111 unmodified lines5354555656575858596061616263649 unmodified lines747576777778798084 unmodified lines16516616716816816917017112 unmodified lines18418518618725 unmodified lines- field aggregation / 字段聚合- thin string and number normalization / 薄字符串和数字规范化
Those steps must stay aligned with `tokenizer.py`, `inference.py`, `config.json`,Those steps must stay aligned with `anifilebert/tokenizer.py`, `anifilebert/inference.py`, `config.json`,and `vocab.json`.
这些步骤必须与 `tokenizer.py`、`inference.py`、`config.json`、`vocab.json`这些步骤必须与 `anifilebert/tokenizer.py`、`anifilebert/inference.py`、`config.json`、`vocab.json`保持一致。
## 2. Export / 导出
```powershelluv run python export_onnx.py --model-dir . --output exports/anime_filename_parser.onnx --max-length 128uv run python -m tools.export_onnx --model-dir . --output exports/anime_filename_parser.onnx --max-length 128```
The exporter also writes:11 unmodified lines
## 3. Local ONNX Inference / 本地 ONNX 推理
Use `onnx_inference.py` as the minimal runnable reference.Use `python -m tools.onnx_inference` as the minimal runnable reference.
使用 `onnx_inference.py` 作为最小可运行参考实现。使用 `python -m tools.onnx_inference` 作为最小可运行参考实现。
```powershelluv run python onnx_inference.py "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"```
Expected:9 unmodified lines特典编号示例:
```powershelluv run python onnx_inference.py "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"uv run python -m tools.onnx_inference "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"```
Expected:84 unmodified lines运行:
```powershelluv run python benchmark_inference.py --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output benchmark_results.jsonuv run python -m tools.benchmark_inference --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output reports/benchmark_results.json```
Local single-thread CPU result, measured on 26 real-world regression cases with12 unmodified lines
该基准包含 tokenizer、模型/session 前向、约束 BIO 解码、实体聚合和薄层规范化;循环内不会重复创建 ONNX Runtime session。
47 unmodified lines48495051515253535455565657585920 unmodified lines80818283838485868 unmodified lines95969798989910010135 unmodified lines1371381391401401411421431 unmodified line14514614714814814915015140 unmodified lines1921931941951961971981951961971981992002012022 unmodified lines2052062072072082092102113 unmodified lines21521621721721821922022121821922022122222322422514 unmodified lines24024124224224324424524524624724824925025147 unmodified lines
## 3. Relabel Full Dataset / 全量重标注
Use this when weak-label rules changed in `dmhy_dataset.py` or `label_repairs.py`.Use this when weak-label rules changed in `tools/dmhy_dataset.py` or `anifilebert/label_repairs.py`.
当 `dmhy_dataset.py` 或 `label_repairs.py` 的弱标注规则改变时,使用此流程。当 `tools/dmhy_dataset.py` 或 `anifilebert/label_repairs.py` 的弱标注规则改变时,使用此流程。
```powershelluv run python relabel_dataset_from_filenames.py `uv run python -m tools.relabel_dataset_from_filenames ` --input datasets/AnimeName/dmhy_weak.jsonl ` --output datasets/AnimeName/dmhy_weak.relabel.jsonl ` --manifest-output datasets/AnimeName/dmhy_weak.relabel.manifest.json `20 unmodified lines当前发布模型使用字符级 tokenizer。
```powershelluv run python convert_to_char_dataset.py `uv run python -m tools.convert_to_char_dataset ` --input datasets/AnimeName/dmhy_weak.jsonl ` --output datasets/AnimeName/dmhy_weak_char.jsonl ` --vocab-output datasets/AnimeName/vocab.char.json `8 unmodified lines推荐 RTX 3080 训练命令:
```powershelluv run python train.py --tokenizer char `uv run python -m anifilebert.train --tokenizer char ` --data-file datasets/AnimeName/dmhy_weak_char.jsonl ` --vocab-file datasets/AnimeName/vocab.char.json ` --save-dir checkpoints/dmhy-char-full `35 unmodified lines`data/parser_regression_cases.json` 后,才使用困难样本微调。
```powershelluv run python build_repair_focus_dataset.py `uv run python -m tools.build_repair_focus_dataset ` --input datasets/AnimeName/dmhy_weak_char.jsonl ` --output data/thin_hard_focus_char.jsonl ` --context-samples 30000 `1 unmodified line --repeat-manual 240 ` --seed 57
uv run python train.py --tokenizer char `uv run python -m anifilebert.train --tokenizer char ` --data-file data/thin_hard_focus_char.jsonl ` --vocab-file datasets/AnimeName/vocab.char.json ` --save-dir checkpoints/dmhy-char-thin-hardfocus `40 unmodified linesCopy-Item "$final/tokenizer_config.json" . -ForceCopy-Item "$final/training_args.bin" . -ForceCopy-Item "$final/vocab.json" . -ForceCopy-Item "$final/run_metadata.json" . -ForceCopy-Item "$final/trainer_eval_metrics.json" . -ForceCopy-Item "$final/parse_eval_metrics.json" . -ForceCopy-Item "$final/case_metrics.json" . -ForceNew-Item -ItemType Directory -Path reports -Force | Out-NullCopy-Item "$final/run_metadata.json" reports/run_metadata.json -ForceCopy-Item "$final/trainer_eval_metrics.json" reports/trainer_eval_metrics.json -ForceCopy-Item "$final/parse_eval_metrics.json" reports/parse_eval_metrics.json -ForceCopy-Item "$final/case_metrics.json" reports/case_metrics.json -ForceCopy-Item datasets/AnimeName/vocab.char.json .\vocab.char.json -Force```
2 unmodified lines然后导出 ONNX:
```powershelluv run python export_onnx.py --model-dir . --output exports/anime_filename_parser.onnx --max-length 128uv run python -m tools.export_onnx --model-dir . --output exports/anime_filename_parser.onnx --max-length 128```
## 8. Validation Checklist / 验证清单3 unmodified lines提交前执行:
```powershelluv run python -m py_compile tokenizer.py dataset.py dmhy_dataset.py label_repairs.py train.py inference.py export_onnx.py onnx_inference.pyuv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output case_metrics.jsonuv run python inference.py --model-dir . "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python onnx_inference.py "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"uv run python benchmark_inference.py --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output benchmark_results.jsonuv run python -m py_compile anifilebert/*.py tools/*.pyuv run python -m tools.evaluate_parser_cases --model-dir . --case-file data/parser_regression_cases.json --output reports/case_metrics.jsonuv run python -m anifilebert.inference --model-dir . "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"uv run python -m tools.onnx_inference "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"uv run python -m tools.benchmark_inference --model-dir . --onnx exports/anime_filename_parser.onnx --case-file data/parser_regression_cases.json --repeat 20 --warmup 20 --torch-threads 1 --ort-threads 1 --output reports/benchmark_results.json```
## 9. Git and LFS Order / Git 与 LFS 顺序14 unmodified lines再提交模型仓库:
```powershellgit add README.md MAINTENANCE.md ANDROID.md docs/training.md docs/onnx.md `git add README.md docs/maintenance.md docs/android.md docs/training.md docs/onnx.md ` config.json model.safetensors tokenizer_config.json training_args.bin vocab.json vocab.char.json ` exports/anime_filename_parser.onnx exports/anime_filename_parser.metadata.json ` train.py inference.py export_onnx.py onnx_inference.py data/parser_regression_cases.json datasets/AnimeName reports anifilebert tools data/parser_regression_cases.json datasets/AnimeNamegit commit -m "Update AniFileBERT model and documentation"git lfs push origin main --allgit push origin main```
33 unmodified lines343536373733 unmodified lines "throughput_fps": 75.88307247148819 } ]}}12"""Command-line tools for AniFileBERT maintenance."""
15 unmodified lines1617181920212223192021222324252627282968 unmodified lines98991009810110210310474 unmodified lines17918018117918018118218218318418518618718818915 unmodified linesimport onnxruntime as ortfrom transformers import BertForTokenClassification
from config import Configfrom evaluate_parser_cases import DEFAULT_CASE_FILE, load_casesfrom inference import parse_filenamefrom onnx_inference import OnnxFilenameParserfrom tokenizer import load_tokenizerfrom anifilebert.config import Configfrom tools.evaluate_parser_cases import DEFAULT_CASE_FILE, load_casesfrom anifilebert.inference import parse_filenamefrom tools.onnx_inference import OnnxFilenameParserfrom anifilebert.tokenizer import load_tokenizer
DEFAULT_OUTPUT_FILE = Path("reports") / "benchmark_results.json"
def percentile(values: List[float], pct: float) -> float:68 unmodified lines parser.add_argument("--torch-threads", type=int, default=1, help="torch intra-op thread count") parser.add_argument("--ort-threads", type=int, default=1, help="ONNX Runtime intra/inter-op thread count") parser.add_argument("--no-constrained-bio", action="store_true", help="Use greedy labels for PyTorch backend") parser.add_argument("--output", default=None, help="Optional JSON output path") parser.add_argument("--output", default=str(DEFAULT_OUTPUT_FILE), help="JSON output path") args = parser.parse_args()
filenames = load_case_filenames(args.case_file, args.limit_cases)74 unmodified lines f"{item['throughput_fps']:.1f} |" )
if args.output: output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") output_path = Path(args.output) output_path.parent.mkdir(parents=True, exist_ok=True) output_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
if __name__ == "__main__": main()
8 unmodified lines910111212131415322 unmodified lines3383393403418 unmodified linesfrom pathlib import Pathfrom typing import Iterable, List
from label_repairs import repair_jsonl_itemfrom anifilebert.label_repairs import repair_jsonl_item
SPECIAL_FOCUS_RE = re.compile( r"(?<![A-Za-z0-9])(?:NCOP|NCED|OP|ED|PV|CM|IV)\s*[_\-.]?\s*\d{0,4}"322 unmodified lines
if __name__ == "__main__": main()
131 unmodified lines13213313413513513613713813914014014114214338 unmodified lines182183184185131 unmodified lines submit = subparsers.add_parser("submit", help="Submit a training job") submit.add_argument("--config", help="Local JSON config to send to the worker") submit.add_argument("--profile", help="Remote profile name under colab/configs") submit.add_argument("--arg", dest="args", action="append", default=[], help="Extra arg for colab_train.py") submit.add_argument("--arg", dest="args", action="append", default=[], help="Extra arg for tools.colab_train") submit.add_argument("--wait", action="store_true", help="Poll until the job finishes") submit.add_argument("--poll", type=int, default=60, help="Polling interval in seconds") submit.add_argument("--tail", type=int, default=80, help="Log lines to show while waiting") submit.add_argument("extra_args", nargs=argparse.REMAINDER, help="Arguments after -- are passed to colab_train.py") help="Arguments after -- are passed to tools.colab_train")
status = subparsers.add_parser("status", help="Show job status") status.add_argument("job_id")38 unmodified lines
if __name__ == "__main__": main()
2 unmodified lines34566789359 unmodified lines36937037137237237337437535 unmodified lines41141241341441441541641741819 unmodified lines43843944044044144244344444597 unmodified lines5435445455462 unmodified lines
Typical Colab usage:
python colab_train.py --config colab/configs/dmhy_regex_finetune.json python -m tools.colab_train --config colab/configs/dmhy_regex_finetune.json
This script keeps the Colab side reproducible by putting run parameters in JSONprofiles. It can clone/update the repo, mount Drive, install dependencies,359 unmodified lines
def build_train_command(training: Mapping[str, Any]) -> list[str]: cmd = [sys.executable, "train.py"] cmd = [sys.executable, "-m", "anifilebert.train"] for key, flag in [ ("tokenizer", "--tokenizer"), ("data_file", "--data-file"),35 unmodified lines return cmd = [ sys.executable, "export_onnx.py", "-m", "tools.export_onnx", "--model-dir", os.path.join(config["training"]["save_dir"], "final"), "--output",19 unmodified lines return cmd = [ sys.executable, "inference.py", "-m", "anifilebert.inference", "--model-dir", os.path.join(config["training"]["save_dir"], "final"), smoke["sample"],97 unmodified lines
if __name__ == "__main__": main()
2 unmodified lines34566789117 unmodified lines127128129130130131132133310 unmodified lines4444454464472 unmodified lines
Start this inside a Colab runtime:
python colab_worker.py python -m tools.colab_worker
The worker exposes a token-protected local HTTP API and, by default, starts aCloudflare Quick Tunnel so Codex on your local machine can submit jobs.117 unmodified lines log_path = job_dir / "worker.log" config_path: Path | None = None
cmd = [sys.executable, "colab_train.py"] cmd = [sys.executable, "-m", "tools.colab_train"] config = self._job_config(payload) config.setdefault("artifacts", {}) config["artifacts"]["manifest"] = os.fspath(job_dir / "colab_run_manifest.json")310 unmodified lines
if __name__ == "__main__": main()
198 unmodified lines199200201202198 unmodified lines
if __name__ == "__main__": main()
13 unmodified lines14151617181718192021733 unmodified lines75575675775813 unmodified linesimport refrom typing import Dict, List, Optional, Tuple
from config import Configfrom tokenizer import AnimeTokenizer, create_tokenizerfrom anifilebert.config import Configfrom anifilebert.tokenizer import AnimeTokenizer, create_tokenizer
# ═══════════════════════════════════════════════════════════════733 unmodified lines json.dump(tokenizer.get_vocab(), f, ensure_ascii=False, indent=2) print(f"Tokenizer vocab saved to {vocab_path}") print(f"Vocab size: {tokenizer.vocab_size}")
25 unmodified lines2627282930313229303132333435802 unmodified lines83883984084125 unmodified linesfrom seqeval.metrics import classification_report, f1_score, precision_score, recall_scorefrom transformers import BertForTokenClassification
from config import Configfrom dataset import labels_for_tokenizerfrom inference import constrained_bio_decode, postprocessfrom tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerfrom anifilebert.config import Configfrom anifilebert.dataset import labels_for_tokenizerfrom anifilebert.inference import constrained_bio_decode, postprocessfrom anifilebert.tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizer
def iter_jsonl(path: Path, limit: Optional[int] = None) -> Iterable[dict]:802 unmodified lines
if __name__ == "__main__": main()
18 unmodified lines1920212223242223242526271229 unmodified lines125712581259126018 unmodified linesfrom pathlib import Pathfrom typing import Iterable, List, Optional, Sequence
from data_generator import LABEL_MAP, categorize_meta_tokenfrom label_repairs import season_marker_numberfrom tokenizer import AnimeTokenizerfrom tools.data_generator import LABEL_MAP, categorize_meta_tokenfrom anifilebert.label_repairs import season_marker_numberfrom anifilebert.tokenizer import AnimeTokenizer
VIDEO_EXTENSIONS = {1229 unmodified lines parsed_args = parse_args() random.seed(parsed_args.seed) export_dataset(parsed_args)
7 unmodified lines891011121311121314151617181920144 unmodified lines16516616716716816917017119 unmodified lines1911921931931941951961941951961971981992002017 unmodified linesimport torchfrom transformers import BertForTokenClassification
from config import Configfrom inference import parse_filenamefrom tokenizer import load_tokenizerfrom anifilebert.config import Configfrom anifilebert.inference import parse_filenamefrom anifilebert.tokenizer import load_tokenizer
DEFAULT_CASE_FILE = os.path.join("data", "parser_regression_cases.json")DEFAULT_OUTPUT_FILE = os.path.join("reports", "case_metrics.json")
def normalize_field_value(field: str, value) -> Optional[str]:144 unmodified lines parser.add_argument("--case-file", default=DEFAULT_CASE_FILE) parser.add_argument("--tokenizer", choices=["regex", "char"], default=None) parser.add_argument("--max-length", type=int, default=None) parser.add_argument("--output", default=None, help="Optional JSON output path") 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") args = parser.parse_args()19 unmodified lines ) print_metrics(args.mode, metrics)
if args.output: os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) with open(args.output, "w", encoding="utf-8") as f: json.dump(metrics, f, ensure_ascii=False, indent=2) os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) with open(args.output, "w", encoding="utf-8") as f: json.dump(metrics, f, ensure_ascii=False, indent=2)
if __name__ == "__main__": main()
18 unmodified lines1920212222232425115 unmodified lines14114214314418 unmodified linesimport torchfrom transformers import BertForTokenClassification
from tokenizer import AnimeTokenizer, load_tokenizerfrom anifilebert.tokenizer import AnimeTokenizer, load_tokenizer
if hasattr(sys.stdout, "reconfigure"):115 unmodified lines
if __name__ == "__main__": main()
6 unmodified lines789101112101112131415239 unmodified lines2552562572582582592602612622636 unmodified linesannotation, and writes JSONL.
Usage: python llm_labeler.py --max-files 100 # annotate 100 files python llm_labeler.py --min-id 689305 # resume from file ID python llm_labeler.py --batch-size 15 # 15 files per subagent call python -m tools.llm_labeler --max-files 100 # annotate 100 files python -m tools.llm_labeler --min-id 689305 # resume from file ID python -m tools.llm_labeler --batch-size 15 # 15 files per subagent call"""import argparseimport json239 unmodified lines print() print("NEXT: For each prompt file, invoke a subagent with the prompt,") print("validate the JSON output, and save to batch_NNNNN.jsonl.") print("Then run: python llm_labeler.py --merge") print("Then run: python -m tools.llm_labeler --merge") print()
if __name__ == "__main__": main()
67 unmodified lines6869707167 unmodified lines
if __name__ == "__main__": main()
2 unmodified lines3456678991011125 unmodified lines1819202122212223242597 unmodified lines1231241251262 unmodified lines
The ONNX file outputs token logits only. End-to-end parsing still needs therepository tokenizer, constrained BIO decoding, and the same field aggregationused by inference.py.used by anifilebert.inference.
Usage: python onnx_inference.py "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4" python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4""""
import argparse5 unmodified linesimport onnxruntime as ortimport torch
from inference import constrained_bio_decode, postprocessfrom tokenizer import AnimeTokenizer, load_tokenizerfrom anifilebert.inference import constrained_bio_decode, postprocessfrom anifilebert.tokenizer import AnimeTokenizer, load_tokenizer
def encode(97 unmodified lines
if __name__ == "__main__": main()
9 unmodified lines101112131415131415161718136 unmodified lines1551561571589 unmodified linesfrom statistics import meanfrom typing import Iterable
from dmhy_dataset import weak_label_filenamefrom label_repairs import repair_jsonl_itemfrom tokenizer import AnimeTokenizerfrom tools.dmhy_dataset import weak_label_filenamefrom anifilebert.label_repairs import repair_jsonl_itemfrom anifilebert.tokenizer import AnimeTokenizer
def parse_args() -> argparse.Namespace:136 unmodified lines
if __name__ == "__main__": main()
8 unmodified lines91011121213141585 unmodified lines1011021031048 unmodified linesfrom pathlib import Pathfrom typing import Dict, List
from label_repairs import LabelRepair, repair_jsonl_itemfrom anifilebert.label_repairs import LabelRepair, repair_jsonl_item
def parse_args() -> argparse.Namespace:85 unmodified lines
if __name__ == "__main__": main()
296 unmodified lines297298299300296 unmodified lines
if __name__ == "__main__": main()
8 unmodified lines91011121314151612131415161718192021222324253 unmodified lines2930313233343536373839404142304344453334464737484950514 unmodified lines5657584849505159606114 unmodified lines767778727980818227 unmodified lines1101111121061071081131141151161171181191208 unmodified lines Trainer, TrainingArguments, DataCollatorForTokenClassification)
from config import Configfrom tokenizer import create_tokenizerfrom model import create_model, count_parametersfrom dataset import AnimeDataset, align_tokens_for_tokenizerfrom train import compute_metricsfrom anifilebert.config import Configfrom anifilebert.tokenizer import create_tokenizerfrom anifilebert.model import create_model, count_parametersfrom anifilebert.dataset import AnimeDataset, align_tokens_for_tokenizerfrom anifilebert.train import compute_metrics
parser = argparse.ArgumentParser(description="Quick test: train a small A/B subset")parser.add_argument("--tokenizer", choices=["regex", "char"], default="regex")parser.add_argument("--data-file", default="data/synthetic_small.jsonl")parser.add_argument("--vocab-file", default=None)parser.add_argument("--output-dir", default=None)parser.add_argument("--limit-samples", type=int, default=5000)parser.add_argument("--epochs", type=float, default=2)parser.add_argument("--max-seq-length", type=int, default=None)3 unmodified linesif args_cli.max_seq_length is not None: cfg.max_seq_length = args_cli.max_seq_length
output_dir = args_cli.output_dir or os.path.join( tempfile.gettempdir(), f"anifilebert_test_checkpoints_{args_cli.tokenizer}",)os.makedirs(output_dir, exist_ok=True)
# Use first N sampleswith open(args_cli.data_file, 'r', encoding='utf-8') as f: all_data = [json.loads(line) for line in f][:args_cli.limit_samples]
# Load tokenizervocab_file = 'data/vocab.json' if args_cli.tokenizer == 'regex' else 'data/vocab.char.json'vocab_file = args_cli.vocab_file or os.path.join(output_dir, f"vocab.{args_cli.tokenizer}.json")tok = create_tokenizer(args_cli.tokenizer)if not os.path.isfile(vocab_file): with open('data/synthetic.jsonl', 'r', encoding='utf-8') as f: vocab_data = [json.loads(line) for line in f][:args_cli.limit_samples] tok.build_vocab([ align_tokens_for_tokenizer(item['tokens'], item['labels'], tok)[0] for item in vocab_data for item in all_data ]) with open(vocab_file, 'w', encoding='utf-8') as f: json.dump(tok.get_vocab(), f, ensure_ascii=False, indent=2)4 unmodified linesmodel = create_model(cfg)print(f'Model params: {count_parameters(model):,}')
# Use first N sampleswith open('data/synthetic.jsonl', 'r', encoding='utf-8') as f: all_data = [json.loads(line) for line in f][:args_cli.limit_samples]
split_idx = int(len(all_data) * cfg.train_split)train_data = all_data[:split_idx]eval_data = all_data[split_idx:]14 unmodified linesprint(f'Train: {len(train_ds)}, Eval: {len(eval_ds)}')
args = TrainingArguments( output_dir='./test_checkpoints' if args_cli.tokenizer == 'regex' else './test_checkpoints_char', output_dir=output_dir, num_train_epochs=args_cli.epochs, per_device_train_batch_size=64, per_device_eval_batch_size=64,27 unmodified lines print(f' {k}: {v:.4f}')
# Savesave_path = './test_checkpoints/final'if args_cli.tokenizer == 'char': save_path = './test_checkpoints_char/final'save_path = os.path.join(output_dir, 'final')trainer.save_model(save_path)model.config.tokenizer_variant = args_cli.tokenizermodel.config.max_seq_length = cfg.max_seq_lengthtok.save_pretrained(save_path)print(f'Saved to {save_path}')print('Training test PASSED!')
AGENTS.md+27-27
README.md+18-24
anifilebert/__init__.pyAdded+2
config.py → anifilebert/config.pyRenamed+1
dataset.py → anifilebert/dataset.pyRenamed+4-4
inference.py → anifilebert/inference.pyRenamed+6-5
label_repairs.py → anifilebert/label_repairs.pyRenamed+1
model.py → anifilebert/model.pyRenamed+2-1
tokenizer.py → anifilebert/tokenizer.pyRenamed+1
train.py → anifilebert/train.pyRenamed+7-6
colab/README.md+5-4
colab/start_worker.ipynb+1-1
ANDROID.md → docs/android.mdRenamed+7-6
MAINTENANCE.md → docs/maintenance.mdRenamed+26-15
docs/onnx.md+9-8
docs/training.md+21-19
benchmark_results.json → reports/benchmark_results.jsonRenamed+1-1
case_metrics.json → reports/case_metrics.jsonRenamed
parse_eval_metrics.json → reports/parse_eval_metrics.jsonRenamed
run_metadata.json → reports/run_metadata.jsonRenamed
trainer_eval_metrics.json → reports/trainer_eval_metrics.jsonRenamed
training_lineage.json → reports/training_lineage.jsonRenamed
tools/__init__.pyAdded+2
benchmark_inference.py → tools/benchmark_inference.pyRenamed+13-10
build_repair_focus_dataset.py → tools/build_repair_focus_dataset.pyRenamed+2-1
colab_client.py → tools/colab_client.pyRenamed+3-2
colab_train.py → tools/colab_train.pyRenamed+7-4
colab_worker.py → tools/colab_worker.pyRenamed+3-2
convert_to_char_dataset.py → tools/convert_to_char_dataset.pyRenamed+1
data_generator.py → tools/data_generator.pyRenamed+3-2
diagnose_pipeline.py → tools/diagnose_pipeline.pyRenamed+5-4
dmhy_dataset.py → tools/dmhy_dataset.pyRenamed+4-3
evaluate_parser_cases.py → tools/evaluate_parser_cases.pyRenamed+9-8
export_onnx.py → tools/export_onnx.pyRenamed+2-1
llm_labeler.py → tools/llm_labeler.pyRenamed+5-4
mix_datasets.py → tools/mix_datasets.pyRenamed+1
onnx_inference.py → tools/onnx_inference.pyRenamed+5-4
relabel_dataset_from_filenames.py → tools/relabel_dataset_from_filenames.pyRenamed+4-3
repair_dataset_labels.py → tools/repair_dataset_labels.pyRenamed+2-1
semantic_labeler.py → tools/semantic_labeler.pyRenamed+1
test_train_small.py → tools/test_train_small.pyRenamed+23-17