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 lines8910111213141516171821 unmodified lines404142434445464748495051525354555657585960616263646566676869704 unmodified lines757677787980815 unmodified lines878889909192932 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231244 unmodified lines12913013113213313413513613713813914014114214314415 unmodified lines1601611621631641651669 unmodified lines1761771787 unmodified lines- Root model artifacts (`config.json`, `model.safetensors`, `vocab.json`,`tokenizer_config.json`, `training_args.bin`) are the published defaultcheckpoint.- 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`.- `datasets/AnimeName` is a nested dataset submodule and should be treated asthe 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"```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.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.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-full```Export for Android:```bashuv run python export_onnx.py --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parser```## Codex-Controlled Colab Training4 unmodified linesBefore 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/`.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```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 health```Submit the default regex fine-tune:```powershellpython colab_client.py submit --profile dmhy_regex_finetune --wait```Submit the character tokenizer run only when intentional:```powershellpython colab_client.py 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>```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 . ...`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`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 exporterreports 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.- Full training is expensive; do not start long multi-epoch runs unless thetask explicitly requires it.15 unmodified linesPreserve LFS handling for `.safetensors`, `.onnx`, `.bin`, and related modelfiles.- When publishing a new checkpoint, copy the final checkpoint files to therepository root as described in `MAINTENANCE.md`.- When updating `datasets/AnimeName`, commit the submodule pointer in this repoand 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.7 unmodified lines89101112131415161721 unmodified lines394041424344454647484950515253545556575859606162636465666768694 unmodified lines747576777879805 unmodified lines868788899091922 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221234 unmodified lines12812913013113213313413513613713813914014114214315 unmodified lines1591601611621631641659 unmodified lines1751761771787 unmodified lines- Root model artifacts (`config.json`, `model.safetensors`, `vocab.json`,`tokenizer_config.json`, `training_args.bin`) are the published defaultcheckpoint.- Core parser/training code lives in `anifilebert/`.- Command-line tools live in `tools/`, including ONNX export, fixed-caseevaluation, benchmarks, dataset relabeling, dataset generation, and Colabhelpers.- `datasets/AnimeName` is a nested dataset submodule and should be treated asthe 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 -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 -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 -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 -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 -m tools.export_onnx --model-dir . --max-length 128 --android-assets-dir ../../scraper/src/main/assets/anime_parser```## Codex-Controlled Colab Training4 unmodified linesBefore 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:`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 -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 -m tools.colab_client health```Submit the default regex fine-tune:```powershellpython -m tools.colab_client submit --profile dmhy_regex_finetune --wait```Submit the character tokenizer run only when intentional:```powershellpython -m tools.colab_client submit --profile dmhy_char_train --wait```Useful follow-up commands:```powershellpython -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 -m anifilebert.inference --model-dir . ...`with at least one realistic filename.- 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 -m tools.test_train_small --limit-samples 5000 --epochs 2` when practical.- For export changes, run `python -m tools.export_onnx ...` and confirm the exporterreports a small PyTorch/ONNX logits difference.- 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 thetask explicitly requires it.15 unmodified linesPreserve LFS handling for `.safetensors`, `.onnx`, `.bin`, and related modelfiles.- When publishing a new checkpoint, copy the final checkpoint files to therepository root and reports as described in `docs/maintenance.md`.- When updating `datasets/AnimeName`, commit the submodule pointer in this repoand 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 lines454647484950512 unmodified lines5455565758596030 unmodified lines9192939495969710 unmodified lines1081091101111121131141151166 unmodified lines1231241251261271281292 unmodified lines1321331341351361371389 unmodified lines1481491501511521531541551561571581591601613 unmodified lines16516616716816917017119 unmodified lines19119219319419519619713 unmodified lines21121221321421521621735 unmodified lines2532542552562572582592602612622632642652662672682692702712722732742752762778 unmodified lines28628728844 unmodified lines| Item | Value || --- | --- || Architecture / 架构 | `BertForTokenClassification` || Tokenizer / 分词器 | Custom character tokenizer in `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` |**中文**:根目录就是发布 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"```Expected output:10 unmodified linesmodel = BertForTokenClassification.from_pretrained("ModerRAS/AniFileBERT")```**中文**:如果需要完整字段解析,请 clone 本仓库并使用 `inference.py`,因为分词器和后处理是自定义的。**English**: For complete field parsing, clone this repo and use `inference.py`; 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"```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).## 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` 为准;旧版结构规则辅助层已移除,不再作为运行时或质量对照。**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.Run regression:```powershelluv run python evaluate_parser_cases.py --model-dir . --case-file data/parser_regression_cases.json --output 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.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 `--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:- 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.pydata/parser_regression_cases.jsondatasets/AnimeName/exports/anime_filename_parser.onnxdocs/```## Maintenance / 维护See [`MAINTENANCE.md`](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.44 unmodified lines454647484950512 unmodified lines5455565758596030 unmodified lines9192939495969710 unmodified lines1081091101111121131141151166 unmodified lines1231241251261271281292 unmodified lines1321331341351361371389 unmodified lines1481491501511521531541551561571581591601613 unmodified lines16516616716816917017119 unmodified lines19119219319419519619713 unmodified lines21121221321421521621735 unmodified lines2532542552562572582592602612622632642652662672682692708 unmodified lines27928028128244 unmodified lines| Item | Value || --- | --- || Architecture / 架构 | `BertForTokenClassification` || 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 / 训练链路 | `reports/training_lineage.json` |**中文**:根目录就是发布 checkpoint,不再保留旧的 `model/` 重复副本。默认解析路径是“模型 logits + 约束 BIO + 薄字段规范化”,不再默认启用重结构规则;直接 `from_pretrained()` 只能加载 token-classification 权重。30 unmodified linesRun the Python parser:```powershelluv 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 本仓库并使用 `python -m anifilebert.inference`,因为分词器和后处理是自定义的。**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 -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 [`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 微调。细节见 `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 `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 -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 -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 -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````python -m anifilebert.train` writes:- Hugging Face checkpoints under `--save-dir`,- `final/run_metadata.json`,35 unmodified linestokenizer_config.jsonvocab.jsontraining_args.binanifilebert/tools/data/parser_regression_cases.jsondatasets/AnimeName/exports/anime_filename_parser.onnxdocs/reports/```## Maintenance / 维护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 lines72737471 unmodified lines@propertydef num_labels(self) -> int:return len(self.label2id)71 unmodified lines7273747571 unmodified lines@propertydef num_labels(self) -> int:return len(self.label2id)
10 unmodified lines111213141516171819312 unmodified lines33233333433533633733817 unmodified lines35635735810 unmodified linesfrom torch.utils.data import Datasetfrom typing import Dict, List, Optional, Tuplefrom config import Configfrom label_repairs import repair_sequel_season_labelsfrom tokenizer import AnimeTokenizerclass AnimeDataset(Dataset):312 unmodified linesif __name__ == "__main__":# Quick testfrom config import Configcfg = Config()tok = AnimeTokenizer()17 unmodified linesprint(f"input_ids: {sample['input_ids'].tolist()}")print(f"labels: {sample['labels'].tolist()}")print(f"attention_mask: {sample['attention_mask'].tolist()}")10 unmodified lines111213141516171819312 unmodified lines33233333433533633717 unmodified lines35535635735810 unmodified linesfrom torch.utils.data import Datasetfrom typing import Dict, List, Optional, Tuplefrom .config import Configfrom .label_repairs import repair_sequel_season_labelsfrom .tokenizer import AnimeTokenizerclass AnimeDataset(Dataset):312 unmodified linesif __name__ == "__main__":# Quick testcfg = Config()tok = AnimeTokenizer()17 unmodified linesprint(f"input_ids: {sample['input_ids'].tolist()}")print(f"labels: {sample['labels'].tolist()}")print(f"attention_mask: {sample['attention_mask'].tolist()}")
4 unmodified lines567891011125 unmodified lines181920212223242526492 unmodified lines5195205214 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"""import argparse5 unmodified linesimport torchfrom transformers import BertForTokenClassificationfrom config import Configfrom label_repairs import season_marker_numberfrom tokenizer import AnimeTokenizer, load_tokenizer# Chinese number mapping492 unmodified linesif __name__ == "__main__":main()4 unmodified lines567891011125 unmodified lines181920212223242526492 unmodified lines5195205215224 unmodified linesand outputs structured metadata.Usage: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 BertForTokenClassificationfrom .config import Configfrom .label_repairs import season_marker_numberfrom .tokenizer import AnimeTokenizer, load_tokenizer# Chinese number mapping492 unmodified linesif __name__ == "__main__":main()
514 unmodified lines515516517514 unmodified linesnormalized.append(f"{prefix}-{entity}")previous_entity = entityreturn normalized514 unmodified lines515516517518514 unmodified linesnormalized.append(f"{prefix}-{entity}")previous_entity = entityreturn normalized
3 unmodified lines4567891046 unmodified lines5758593 unmodified lines"""from transformers import BertConfig, BertForTokenClassificationfrom config import Configdef create_model(config: Config) -> BertForTokenClassification:46 unmodified linescfg.vocab_size = 3000model = create_model(cfg)print_model_summary(model)3 unmodified lines4567891046 unmodified lines575859603 unmodified lines"""from transformers import BertConfig, BertForTokenClassificationfrom .config import Configdef create_model(config: Config) -> BertForTokenClassification:46 unmodified linescfg.vocab_size = 3000model = create_model(cfg)print_model_summary(model)
407 unmodified lines408409410407 unmodified linesprint(f"Input: {case}")print(f"Tokens: {toks}")print()407 unmodified lines408409410411407 unmodified linesprint(f"Input: {case}")print(f"Tokens: {toks}")print()
24 unmodified lines2526272829303132333435623 unmodified lines65966066166266366466520 unmodified lines68668768824 unmodified lines)from seqeval.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_scorefrom 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, postprocessdef compute_metrics(p):623 unmodified linesif 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_modescase_metrics = evaluate_case_modes(model_dir=final_save_path,20 unmodified linesif __name__ == "__main__":main()24 unmodified lines2526272829303132333435623 unmodified lines65966066166266366466520 unmodified lines68668768868924 unmodified lines)from seqeval.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_scorefrom .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, postprocessdef compute_metrics(p):623 unmodified linesif not args.no_case_eval:if args.case_eval_file and os.path.isfile(args.case_eval_file):from tools.evaluate_parser_cases import evaluate_case_modescase_metrics = evaluate_case_modes(model_dir=final_save_path,20 unmodified linesif __name__ == "__main__":main()
19 unmodified lines2021222324252614 unmodified lines41424344454647489 unmodified lines585960616263648 unmodified lines73747519 unmodified lines%cd /content/AniFileBERT!git pull --ff-only || true!git submodule update --init --recursive!python colab_worker.py```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 --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 --wait```The worker writes per-job logs under:8 unmodified linesMyDrive/AniFileBERT/checkpoints/<profile-name>/MyDrive/AniFileBERT/last_run_manifest.json```19 unmodified lines2021222324252614 unmodified lines41424344454647489 unmodified lines585960616263648 unmodified lines7374757619 unmodified lines%cd /content/AniFileBERT!git pull --ff-only || true!git submodule update --init --recursive!python -m tools.colab_worker```The cell prints:14 unmodified lines```powershell$env:ANIFILEBERT_COLAB_URL="https://...trycloudflare.com"$env:ANIFILEBERT_COLAB_TOKEN="..."python -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 -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 lines3839404142434437 unmodified lines"%cd /content/AniFileBERT\n","!git pull --ff-only || true\n","!git submodule update --init --recursive\n","!python colab_worker.py\n"]}]37 unmodified lines3839404142434437 unmodified lines"%cd /content/AniFileBERT\n","!git pull --ff-only || true\n","!git submodule update --init --recursive\n","!python -m tools.colab_worker\n"]}]
11 unmodified lines1213141516171823 unmodified lines424344454647485 unmodified lines5455565758596013 unmodified lines7475767778798028 unmodified lines10911011111211311411 unmodified lines```powershelluv syncuv run python export_onnx.py --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"```Expected fields / 期望字段:5 unmodified linesSpecial-code example / 特典编号示例:```powershelluv run python onnx_inference.py "[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 / 高置信结构修正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.最小 Python ONNX Runtime 参考见 [`docs/onnx.md`](docs/onnx.md)。11 unmodified lines1213141516171823 unmodified lines424344454647485 unmodified lines5455565758596013 unmodified lines7475767778798028 unmodified lines10911011111211311411511 unmodified lines```powershelluv syncuv 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 -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 -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 / 字段聚合- thin string/number normalization / 轻量字符串和数字规范化The Android runtime implementation lives in MiruPlay:28 unmodified lines## More Details / 更多说明See [`onnx.md`](onnx.md) for a minimal Python ONNX Runtime reference.最小 Python ONNX Runtime 参考见 [`onnx.md`](onnx.md)。
45 unmodified lines464748495051525354553 unmodified lines596061626364656667686970717226 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212369 unmodified lines19319419545 unmodified linestraining_args.binvocab.jsonvocab.char.jsonrun_metadata.jsontrainer_eval_metrics.jsonparse_eval_metrics.jsoncase_metrics.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).完整流程见 [`docs/training.md`](docs/training.md)。Recommended full training command / 推荐全量训练命令:```powershelluv 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 `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" . -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 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.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```45 unmodified lines464748495051525354555657585960616263643 unmodified lines686970717273747576777879808126 unmodified lines10810911011111211311411511611711811912012112212312412512612712812913013113213369 unmodified lines20320420520645 unmodified linestraining_args.binvocab.jsonvocab.char.json```Release reports are kept under `reports/`:发布报告保存在 `reports/`:```textreports/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 [`training.md`](training.md).完整流程见 [`training.md`](training.md)。Recommended full training command / 推荐全量训练命令:```powershelluv 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" . -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 -m tools.export_onnx --model-dir . --output exports/anime_filename_parser.onnx --max-length 128```Validate / 验证:```powershelluv 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 lines2627282930313233343536373839404111 unmodified lines5354555657585960616263649 unmodified lines7475767778798084 unmodified lines16516616716816917017112 unmodified lines18418518625 unmodified lines- field aggregation / 字段聚合- thin string and number normalization / 薄字符串和数字规范化Those steps must stay aligned with `tokenizer.py`, `inference.py`, `config.json`,and `vocab.json`.这些步骤必须与 `tokenizer.py`、`inference.py`、`config.json`、`vocab.json`保持一致。## 2. Export / 导出```powershelluv run python export_onnx.py --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.使用 `onnx_inference.py` 作为最小可运行参考实现。```powershelluv run python onnx_inference.py "[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"```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.json```Local single-thread CPU result, measured on 26 real-world regression cases with12 unmodified lines该基准包含 tokenizer、模型/session 前向、约束 BIO 解码、实体聚合和薄层规范化;循环内不会重复创建 ONNX Runtime session。25 unmodified lines2627282930313233343536373839404111 unmodified lines5354555657585960616263649 unmodified lines7475767778798084 unmodified lines16516616716816917017112 unmodified lines18418518618725 unmodified lines- field aggregation / 字段聚合- thin string and number normalization / 薄字符串和数字规范化Those steps must stay aligned with `anifilebert/tokenizer.py`, `anifilebert/inference.py`, `config.json`,and `vocab.json`.这些步骤必须与 `anifilebert/tokenizer.py`、`anifilebert/inference.py`、`config.json`、`vocab.json`保持一致。## 2. Export / 导出```powershelluv 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 `python -m tools.onnx_inference` as the minimal runnable reference.使用 `python -m tools.onnx_inference` 作为最小可运行参考实现。```powershelluv run python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4"```Expected:9 unmodified lines特典编号示例:```powershelluv run python -m tools.onnx_inference "[YYDM&VCB-Studio] Shinsekai Yori [NCED02][Ma10p_1080p][x265_flac].mkv"```Expected:84 unmodified lines运行:```powershelluv 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 lines48495051525354555657585920 unmodified lines808182838485868 unmodified lines959697989910010135 unmodified lines1371381391401411421431 unmodified line14514614714814915015140 unmodified lines1921931941951961971981992002012 unmodified lines2042052062072082092103 unmodified lines21421521621721821922022122222322414 unmodified lines23924024124224324424524624724824947 unmodified lines## 3. Relabel Full Dataset / 全量重标注Use this when weak-label rules changed in `dmhy_dataset.py` or `label_repairs.py`.当 `dmhy_dataset.py` 或 `label_repairs.py` 的弱标注规则改变时,使用此流程。```powershelluv run python relabel_dataset_from_filenames.py `--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 `--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 `--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 `--input datasets/AnimeName/dmhy_weak_char.jsonl `--output data/thin_hard_focus_char.jsonl `--context-samples 30000 `1 unmodified line--repeat-manual 240 `--seed 57uv run python train.py --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" . -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 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.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 `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/AnimeNamegit commit -m "Update AniFileBERT model and documentation"git lfs push origin main --allgit push origin main```47 unmodified lines48495051525354555657585920 unmodified lines808182838485868 unmodified lines959697989910010135 unmodified lines1371381391401411421431 unmodified line14514614714814915015140 unmodified lines1921931941951961971981992002012022 unmodified lines2052062072082092102113 unmodified lines21521621721821922022122222322422514 unmodified lines24024124224324424524624724824925025147 unmodified lines## 3. Relabel Full Dataset / 全量重标注Use this when weak-label rules changed in `tools/dmhy_dataset.py` or `anifilebert/label_repairs.py`.当 `tools/dmhy_dataset.py` 或 `anifilebert/label_repairs.py` 的弱标注规则改变时,使用此流程。```powershelluv 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 -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 -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 -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 57uv 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" . -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 -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 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 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 `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 lines3435363733 unmodified lines"throughput_fps": 75.88307247148819}]}33 unmodified lines3435363733 unmodified lines"throughput_fps": 75.88307247148819}]}
12"""Command-line tools for AniFileBERT maintenance."""
15 unmodified lines161718192021222324252668 unmodified lines959697989910010174 unmodified lines17617717817918018118218318418518615 unmodified linesimport onnxruntime as ortfrom transformers import BertForTokenClassificationfrom config import Configfrom evaluate_parser_cases import DEFAULT_CASE_FILE, load_casesfrom inference import parse_filenamefrom onnx_inference import OnnxFilenameParserfrom tokenizer import load_tokenizerdef percentile(values: List[float], pct: float) -> float:68 unmodified linesparser.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")args = parser.parse_args()filenames = load_case_filenames(args.case_file, args.limit_cases)74 unmodified linesf"{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")if __name__ == "__main__":main()15 unmodified lines161718192021222324252627282968 unmodified lines989910010110210310474 unmodified lines17918018118218318418518618718818915 unmodified linesimport onnxruntime as ortfrom transformers import BertForTokenClassificationfrom 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_tokenizerDEFAULT_OUTPUT_FILE = Path("reports") / "benchmark_results.json"def percentile(values: List[float], pct: float) -> float:68 unmodified linesparser.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=str(DEFAULT_OUTPUT_FILE), help="JSON output path")args = parser.parse_args()filenames = load_case_filenames(args.case_file, args.limit_cases)74 unmodified linesf"{item['throughput_fps']:.1f} |")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 lines9101112131415322 unmodified lines3383393408 unmodified linesfrom pathlib import Pathfrom typing import Iterable, Listfrom label_repairs import repair_jsonl_itemSPECIAL_FOCUS_RE = re.compile(r"(?<![A-Za-z0-9])(?:NCOP|NCED|OP|ED|PV|CM|IV)\s*[_\-.]?\s*\d{0,4}"322 unmodified linesif __name__ == "__main__":main()8 unmodified lines9101112131415322 unmodified lines3383393403418 unmodified linesfrom pathlib import Pathfrom typing import Iterable, Listfrom anifilebert.label_repairs import repair_jsonl_itemSPECIAL_FOCUS_RE = re.compile(r"(?<![A-Za-z0-9])(?:NCOP|NCED|OP|ED|PV|CM|IV)\s*[_\-.]?\s*\d{0,4}"322 unmodified linesif __name__ == "__main__":main()
131 unmodified lines13213313413513613713813914014114214338 unmodified lines182183184131 unmodified linessubmit = 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("--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")status = subparsers.add_parser("status", help="Show job status")status.add_argument("job_id")38 unmodified linesif __name__ == "__main__":main()131 unmodified lines13213313413513613713813914014114214338 unmodified lines182183184185131 unmodified linessubmit = 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 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 tools.colab_train")status = subparsers.add_parser("status", help="Show job status")status.add_argument("job_id")38 unmodified linesif __name__ == "__main__":main()
2 unmodified lines3456789359 unmodified lines36937037137237337437535 unmodified lines41141241341441541641719 unmodified lines43743843944044144244397 unmodified lines5415425432 unmodified linesTypical Colab usage:python colab_train.py --config colab/configs/dmhy_regex_finetune.jsonThis script keeps the Colab side reproducible by putting run parameters in JSONprofiles. It can clone/update the repo, mount Drive, install dependencies,359 unmodified linesdef build_train_command(training: Mapping[str, Any]) -> list[str]:cmd = [sys.executable, "train.py"]for key, flag in [("tokenizer", "--tokenizer"),("data_file", "--data-file"),35 unmodified linesreturncmd = [sys.executable,"export_onnx.py","--model-dir",os.path.join(config["training"]["save_dir"], "final"),"--output",19 unmodified linesreturncmd = [sys.executable,"inference.py","--model-dir",os.path.join(config["training"]["save_dir"], "final"),smoke["sample"],97 unmodified linesif __name__ == "__main__":main()2 unmodified lines3456789359 unmodified lines36937037137237337437535 unmodified lines41141241341441541641741819 unmodified lines43843944044144244344444597 unmodified lines5435445455462 unmodified linesTypical Colab usage:python -m tools.colab_train --config colab/configs/dmhy_regex_finetune.jsonThis script keeps the Colab side reproducible by putting run parameters in JSONprofiles. It can clone/update the repo, mount Drive, install dependencies,359 unmodified linesdef build_train_command(training: Mapping[str, Any]) -> list[str]:cmd = [sys.executable, "-m", "anifilebert.train"]for key, flag in [("tokenizer", "--tokenizer"),("data_file", "--data-file"),35 unmodified linesreturncmd = [sys.executable,"-m","tools.export_onnx","--model-dir",os.path.join(config["training"]["save_dir"], "final"),"--output",19 unmodified linesreturncmd = [sys.executable,"-m","anifilebert.inference","--model-dir",os.path.join(config["training"]["save_dir"], "final"),smoke["sample"],97 unmodified linesif __name__ == "__main__":main()
2 unmodified lines3456789117 unmodified lines127128129130131132133310 unmodified lines4444454462 unmodified linesStart this inside a Colab runtime:python colab_worker.pyThe 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 lineslog_path = job_dir / "worker.log"config_path: Path | None = Nonecmd = [sys.executable, "colab_train.py"]config = self._job_config(payload)config.setdefault("artifacts", {})config["artifacts"]["manifest"] = os.fspath(job_dir / "colab_run_manifest.json")310 unmodified linesif __name__ == "__main__":main()2 unmodified lines3456789117 unmodified lines127128129130131132133310 unmodified lines4444454464472 unmodified linesStart this inside a Colab runtime:python -m tools.colab_workerThe 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 lineslog_path = job_dir / "worker.log"config_path: Path | None = Nonecmd = [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 linesif __name__ == "__main__":main()
198 unmodified lines199200201198 unmodified linesif __name__ == "__main__":main()198 unmodified lines199200201202198 unmodified linesif __name__ == "__main__":main()
13 unmodified lines1415161718192021733 unmodified lines75575675713 unmodified linesimport refrom typing import Dict, List, Optional, Tuplefrom config import Configfrom tokenizer import AnimeTokenizer, create_tokenizer# ═══════════════════════════════════════════════════════════════733 unmodified linesjson.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}")13 unmodified lines1415161718192021733 unmodified lines75575675775813 unmodified linesimport refrom typing import Dict, List, Optional, Tuplefrom anifilebert.config import Configfrom anifilebert.tokenizer import AnimeTokenizer, create_tokenizer# ═══════════════════════════════════════════════════════════════733 unmodified linesjson.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 lines26272829303132333435802 unmodified lines83883984025 unmodified linesfrom seqeval.metrics import classification_report, f1_score, precision_score, recall_scorefrom transformers import BertForTokenClassificationfrom config import Configfrom dataset import labels_for_tokenizerfrom inference import constrained_bio_decode, postprocessfrom tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerdef iter_jsonl(path: Path, limit: Optional[int] = None) -> Iterable[dict]:802 unmodified linesif __name__ == "__main__":main()25 unmodified lines26272829303132333435802 unmodified lines83883984084125 unmodified linesfrom seqeval.metrics import classification_report, f1_score, precision_score, recall_scorefrom transformers import BertForTokenClassificationfrom anifilebert.config import Configfrom anifilebert.dataset import labels_for_tokenizerfrom anifilebert.inference import constrained_bio_decode, postprocessfrom anifilebert.tokenizer import AnimeTokenizer, create_tokenizer, load_tokenizerdef iter_jsonl(path: Path, limit: Optional[int] = None) -> Iterable[dict]:802 unmodified linesif __name__ == "__main__":main()
18 unmodified lines1920212223242526271229 unmodified lines12571258125918 unmodified linesfrom pathlib import Pathfrom typing import Iterable, List, Optional, Sequencefrom data_generator import LABEL_MAP, categorize_meta_tokenfrom label_repairs import season_marker_numberfrom tokenizer import AnimeTokenizerVIDEO_EXTENSIONS = {1229 unmodified linesparsed_args = parse_args()random.seed(parsed_args.seed)export_dataset(parsed_args)18 unmodified lines1920212223242526271229 unmodified lines125712581259126018 unmodified linesfrom pathlib import Pathfrom typing import Iterable, List, Optional, Sequencefrom tools.data_generator import LABEL_MAP, categorize_meta_tokenfrom anifilebert.label_repairs import season_marker_numberfrom anifilebert.tokenizer import AnimeTokenizerVIDEO_EXTENSIONS = {1229 unmodified linesparsed_args = parse_args()random.seed(parsed_args.seed)export_dataset(parsed_args)
7 unmodified lines8910111213141516171819144 unmodified lines16416516616716816917019 unmodified lines1901911921931941951961971981992007 unmodified linesimport torchfrom transformers import BertForTokenClassificationfrom config import Configfrom inference import parse_filenamefrom tokenizer import load_tokenizerDEFAULT_CASE_FILE = os.path.join("data", "parser_regression_cases.json")def normalize_field_value(field: str, value) -> Optional[str]:144 unmodified linesparser.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("--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)if __name__ == "__main__":main()7 unmodified lines891011121314151617181920144 unmodified lines16516616716816917017119 unmodified lines1911921931941951961971981992002017 unmodified linesimport torchfrom transformers import BertForTokenClassificationfrom anifilebert.config import Configfrom anifilebert.inference import parse_filenamefrom anifilebert.tokenizer import load_tokenizerDEFAULT_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 linesparser.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=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)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 lines19202122232425115 unmodified lines14114214318 unmodified linesimport torchfrom transformers import BertForTokenClassificationfrom tokenizer import AnimeTokenizer, load_tokenizerif hasattr(sys.stdout, "reconfigure"):115 unmodified linesif __name__ == "__main__":main()18 unmodified lines19202122232425115 unmodified lines14114214314418 unmodified linesimport torchfrom transformers import BertForTokenClassificationfrom anifilebert.tokenizer import AnimeTokenizer, load_tokenizerif hasattr(sys.stdout, "reconfigure"):115 unmodified linesif __name__ == "__main__":main()
6 unmodified lines789101112131415239 unmodified lines2552562572582592602612626 unmodified linesannotation, and writes JSONL.Usage:python llm_labeler.py --max-files 100 # annotate 100 filespython llm_labeler.py --min-id 689305 # resume from file IDpython llm_labeler.py --batch-size 15 # 15 files per subagent call"""import argparseimport json239 unmodified linesprint()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()if __name__ == "__main__":main()6 unmodified lines789101112131415239 unmodified lines2552562572582592602612622636 unmodified linesannotation, and writes JSONL.Usage:python -m tools.llm_labeler --max-files 100 # annotate 100 filespython -m tools.llm_labeler --min-id 689305 # resume from file IDpython -m tools.llm_labeler --batch-size 15 # 15 files per subagent call"""import argparseimport json239 unmodified linesprint()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 -m tools.llm_labeler --merge")print()if __name__ == "__main__":main()
67 unmodified lines68697067 unmodified linesif __name__ == "__main__":main()67 unmodified lines6869707167 unmodified linesif __name__ == "__main__":main()
2 unmodified lines34567891011125 unmodified lines181920212223242597 unmodified lines1231241252 unmodified linesThe 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.Usage:python onnx_inference.py "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4""""import argparse5 unmodified linesimport onnxruntime as ortimport torchfrom inference import constrained_bio_decode, postprocessfrom tokenizer import AnimeTokenizer, load_tokenizerdef encode(97 unmodified linesif __name__ == "__main__":main()2 unmodified lines34567891011125 unmodified lines181920212223242597 unmodified lines1231241251262 unmodified linesThe ONNX file outputs token logits only. End-to-end parsing still needs therepository tokenizer, constrained BIO decoding, and the same field aggregationused by anifilebert.inference.Usage:python -m tools.onnx_inference "[GM-Team][国漫][神印王座][Throne of Seal][2022][200][AVC][GB][1080P].mp4""""import argparse5 unmodified linesimport onnxruntime as ortimport torchfrom anifilebert.inference import constrained_bio_decode, postprocessfrom anifilebert.tokenizer import AnimeTokenizer, load_tokenizerdef encode(97 unmodified linesif __name__ == "__main__":main()
9 unmodified lines101112131415161718136 unmodified lines1551561579 unmodified linesfrom statistics import meanfrom typing import Iterablefrom dmhy_dataset import weak_label_filenamefrom label_repairs import repair_jsonl_itemfrom tokenizer import AnimeTokenizerdef parse_args() -> argparse.Namespace:136 unmodified linesif __name__ == "__main__":main()9 unmodified lines101112131415161718136 unmodified lines1551561571589 unmodified linesfrom statistics import meanfrom typing import Iterablefrom tools.dmhy_dataset import weak_label_filenamefrom anifilebert.label_repairs import repair_jsonl_itemfrom anifilebert.tokenizer import AnimeTokenizerdef parse_args() -> argparse.Namespace:136 unmodified linesif __name__ == "__main__":main()
8 unmodified lines910111213141585 unmodified lines1011021038 unmodified linesfrom pathlib import Pathfrom typing import Dict, Listfrom label_repairs import LabelRepair, repair_jsonl_itemdef parse_args() -> argparse.Namespace:85 unmodified linesif __name__ == "__main__":main()8 unmodified lines910111213141585 unmodified lines1011021031048 unmodified linesfrom pathlib import Pathfrom typing import Dict, Listfrom anifilebert.label_repairs import LabelRepair, repair_jsonl_itemdef parse_args() -> argparse.Namespace:85 unmodified linesif __name__ == "__main__":main()
296 unmodified lines297298299296 unmodified linesif __name__ == "__main__":main()296 unmodified lines297298299300296 unmodified linesif __name__ == "__main__":main()
8 unmodified lines9101112131415161718192021223 unmodified lines2627282930313233343536373839404 unmodified lines4546474849505152535414 unmodified lines6970717273747527 unmodified lines1031041051061071081091101111121131148 unmodified linesTrainer, 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_metricsparser = argparse.ArgumentParser(description="Quick test: train a small A/B subset")parser.add_argument("--tokenizer", choices=["regex", "char"], default="regex")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# Load tokenizervocab_file = 'data/vocab.json' if args_cli.tokenizer == 'regex' else 'data/vocab.char.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])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',num_train_epochs=args_cli.epochs,per_device_train_batch_size=64,per_device_eval_batch_size=64,27 unmodified linesprint(f' {k}: {v:.4f}')# Savesave_path = './test_checkpoints/final'if args_cli.tokenizer == 'char':save_path = './test_checkpoints_char/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!')8 unmodified lines9101112131415161718192021222324253 unmodified lines29303132333435363738394041424344454647484950514 unmodified lines56575859606114 unmodified lines7677787980818227 unmodified lines1101111121131141151161171181191208 unmodified linesTrainer, TrainingArguments, DataCollatorForTokenClassification)from 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_metricsparser = 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_lengthoutput_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 = 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):tok.build_vocab([align_tokens_for_tokenizer(item['tokens'], item['labels'], tok)[0]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):,}')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=output_dir,num_train_epochs=args_cli.epochs,per_device_train_batch_size=64,per_device_eval_batch_size=64,27 unmodified linesprint(f' {k}: {v:.4f}')# Savesave_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