dariyooo/DaKanji-Single-Kanji-Recognition
소개
A machine learning model to recognize Japanese characters (Kanji, Katakana, Hiragana)
AI 및 머신러닝측정된 스타 증가
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
OriginalDaKanji: Single Character Recognition
A small, fast CNN that takes a (grayscale) image of any size and returns character probabilities. Recognize a single handwritten or printed Japanese character (Kanji, Hiragana, or Katakana) from a drawing. The pipeline is language-agnostic, so with your own data it works for other scripts (e.g. Chinese) too.

This is the complete v2 rewrite of this project where I applied all my learnings from the last years.
- Data agnostic: model for Japanese / Chinese / Korean / ...
- Preprocessing in the model: No more tedious image handling in app code, everything as high-performance Tensor operations
- Latest frameworks: Uses Torch + MLflow + Marimo for dev and ONNX / ExecuTorch for Deployment
- Real model comparison: Benchmarked Custom CNN / MobileNet / EffNet Lite on accuracy and latency
- Proper optimization: Latest quantization and tuned embedding size
- Result: A tiny custom CNN (<3MB) with sub millisecond latency (~0.2ms on m5 max)
| backend | precision | latency(ms) | size(MB) |
|---|---|---|---|
| ONNX Runtime (CPU) | int8 | 0.14 | 2.23 |
| XNNPACK (CPU) | int8 | 0.16 | 2.17 |
| CoreML (ANE/GPU/CPU) | fp16 | 0.15 | 4.20 |
Quick start
One-time setup (extracts the committed fonts from fonts/fonts.zip):
uv run scripts/setup.py
Put your labled images in a directory <root>/<class_index>/*.{jpg,png} and point the data config at
them. configs/data/kanji.toml: root is the train set,
val_root the held-out set. Then run the pipeline:
# 0. (optional) watch metrics live in a separate terminal.
uv run mlflow ui --backend-store-uri sqlite:///outputs/mlflow.db --port 5001 # http://127.0.0.1:5001
# 1. Train the fp32 model (90/10 split, writes outputs/runs/best.pt, logs to MLflow)
uv run python scripts/train.py --config configs/runs/kanji_efficientnet_lite_b0.toml --epochs 30
# 2. Evaluate fp32 on the held-out set (top-1/5/10 + outputs/eval/predictions.png grid)
uv run python scripts/evaluate.py --config configs/runs/kanji_efficientnet_lite_b0.toml --from outputs/runs/best.pt
# 3. Quantize + QAT fine-tune -> int8 XNNPACK .pte (outputs/exports/model_xnnpack_1024_1.pte)
uv run python scripts/quantize.py --config configs/runs/kanji_efficientnet_lite_b0.toml --from outputs/runs/best.pt --qat-epochs 8 --lr 1e-5
# 4. Evaluate the int8 .pte on the same held-out set (compare to step 2)
uv run python scripts/evaluate.py --config configs/runs/kanji_efficientnet_lite_b0.toml --pte outputs/exports/model_xnnpack_1024_1.pte
# 5. Export the fp32 model to ONNX + ExecuTorch .pte (with PyTorch parity check)
uv run python scripts/export.py --from outputs/runs/best.pt
The fp32 best.pt stays the source of truth: re-quantize or re-export from it any time.
(Step 4 runs the .pte per image through the ExecuTorch runtime, so it's slower than the
fp32 eval. Point --root at a subset for a quick check.)
Advanced
# Grid search backbone x input size (fp32) to pick an architecture, results -> CSV + MLflow
uv run python scripts/architecture_search.py --config configs/runs/grid.toml
# Or experiment interactively (widgets for backbone / size / lr, logs to MLflow)
uv run marimo edit notebooks/train.py
# Apple CoreML .pte (ANE/GPU/CPU). Self-contained: uv pins an isolated torch 2.7 toolchain
# from the script header, because the CoreML delegate miscompiles on the main torch 2.12 stack.
uv run scripts/export_coreml.py --from outputs/runs/head_rank/r128/best.pt
# Vulkan .pte (cross-platform GPU), int8 or int4 weight-only on the classifier
uv run python scripts/export.py --from outputs/runs/head_rank/r128/best.pt \
--vulkan outputs/exports/model_vulkan_int8.pte --vulkan-quantize 8
You can follow the recipe in these files to export the models to other accelerators.
Visually similar characters
The visual look-alikes of every kanji are computed from this model's release in kanji-visual-similarity-yomitan, which publishes them as a Yomitan / DaLang dictionary.
Packaging for the DaKanji app
scripts/prepare_release_assets.py bundles the exported
artifacts (the XNNPACK .pte per input bound, ONNX, labels, and the fp32 checkpoint) into the
release assets the app expects, and throws if any are missing:
uv run python scripts/prepare_release_assets.py # -> outputs/release/
Input bounds
ExecuTorch reserves its memory arena at load from the declared bound, so each bound passed to
--max-side becomes its own method: forward_1024 (20 MiB) and forward_64 (80 KiB). Load the
one you need, and re-export any other bound from the quantized.pt2 written beside the checkpoint.
Inputs above a method's bound are a shape error, so downscale with
F.interpolate(x, size=(64, 64), mode="bilinear", align_corners=False). ONNX has no bound.
Tracking runs on a remote MLflow
Runs log to a local sqlite store under outputs/ by default. Point them at a tracking server with
mlflow's own environment variable, so no host ends up in the repo:
export MLFLOW_TRACKING_URI=http://<host>:<port>
Experiments are named DaKanji-Single-Kanji-Recognition/<stage> so several projects can share one
server. A tracking server owns its artifact store, so artifacts upload through it and clients need
no S3 credentials. Logging is best effort: if the server is unreachable, training warns once and
carries on.
How it works
- A run config (
configs/runs/*.toml) holds the training config inline (model, optimizer, augmentation, logging) and references one reusabledatafragment by name. - Training runs a custom PyTorch loop (AMP, schedules, MLflow logging, checkpoints), producing an fp32 checkpoint as the source of truth.
- Quantization (optional, stage 2) fine-tunes that checkpoint with PT2E QAT and lowers it to an int8 XNNPACK
.ptefor on-device CPU/ARM inference. - Export turns a checkpoint into an ONNX or ExecuTorch artifact with resize and normalize baked in, so it takes a raw grayscale image and outputs character probabilities. ONNX accepts any input size; an ExecuTorch
.pteaccepts sizes up to the bound it was exported with.
Inference.
Input: an image (B, C, H, W) with C = 1 (grayscale, preferred) or C = 3 (RGB, may have slightly worse results), any size, any range. The model resizes and reduces colour to one channel internally.
Output: probabilities (B, num_classes) aligned with labels.txt.
Apps that use this model
| name | android | iOS | Linux | MacOS | Windows | Web |
|---|---|---|---|---|---|---|
| DaKanji (v4+) | ✅ | ✅ | ✅ | ✅ | ✅ | |
| Kanjiheatmap | ✅ | |||||
| Yaku | ✅ |
Full Results
Results of initial trainig
| backbone (fp32) | size | acc | latency(ms) | size(MB) |
|---|---|---|---|---|
| efficientnet_lite_b4 | 64 | 0.997 | 402.15 | 80.88 |
| small_cnn | 64 | 0.995 | 0.74 | 11.40 |
| mobilenetv3_large | 64 | 0.995 | 59.50 | 50.35 |
| efficientnet_lite_b0 | 64 | 0.992 | 142.36 | 47.09 |
| mobilenetv3_small | 64 | 0.990 | 52.87 | 32.88 |
(latency = mean of 300 runs)
Results of embedding tuning
| head_rank | acc | latency(ms) | size(MB) | params(M) |
|---|---|---|---|---|
| 256 | 0.995 | 0.74 | 11.67 | 2.91 |
| 192 | 0.995 | 0.90 | 9.94 | 2.48 |
| 128 | 0.995 | 0.85 | 8.20 | 2.04 |
| 96 | 0.994 | 0.72 | 7.34 | 1.83 |
| 64 | 0.993 | 0.72 | 6.47 | 1.61 |
Results of quantization (top-1/5/10 over the full val_root, 1,301,400 images)
| precision | top-1 | top-5 | top-10 | errors | size(MB) | params(M) |
|---|---|---|---|---|---|---|
| fp32 | 0.9974 | 1.0000 | 1.0000 | 3,415 | 8.20 | 2.04 |
| int8 (ONNX) | 0.9963 | 1.0000 | 1.0000 | 4,811 | 2.23 | 2.04 |
| int8 (XNNPACK) | 0.9924 | 0.9999 | 1.0000 | 9,928 | 2.17 | 2.04 |
Backend comparison (latency = median of 500 runs at 64x64, batch 1, M-series CPU)
| backend | precision | median(ms) | p90 | max | size(MB) |
|---|---|---|---|---|---|
| ONNX Runtime (CPU) | int8 | 0.136 | 0.148 | 0.219 | 2.23 |
| XNNPACK (CPU) | int8 | 0.158 | 0.173 | 0.191 | 2.17 |
| CoreML (ANE/GPU/CPU) | fp16 | 0.15 | - | - | 4.20 |
| ExecuTorch portable (CPU) | fp32 | 36.60 | - | - | 8.20 |
Usage in your software
I put lots of effort and time into developing this model and hope that it can be used in many apps.
If you decide to use this machine learning model please give me credit like:
Character recognition powered by machine learning from Dariyooo (DaAppLab)
It would also be nice if you open an issue and tell me that you are using this model.
Than I would add your software to the apps section
Credits
Training data kindly provided by the ETL Character Database and the KanjiVG dataset. Architecture based on EfficientNet: Rethinking Model Scaling for CNNs.
License
MIT © CaptainDario
관련 프로젝트 살펴보기
불러오는 중…