Image Classification
timm
ONNX
Safetensors
mobile-screenshots
phone-screenshots
screenshot-analysis
content-safety
Instructions to use yapwithai/phone-screen-classifier with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- timm
How to use yapwithai/phone-screen-classifier with timm:
import timm model = timm.create_model("hf_hub:yapwithai/phone-screen-classifier", pretrained=True) - Notebooks
- Google Colab
- Kaggle
Upload phone screen classifier
Browse files- README.md +201 -0
- checkpoints/checkpoint.pt +3 -0
- config.json +41 -0
- inference/labels.json +68 -0
- inference/python.py +144 -0
- inference/typescript.ts +283 -0
- model.safetensors +3 -0
- onnx/model.fp16.onnx +3 -0
- onnx/model.int8.onnx +3 -0
- onnx/model.onnx +3 -0
- onnx/model.onnx.data +3 -0
- preprocess.json +17 -0
- train.json +203 -0
README.md
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
model_name: Yap Phone Screenshot Classifier
|
| 3 |
+
library_name: 'timm'
|
| 4 |
+
base_model: 'timm/mobilenetv4_conv_medium.e250_r384_in12k'
|
| 5 |
+
tags:
|
| 6 |
+
- image-classification
|
| 7 |
+
- mobile-screenshots
|
| 8 |
+
- phone-screenshots
|
| 9 |
+
- screenshot-analysis
|
| 10 |
+
- content-safety
|
| 11 |
+
- timm
|
| 12 |
+
datasets:
|
| 13 |
+
- yapwithai/phone-screenshots
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# Yap Phone Screenshot Classifier
|
| 17 |
+
|
| 18 |
+
Yap Phone Screenshot Classifier predicts two labels for one image:
|
| 19 |
+
|
| 20 |
+
1. `screen`: the phone-screen category.
|
| 21 |
+
2. `safety`: the content-safety category.
|
| 22 |
+
|
| 23 |
+
The model returns exactly two outputs: `screen` and `safety`.
|
| 24 |
+
|
| 25 |
+
The model is fine-tuned from `timm/mobilenetv4_conv_medium.e250_r384_in12k` on the Yap phone screenshot dataset: [`yapwithai/phone-screenshots`](https://huggingface.co/datasets/yapwithai/phone-screenshots).
|
| 26 |
+
|
| 27 |
+
## What It Is For
|
| 28 |
+
|
| 29 |
+
This model is built for routing and filtering mobile screenshot workflows. It separates UI classification from safety classification so an application can answer both of these questions before running more expensive analysis:
|
| 30 |
+
|
| 31 |
+
- What kind of screen is this?
|
| 32 |
+
- Which safety category does this image belong to?
|
| 33 |
+
|
| 34 |
+
`generic` and `other` are real screen labels when included in the exported label map. `generic` means phone UI that is not one of the more specific trained screen classes. `other` means non-phone UI or images outside the phone-screenshot distribution.
|
| 35 |
+
|
| 36 |
+
## Files
|
| 37 |
+
|
| 38 |
+
| File | Purpose |
|
| 39 |
+
| :------------------------ | :------------------------------------------------------------- |
|
| 40 |
+
| `onnx/model.onnx` | ONNX model for CPU/server inference. |
|
| 41 |
+
| `onnx/model.fp16.onnx` | Optional FP16 ONNX candidate. |
|
| 42 |
+
| `onnx/model.int8.onnx` | Optional INT8 ONNX candidate. |
|
| 43 |
+
| `onnx/model.onnx.data` | External ONNX weight data loaded beside `model.onnx`. |
|
| 44 |
+
| `model.safetensors` | PyTorch state dict for reproducibility and continued training. |
|
| 45 |
+
| `config.json` | Model identity, base model, output names, and label arrays. |
|
| 46 |
+
| `preprocess.json` | Resize and normalization contract used during training/export. |
|
| 47 |
+
| `train.json` | Sanitized training recipe for post-training or reproduction. |
|
| 48 |
+
| `inference/python.py` | Python helper for ONNX inference from image paths. |
|
| 49 |
+
| `inference/typescript.ts` | TypeScript helper for ONNX inference from image paths. |
|
| 50 |
+
| `inference/labels.json` | Screen and safety labels used to decode model logits. |
|
| 51 |
+
| `README.md` | This model card and runnable inference reference. |
|
| 52 |
+
|
| 53 |
+
## Outputs
|
| 54 |
+
|
| 55 |
+
The ONNX graph has two outputs in this exact order:
|
| 56 |
+
|
| 57 |
+
| Output | Shape | Meaning |
|
| 58 |
+
| :------- | :---------------------------- | :---------------------- |
|
| 59 |
+
| `screen` | `[batch, screen_class_count]` | Screen-category logits. |
|
| 60 |
+
| `safety` | `[batch, safety_class_count]` | Content-safety logits. |
|
| 61 |
+
|
| 62 |
+
Inference uses `argmax` for both heads in this version.
|
| 63 |
+
|
| 64 |
+
## Test Results
|
| 65 |
+
|
| 66 |
+
| Model | Test | Output | Accuracy | Balanced Acc | Macro F1 | Top-2 | Images |
|
| 67 |
+
| :-- | --: | --: | --: | --: | --: | --: | --: |
|
| 68 |
+
| fp32 | full test | screen | 0.9154 | 0.8385 | 0.7265 | 0.9719 | 23615 |
|
| 69 |
+
| fp32 | full test | safety | 0.9575 | 0.8941 | 0.8600 | 0.9921 | 23615 |
|
| 70 |
+
| fp32 | screen-balanced test | screen | 0.8377 | 0.8421 | 0.8133 | 0.9400 | 6246 |
|
| 71 |
+
| fp32 | screen-balanced test | safety | 0.9776 | 0.9285 | 0.9110 | 0.9978 | 6246 |
|
| 72 |
+
| fp32 | safety-balanced test | screen | 0.9580 | 0.7752 | 0.6547 | 0.9870 | 3000 |
|
| 73 |
+
| fp32 | safety-balanced test | safety | 0.8957 | 0.8957 | 0.8947 | 0.9847 | 3000 |
|
| 74 |
+
| fp16 | full test | screen | 0.9153 | 0.8384 | 0.7264 | 0.9719 | 23615 |
|
| 75 |
+
| fp16 | full test | safety | 0.9575 | 0.8941 | 0.8600 | 0.9921 | 23615 |
|
| 76 |
+
| fp16 | screen-balanced test | screen | 0.8373 | 0.8419 | 0.8130 | 0.9400 | 6246 |
|
| 77 |
+
| fp16 | screen-balanced test | safety | 0.9776 | 0.9285 | 0.9110 | 0.9978 | 6246 |
|
| 78 |
+
| fp16 | safety-balanced test | screen | 0.9580 | 0.7752 | 0.6547 | 0.9870 | 3000 |
|
| 79 |
+
| fp16 | safety-balanced test | safety | 0.8957 | 0.8957 | 0.8947 | 0.9847 | 3000 |
|
| 80 |
+
| int8 | full test | screen | 0.0018 | 0.0424 | 0.0024 | 0.0278 | 23615 |
|
| 81 |
+
| int8 | full test | safety | 0.1013 | 0.3502 | 0.0696 | 0.9431 | 23615 |
|
| 82 |
+
| int8 | screen-balanced test | screen | 0.0062 | 0.0424 | 0.0031 | 0.1039 | 6246 |
|
| 83 |
+
| int8 | screen-balanced test | safety | 0.1703 | 0.3686 | 0.1153 | 0.9241 | 6246 |
|
| 84 |
+
| int8 | safety-balanced test | screen | 0.0003 | 0.0417 | 0.0000 | 0.0140 | 3000 |
|
| 85 |
+
| int8 | safety-balanced test | safety | 0.3493 | 0.3493 | 0.1992 | 0.6667 | 3000 |
|
| 86 |
+
|
| 87 |
+
## CPU Timing
|
| 88 |
+
|
| 89 |
+
| Model | Images/s | Load Mean | Model Mean | Total Mean | Total Median | Total P95 | Provider |
|
| 90 |
+
| :-- | --: | --: | --: | --: | --: | --: | --: |
|
| 91 |
+
| fp32 | 20.0538 | 0.12 ms | 49.52 ms | 49.87 ms | 57.84 ms | 85.82 ms | onnxruntime:CPUExecutionProvider |
|
| 92 |
+
| fp16 | 20.8351 | 0.11 ms | 47.69 ms | 48.00 ms | 48.60 ms | 63.65 ms | onnxruntime:CPUExecutionProvider |
|
| 93 |
+
| int8 | 72.6504 | 0.14 ms | 13.36 ms | 13.76 ms | 14.07 ms | 18.01 ms | onnxruntime:CPUExecutionProvider |
|
| 94 |
+
|
| 95 |
+
Timing is measured with ONNX Runtime CPU execution on `Apple M4 Max (16 logical cores)`. Total latency includes image load/preprocess, model inference, and label decoding.
|
| 96 |
+
|
| 97 |
+
## Classification Labels
|
| 98 |
+
|
| 99 |
+
For the screen and safety label lists, see [`config.json`](config.json).
|
| 100 |
+
|
| 101 |
+
## Preprocessing
|
| 102 |
+
|
| 103 |
+
Use the preprocessing contract in `preprocess.json`.
|
| 104 |
+
|
| 105 |
+
1. Read the image.
|
| 106 |
+
2. Apply EXIF orientation.
|
| 107 |
+
3. Convert to RGB.
|
| 108 |
+
4. Resize so the longest side is `1024` pixels and keep the original aspect ratio.
|
| 109 |
+
5. Do not crop, stretch, square-pad before preprocessing, or horizontally flip.
|
| 110 |
+
6. Convert to `float32` in `[0, 1]`.
|
| 111 |
+
7. Normalize with the mean and standard deviation from `preprocess.json`.
|
| 112 |
+
8. Pad each normalized tensor to the batch maximum height and width, rounded up to a multiple of 32.
|
| 113 |
+
|
| 114 |
+
The exported model accepts dynamic batch, height, and width.
|
| 115 |
+
|
| 116 |
+
## ONNX Inference
|
| 117 |
+
|
| 118 |
+
The helpers intentionally return only `screen` and `safety`.
|
| 119 |
+
|
| 120 |
+
Keep `onnx/model.onnx.data` beside `onnx/model.onnx`; ONNX Runtime loads the external tensor data when it opens the graph.
|
| 121 |
+
|
| 122 |
+
### Download
|
| 123 |
+
|
| 124 |
+
Download the exported model folder from Hugging Face:
|
| 125 |
+
|
| 126 |
+
```python
|
| 127 |
+
from huggingface_hub import snapshot_download
|
| 128 |
+
|
| 129 |
+
model_dir = snapshot_download("yapwithai/phone-screen-classifier")
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
### Python
|
| 133 |
+
|
| 134 |
+
Install the runtime dependencies:
|
| 135 |
+
|
| 136 |
+
```bash
|
| 137 |
+
python -m pip install numpy pillow onnxruntime
|
| 138 |
+
```
|
| 139 |
+
|
| 140 |
+
Import the helper from the exported model folder:
|
| 141 |
+
|
| 142 |
+
```python
|
| 143 |
+
from inference.python import Classifier, classify
|
| 144 |
+
|
| 145 |
+
print(classify("example.png"))
|
| 146 |
+
|
| 147 |
+
classifier = Classifier(model_dir)
|
| 148 |
+
print(classifier.classify_batch(["one.png", "two.png"]))
|
| 149 |
+
```
|
| 150 |
+
|
| 151 |
+
Or run it directly:
|
| 152 |
+
|
| 153 |
+
```bash
|
| 154 |
+
python inference/python.py example.png another.png
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
### TypeScript
|
| 158 |
+
|
| 159 |
+
Install the runtime dependencies:
|
| 160 |
+
|
| 161 |
+
```bash
|
| 162 |
+
bun add sharp onnxruntime-node
|
| 163 |
+
```
|
| 164 |
+
|
| 165 |
+
Import the helper from the exported model folder:
|
| 166 |
+
|
| 167 |
+
```ts
|
| 168 |
+
import { Classifier, classify } from './inference/typescript.ts';
|
| 169 |
+
|
| 170 |
+
console.log(await classify('example.png'));
|
| 171 |
+
|
| 172 |
+
const classifier = await Classifier.create(modelDir);
|
| 173 |
+
console.log(await classifier.classifyBatch(['one.png', 'two.png']));
|
| 174 |
+
```
|
| 175 |
+
|
| 176 |
+
Or run it directly:
|
| 177 |
+
|
| 178 |
+
```bash
|
| 179 |
+
bun inference/typescript.ts example.png another.png
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
## Training Data
|
| 183 |
+
|
| 184 |
+
The model is trained from local shards of [`yapwithai/phone-screenshots`](https://huggingface.co/datasets/yapwithai/phone-screenshots). Screen labels come from the dataset `label` field. Safety labels come from the dataset `safety` field. `fine_label` is not used.
|
| 185 |
+
|
| 186 |
+
Training uses one minimum train-count floor for both heads. The default is `--min-train-count 300`. Labels with fewer than `--min-train-count` train samples are not trained directly. Screen labels below the floor are folded into `generic`; safety labels below the floor are omitted from the safety head. The exported `config.json` and `inference/labels.json` files are the source of truth for the active screen and safety labels.
|
| 187 |
+
|
| 188 |
+
Training uses adaptive label sampling. `--screen-target-ratio` and `--safety-target-ratio` set the desired effective per-epoch class ratio; `--screen-max-repeat` and `--safety-max-repeat` cap how often smaller classes can repeat in one epoch.
|
| 189 |
+
|
| 190 |
+
## Citation
|
| 191 |
+
|
| 192 |
+
If you use this model, please cite:
|
| 193 |
+
|
| 194 |
+
```bibtex
|
| 195 |
+
@misc{phone-screen-classifier,
|
| 196 |
+
title={Yap Phone Screenshot Classifier},
|
| 197 |
+
year={2026},
|
| 198 |
+
publisher={Yap With AI},
|
| 199 |
+
url={https://huggingface.co/yapwithai/phone-screen-classifier}
|
| 200 |
+
}
|
| 201 |
+
```
|
checkpoints/checkpoint.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7e22dfcf02e0993c23ea02f729d62190e85ff9e8ae5cf01046c0b78942c94e09
|
| 3 |
+
size 104626873
|
config.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architecture": "timm-spatial-flat-multitask",
|
| 3 |
+
"model": "timm/mobilenetv4_conv_medium.e250_r384_in12k",
|
| 4 |
+
"name": "Yap Phone Screenshot Classifier",
|
| 5 |
+
"outputs": [
|
| 6 |
+
"screen",
|
| 7 |
+
"safety"
|
| 8 |
+
],
|
| 9 |
+
"resize_longest_side_px": 1024,
|
| 10 |
+
"safety_labels": [
|
| 11 |
+
"hot",
|
| 12 |
+
"nsfw",
|
| 13 |
+
"safe"
|
| 14 |
+
],
|
| 15 |
+
"screen_labels": [
|
| 16 |
+
"audio",
|
| 17 |
+
"calendar",
|
| 18 |
+
"camera",
|
| 19 |
+
"comments",
|
| 20 |
+
"contacts",
|
| 21 |
+
"email",
|
| 22 |
+
"excel",
|
| 23 |
+
"feed",
|
| 24 |
+
"finances",
|
| 25 |
+
"food",
|
| 26 |
+
"gallery",
|
| 27 |
+
"game",
|
| 28 |
+
"generic",
|
| 29 |
+
"maps",
|
| 30 |
+
"message-chat",
|
| 31 |
+
"message-list",
|
| 32 |
+
"notes",
|
| 33 |
+
"other",
|
| 34 |
+
"post",
|
| 35 |
+
"profile",
|
| 36 |
+
"reading",
|
| 37 |
+
"shopping",
|
| 38 |
+
"streaming",
|
| 39 |
+
"weather"
|
| 40 |
+
]
|
| 41 |
+
}
|
inference/labels.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"safety": {
|
| 3 |
+
"label_to_id": {
|
| 4 |
+
"hot": 0,
|
| 5 |
+
"nsfw": 1,
|
| 6 |
+
"safe": 2
|
| 7 |
+
},
|
| 8 |
+
"labels": [
|
| 9 |
+
"hot",
|
| 10 |
+
"nsfw",
|
| 11 |
+
"safe"
|
| 12 |
+
]
|
| 13 |
+
},
|
| 14 |
+
"screen": {
|
| 15 |
+
"label_to_id": {
|
| 16 |
+
"audio": 0,
|
| 17 |
+
"calendar": 1,
|
| 18 |
+
"camera": 2,
|
| 19 |
+
"comments": 3,
|
| 20 |
+
"contacts": 4,
|
| 21 |
+
"email": 5,
|
| 22 |
+
"excel": 6,
|
| 23 |
+
"feed": 7,
|
| 24 |
+
"finances": 8,
|
| 25 |
+
"food": 9,
|
| 26 |
+
"gallery": 10,
|
| 27 |
+
"game": 11,
|
| 28 |
+
"generic": 12,
|
| 29 |
+
"maps": 13,
|
| 30 |
+
"message-chat": 14,
|
| 31 |
+
"message-list": 15,
|
| 32 |
+
"notes": 16,
|
| 33 |
+
"other": 17,
|
| 34 |
+
"post": 18,
|
| 35 |
+
"profile": 19,
|
| 36 |
+
"reading": 20,
|
| 37 |
+
"shopping": 21,
|
| 38 |
+
"streaming": 22,
|
| 39 |
+
"weather": 23
|
| 40 |
+
},
|
| 41 |
+
"labels": [
|
| 42 |
+
"audio",
|
| 43 |
+
"calendar",
|
| 44 |
+
"camera",
|
| 45 |
+
"comments",
|
| 46 |
+
"contacts",
|
| 47 |
+
"email",
|
| 48 |
+
"excel",
|
| 49 |
+
"feed",
|
| 50 |
+
"finances",
|
| 51 |
+
"food",
|
| 52 |
+
"gallery",
|
| 53 |
+
"game",
|
| 54 |
+
"generic",
|
| 55 |
+
"maps",
|
| 56 |
+
"message-chat",
|
| 57 |
+
"message-list",
|
| 58 |
+
"notes",
|
| 59 |
+
"other",
|
| 60 |
+
"post",
|
| 61 |
+
"profile",
|
| 62 |
+
"reading",
|
| 63 |
+
"shopping",
|
| 64 |
+
"streaming",
|
| 65 |
+
"weather"
|
| 66 |
+
]
|
| 67 |
+
}
|
| 68 |
+
}
|
inference/python.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Sequence, TypedDict, cast
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import onnxruntime as ort
|
| 9 |
+
from PIL import Image, ImageOps
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
MODEL_DIR = Path(__file__).resolve().parent.parent
|
| 13 |
+
PADDING_MULTIPLE = 32
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class Preprocess(TypedDict):
|
| 17 |
+
resize_longest_side_px: int
|
| 18 |
+
mean: list[float]
|
| 19 |
+
std: list[float]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class LabelSet(TypedDict):
|
| 23 |
+
labels: list[str]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Labels(TypedDict):
|
| 27 |
+
screen: LabelSet
|
| 28 |
+
safety: LabelSet
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Prediction(TypedDict):
|
| 32 |
+
screen: str
|
| 33 |
+
safety: str
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class Classifier:
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
model_dir: str | Path = MODEL_DIR,
|
| 40 |
+
providers: Sequence[str] = ("CPUExecutionProvider",),
|
| 41 |
+
) -> None:
|
| 42 |
+
self.directory = Path(model_dir)
|
| 43 |
+
self.session = ort.InferenceSession(str(self.directory / "onnx" / "model.onnx"), providers=list(providers))
|
| 44 |
+
self.preprocess = load_preprocess(self.directory / "preprocess.json")
|
| 45 |
+
self.labels = load_labels(self.directory / "inference" / "labels.json")
|
| 46 |
+
|
| 47 |
+
def classify(self, image_path: str | Path) -> Prediction:
|
| 48 |
+
return self.classify_batch([image_path])[0]
|
| 49 |
+
|
| 50 |
+
def classify_batch(self, image_paths: Sequence[str | Path]) -> list[Prediction]:
|
| 51 |
+
if not image_paths:
|
| 52 |
+
return []
|
| 53 |
+
images = [preprocess_image(Path(image_path), self.preprocess) for image_path in image_paths]
|
| 54 |
+
screen_logits, safety_logits = self.session.run(None, {"image": collate_images(images)})
|
| 55 |
+
return decode_predictions(screen_logits, safety_logits, self.labels)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def classify(image_path: str | Path, model_dir: str | Path = MODEL_DIR) -> Prediction:
|
| 59 |
+
return Classifier(model_dir).classify(image_path)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def classify_batch(image_paths: Sequence[str | Path], model_dir: str | Path = MODEL_DIR) -> list[Prediction]:
|
| 63 |
+
return Classifier(model_dir).classify_batch(image_paths)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def preprocess_image(image_path: Path, preprocess: Preprocess) -> np.ndarray:
|
| 67 |
+
with Image.open(image_path) as opened:
|
| 68 |
+
image = to_training_rgb(opened)
|
| 69 |
+
resized = resize_image(image, preprocess["resize_longest_side_px"])
|
| 70 |
+
array = np.asarray(resized).astype("float32") / 255.0
|
| 71 |
+
mean = np.asarray(preprocess["mean"], dtype="float32")
|
| 72 |
+
std = np.asarray(preprocess["std"], dtype="float32")
|
| 73 |
+
array = (array - mean) / std
|
| 74 |
+
return np.transpose(array, (2, 0, 1))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def to_training_rgb(image: Image.Image) -> Image.Image:
|
| 78 |
+
image = ImageOps.exif_transpose(image)
|
| 79 |
+
if image.mode == "P" and isinstance(image.info.get("transparency"), bytes):
|
| 80 |
+
image = image.convert("RGBA")
|
| 81 |
+
if image.mode in ("RGBA", "LA", "PA"):
|
| 82 |
+
rgba = image.convert("RGBA")
|
| 83 |
+
background = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
|
| 84 |
+
image = Image.alpha_composite(background, rgba)
|
| 85 |
+
return image.convert("RGB")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def collate_images(images: Sequence[np.ndarray]) -> np.ndarray:
|
| 89 |
+
height = round_up(max(int(image.shape[1]) for image in images))
|
| 90 |
+
width = round_up(max(int(image.shape[2]) for image in images))
|
| 91 |
+
batch = np.zeros((len(images), 3, height, width), dtype="float32")
|
| 92 |
+
for index, image in enumerate(images):
|
| 93 |
+
image_height = int(image.shape[1])
|
| 94 |
+
image_width = int(image.shape[2])
|
| 95 |
+
batch[index, :, :image_height, :image_width] = image
|
| 96 |
+
return batch
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def resize_image(image: Image.Image, image_size: int) -> Image.Image:
|
| 100 |
+
scale = image_size / max(image.width, image.height)
|
| 101 |
+
width = max(1, round(image.width * scale))
|
| 102 |
+
height = max(1, round(image.height * scale))
|
| 103 |
+
return image.resize((width, height), Image.Resampling.BICUBIC)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def round_up(value: int, multiple: int = PADDING_MULTIPLE) -> int:
|
| 107 |
+
return ((value + multiple - 1) // multiple) * multiple
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def decode_predictions(screen_logits: np.ndarray, safety_logits: np.ndarray, labels: Labels) -> list[Prediction]:
|
| 111 |
+
# ONNX emits flat screen and safety logits.
|
| 112 |
+
screen_indices = top_indices(screen_logits)
|
| 113 |
+
safety_indices = top_indices(safety_logits)
|
| 114 |
+
return [
|
| 115 |
+
{
|
| 116 |
+
"screen": labels["screen"]["labels"][screen_index],
|
| 117 |
+
"safety": labels["safety"]["labels"][safety_index],
|
| 118 |
+
}
|
| 119 |
+
for screen_index, safety_index in zip(screen_indices, safety_indices, strict=True)
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def load_labels(path: Path) -> Labels:
|
| 124 |
+
return cast(Labels, json.loads(path.read_text(encoding="utf-8")))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def load_preprocess(path: Path) -> Preprocess:
|
| 128 |
+
return cast(Preprocess, json.loads(path.read_text(encoding="utf-8")))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def top_indices(logits: np.ndarray) -> list[int]:
|
| 132 |
+
return [int(index) for index in np.argmax(logits, axis=1)]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
import argparse
|
| 137 |
+
|
| 138 |
+
parser = argparse.ArgumentParser(description="Classify images with the exported ONNX model.")
|
| 139 |
+
parser.add_argument("images", nargs="+")
|
| 140 |
+
parser.add_argument("--model-dir", default=str(MODEL_DIR))
|
| 141 |
+
args = parser.parse_args()
|
| 142 |
+
predictions = classify_batch(args.images, args.model_dir)
|
| 143 |
+
value: Prediction | list[Prediction] = predictions[0] if len(predictions) == 1 else predictions
|
| 144 |
+
print(json.dumps(value, indent=2))
|
inference/typescript.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sharp from 'sharp';
|
| 2 |
+
import * as ort from 'onnxruntime-node';
|
| 3 |
+
import { readFile } from 'node:fs/promises';
|
| 4 |
+
import { dirname, resolve } from 'node:path';
|
| 5 |
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
| 6 |
+
|
| 7 |
+
const MODEL_DIR = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
| 8 |
+
const PADDING_MULTIPLE = 32;
|
| 9 |
+
|
| 10 |
+
export class Classifier {
|
| 11 |
+
private constructor(
|
| 12 |
+
private readonly session: ort.InferenceSession,
|
| 13 |
+
private readonly preprocess: {
|
| 14 |
+
resize_longest_side_px: number;
|
| 15 |
+
mean: [number, number, number];
|
| 16 |
+
std: [number, number, number];
|
| 17 |
+
},
|
| 18 |
+
private readonly labels: {
|
| 19 |
+
screen: { labels: string[] };
|
| 20 |
+
safety: { labels: string[] };
|
| 21 |
+
},
|
| 22 |
+
) {}
|
| 23 |
+
|
| 24 |
+
/**
|
| 25 |
+
* Load the exported ONNX classifier and sidecar metadata.
|
| 26 |
+
*
|
| 27 |
+
* @param modelDir Directory containing the exported model artifacts.
|
| 28 |
+
* @returns Ready-to-use classifier instance.
|
| 29 |
+
*/
|
| 30 |
+
static async create(modelDir = MODEL_DIR): Promise<Classifier> {
|
| 31 |
+
const session = await ort.InferenceSession.create(resolve(modelDir, 'onnx/model.onnx'), {
|
| 32 |
+
executionProviders: ['cpu'],
|
| 33 |
+
});
|
| 34 |
+
const preprocess = JSON.parse(await readFile(resolve(modelDir, 'preprocess.json'), 'utf8')) as {
|
| 35 |
+
resize_longest_side_px: number;
|
| 36 |
+
mean: [number, number, number];
|
| 37 |
+
std: [number, number, number];
|
| 38 |
+
};
|
| 39 |
+
const labels = JSON.parse(await readFile(resolve(modelDir, 'inference/labels.json'), 'utf8')) as {
|
| 40 |
+
screen: { labels: string[] };
|
| 41 |
+
safety: { labels: string[] };
|
| 42 |
+
};
|
| 43 |
+
return new Classifier(session, preprocess, labels);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
/**
|
| 47 |
+
* Classify one image.
|
| 48 |
+
*
|
| 49 |
+
* @param imagePath Path to an image file.
|
| 50 |
+
* @returns Predicted public screen and safety labels.
|
| 51 |
+
*/
|
| 52 |
+
async classify(imagePath: string): Promise<{ screen: string; safety: string }> {
|
| 53 |
+
const [prediction] = await this.classifyBatch([imagePath]);
|
| 54 |
+
if (prediction === undefined) {
|
| 55 |
+
throw new Error('No prediction was produced.');
|
| 56 |
+
}
|
| 57 |
+
return prediction;
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/**
|
| 61 |
+
* Classify a batch of images.
|
| 62 |
+
*
|
| 63 |
+
* @param imagePaths Paths to image files.
|
| 64 |
+
* @returns Predicted public screen and safety labels for each image.
|
| 65 |
+
*/
|
| 66 |
+
async classifyBatch(imagePaths: readonly string[]): Promise<Array<{ screen: string; safety: string }>> {
|
| 67 |
+
if (imagePaths.length === 0) {
|
| 68 |
+
return [];
|
| 69 |
+
}
|
| 70 |
+
const images = await Promise.all(imagePaths.map((imagePath) => preprocessImage(imagePath, this.preprocess)));
|
| 71 |
+
const output = await this.session.run({ image: collateImages(images) });
|
| 72 |
+
return decodePredictions(outputTensor(output, 'screen'), outputTensor(output, 'safety'), this.labels);
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* Classify one image with a classifier loaded from disk.
|
| 78 |
+
*
|
| 79 |
+
* @param imagePath Path to an image file.
|
| 80 |
+
* @param modelDir Directory containing the exported model artifacts.
|
| 81 |
+
* @returns Predicted public screen and safety labels.
|
| 82 |
+
*/
|
| 83 |
+
export async function classify(imagePath: string, modelDir = MODEL_DIR): Promise<{ screen: string; safety: string }> {
|
| 84 |
+
const classifier = await Classifier.create(modelDir);
|
| 85 |
+
if (imagePath.length === 0) {
|
| 86 |
+
throw new Error('Image path must not be empty.');
|
| 87 |
+
}
|
| 88 |
+
return classifier.classify(imagePath);
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
/**
|
| 92 |
+
* Classify a batch of images with a classifier loaded from disk.
|
| 93 |
+
*
|
| 94 |
+
* @param imagePaths Paths to image files.
|
| 95 |
+
* @param modelDir Directory containing the exported model artifacts.
|
| 96 |
+
* @returns Predicted public screen and safety labels for each image.
|
| 97 |
+
*/
|
| 98 |
+
export async function classifyBatch(
|
| 99 |
+
imagePaths: readonly string[],
|
| 100 |
+
modelDir = MODEL_DIR,
|
| 101 |
+
): Promise<Array<{ screen: string; safety: string }>> {
|
| 102 |
+
const classifier = await Classifier.create(modelDir);
|
| 103 |
+
if (imagePaths.length === 0) {
|
| 104 |
+
return [];
|
| 105 |
+
}
|
| 106 |
+
return classifier.classifyBatch(imagePaths);
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
async function preprocessImage(
|
| 110 |
+
imagePath: string,
|
| 111 |
+
preprocess: {
|
| 112 |
+
resize_longest_side_px: number;
|
| 113 |
+
mean: [number, number, number];
|
| 114 |
+
std: [number, number, number];
|
| 115 |
+
},
|
| 116 |
+
): Promise<{ data: Float32Array; height: number; width: number }> {
|
| 117 |
+
const { data, info: metadata } = await sharp(imagePath)
|
| 118 |
+
.rotate()
|
| 119 |
+
.resize({
|
| 120 |
+
width: preprocess.resize_longest_side_px,
|
| 121 |
+
height: preprocess.resize_longest_side_px,
|
| 122 |
+
fit: 'inside',
|
| 123 |
+
kernel: 'cubic',
|
| 124 |
+
})
|
| 125 |
+
.removeAlpha()
|
| 126 |
+
.toColourspace('srgb')
|
| 127 |
+
.raw()
|
| 128 |
+
.toBuffer({ resolveWithObject: true });
|
| 129 |
+
|
| 130 |
+
if (metadata.channels !== 3) {
|
| 131 |
+
throw new Error(`Expected RGB image data, got ${String(metadata.channels)} channels.`);
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
const pixels = metadata.width * metadata.height;
|
| 135 |
+
const tensor = new Float32Array(3 * pixels);
|
| 136 |
+
|
| 137 |
+
for (let pixel = 0; pixel < pixels; pixel += 1) {
|
| 138 |
+
const offset = pixel * 3;
|
| 139 |
+
tensor[pixel] = (channel(data, offset) / 255 - preprocess.mean[0]) / preprocess.std[0];
|
| 140 |
+
tensor[pixels + pixel] = (channel(data, offset + 1) / 255 - preprocess.mean[1]) / preprocess.std[1];
|
| 141 |
+
tensor[2 * pixels + pixel] = (channel(data, offset + 2) / 255 - preprocess.mean[2]) / preprocess.std[2];
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
return {
|
| 145 |
+
data: tensor,
|
| 146 |
+
height: metadata.height,
|
| 147 |
+
width: metadata.width,
|
| 148 |
+
};
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
function collateImages(
|
| 152 |
+
images: ReadonlyArray<{ data: Float32Array; height: number; width: number }>,
|
| 153 |
+
): ort.TypedTensor<'float32'> {
|
| 154 |
+
const height = Math.ceil(Math.max(...images.map((image) => image.height)) / PADDING_MULTIPLE) * PADDING_MULTIPLE;
|
| 155 |
+
const width = Math.ceil(Math.max(...images.map((image) => image.width)) / PADDING_MULTIPLE) * PADDING_MULTIPLE;
|
| 156 |
+
const imagePixels = height * width;
|
| 157 |
+
const tensor = new Float32Array(images.length * 3 * imagePixels);
|
| 158 |
+
|
| 159 |
+
for (let imageIndex = 0; imageIndex < images.length; imageIndex += 1) {
|
| 160 |
+
const image = imageAt(images, imageIndex);
|
| 161 |
+
const sourcePixels = image.height * image.width;
|
| 162 |
+
for (let channelIndex = 0; channelIndex < 3; channelIndex += 1) {
|
| 163 |
+
for (let row = 0; row < image.height; row += 1) {
|
| 164 |
+
const sourceStart = channelIndex * sourcePixels + row * image.width;
|
| 165 |
+
const targetStart = imageIndex * 3 * imagePixels + channelIndex * imagePixels + row * width;
|
| 166 |
+
tensor.set(image.data.subarray(sourceStart, sourceStart + image.width), targetStart);
|
| 167 |
+
}
|
| 168 |
+
}
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
return new ort.Tensor('float32', tensor, [images.length, 3, height, width]);
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
function decodePredictions(
|
| 175 |
+
screen: ort.TypedTensor<'float32'>,
|
| 176 |
+
safety: ort.TypedTensor<'float32'>,
|
| 177 |
+
labels: {
|
| 178 |
+
screen: { labels: string[] };
|
| 179 |
+
safety: { labels: string[] };
|
| 180 |
+
},
|
| 181 |
+
): Array<{ screen: string; safety: string }> {
|
| 182 |
+
// ONNX emits flat screen and safety logits.
|
| 183 |
+
const batchSize = tensorDim(screen, 0);
|
| 184 |
+
const screenClassCount = tensorDim(screen, 1);
|
| 185 |
+
const safetyBatchSize = tensorDim(safety, 0);
|
| 186 |
+
const safetyClassCount = tensorDim(safety, 1);
|
| 187 |
+
if (safetyBatchSize !== batchSize) {
|
| 188 |
+
throw new Error(
|
| 189 |
+
`Safety batch size ${String(safetyBatchSize)} does not match screen batch size ${String(batchSize)}.`,
|
| 190 |
+
);
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
const predictions: Array<{ screen: string; safety: string }> = [];
|
| 194 |
+
for (let row = 0; row < batchSize; row += 1) {
|
| 195 |
+
predictions.push({
|
| 196 |
+
screen: labelAt(labels.screen.labels, topIndex(screen.data, row * screenClassCount, screenClassCount)),
|
| 197 |
+
safety: labelAt(labels.safety.labels, topIndex(safety.data, row * safetyClassCount, safetyClassCount)),
|
| 198 |
+
});
|
| 199 |
+
}
|
| 200 |
+
return predictions;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
function outputTensor(output: ort.InferenceSession.ReturnType, name: string): ort.TypedTensor<'float32'> {
|
| 204 |
+
const tensor = output[name];
|
| 205 |
+
if (tensor === undefined) {
|
| 206 |
+
throw new Error(`Missing ONNX output "${name}".`);
|
| 207 |
+
}
|
| 208 |
+
if (tensor.type !== 'float32') {
|
| 209 |
+
throw new Error(`Expected "${name}" to be float32, got ${tensor.type}.`);
|
| 210 |
+
}
|
| 211 |
+
return tensor as ort.TypedTensor<'float32'>;
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
function tensorDim(tensor: ort.TypedTensor<'float32'>, index: number): number {
|
| 215 |
+
const dimension = tensor.dims[index];
|
| 216 |
+
if (typeof dimension !== 'number') {
|
| 217 |
+
throw new Error(`Missing tensor dimension ${String(index)}.`);
|
| 218 |
+
}
|
| 219 |
+
return dimension;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
function labelAt(labels: readonly string[], index: number): string {
|
| 223 |
+
const label = labels[index];
|
| 224 |
+
if (label === undefined) {
|
| 225 |
+
throw new Error(`Missing label for class ${String(index)}.`);
|
| 226 |
+
}
|
| 227 |
+
return label;
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
function topIndex(data: Float32Array, offset: number, count: number): number {
|
| 231 |
+
let top = 0;
|
| 232 |
+
let score = valueAt(data, offset);
|
| 233 |
+
for (let index = 1; index < count; index += 1) {
|
| 234 |
+
const candidate = valueAt(data, offset + index);
|
| 235 |
+
if (candidate > score) {
|
| 236 |
+
top = index;
|
| 237 |
+
score = candidate;
|
| 238 |
+
}
|
| 239 |
+
}
|
| 240 |
+
return top;
|
| 241 |
+
}
|
| 242 |
+
|
| 243 |
+
function imageAt(
|
| 244 |
+
images: ReadonlyArray<{ data: Float32Array; height: number; width: number }>,
|
| 245 |
+
index: number,
|
| 246 |
+
): { data: Float32Array; height: number; width: number } {
|
| 247 |
+
const image = images[index];
|
| 248 |
+
if (image === undefined) {
|
| 249 |
+
throw new Error(`Missing image at index ${String(index)}.`);
|
| 250 |
+
}
|
| 251 |
+
return image;
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
function valueAt(data: Float32Array, index: number): number {
|
| 255 |
+
const value = data[index];
|
| 256 |
+
if (value === undefined) {
|
| 257 |
+
throw new Error(`Missing tensor value at offset ${String(index)}.`);
|
| 258 |
+
}
|
| 259 |
+
return value;
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
function channel(data: Buffer, index: number): number {
|
| 263 |
+
const channelByte = data[index];
|
| 264 |
+
if (channelByte === undefined) {
|
| 265 |
+
throw new Error(`Missing image channel at offset ${String(index)}.`);
|
| 266 |
+
}
|
| 267 |
+
return channelByte;
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
const script = process.argv[1];
|
| 271 |
+
if (script !== undefined && import.meta.url === pathToFileURL(resolve(script)).href) {
|
| 272 |
+
const args = process.argv.slice(2);
|
| 273 |
+
const modelFlag = args.indexOf('--model-dir');
|
| 274 |
+
const modelDir = modelFlag >= 0 ? args[modelFlag + 1] : MODEL_DIR;
|
| 275 |
+
if (modelFlag >= 0) {
|
| 276 |
+
args.splice(modelFlag, 2);
|
| 277 |
+
}
|
| 278 |
+
if (args.length === 0 || modelDir === undefined) {
|
| 279 |
+
throw new Error('Usage: bun inference/typescript.ts <image...> [--model-dir export_dir]');
|
| 280 |
+
}
|
| 281 |
+
const predictions = await classifyBatch(args, modelDir);
|
| 282 |
+
process.stdout.write(`${JSON.stringify(predictions.length === 1 ? predictions[0] : predictions, null, 2)}\n`);
|
| 283 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d335efa9d3683c28fa2936ef9fdd75aa493482bb38cf624f39efcc81126ed8e
|
| 3 |
+
size 34197844
|
onnx/model.fp16.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:93e24db05bb256043c9b9cb64b177f0e1b4514340d8e92dfb24fa739040918bc
|
| 3 |
+
size 17432378
|
onnx/model.int8.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f1acefd4c5a1204c6c7b1db7bd8e31b59117982136379a60c4dae05d5798e155
|
| 3 |
+
size 9542131
|
onnx/model.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a9a7af13190c85f9ba3794de60cf00986942ecee92fd4ab879532b137c3de6dc
|
| 3 |
+
size 569419
|
onnx/model.onnx.data
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5577fd3b7f9e020044ef91d8ca710310304db065974783a1359be1458f4901c7
|
| 3 |
+
size 33751040
|
preprocess.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"crop": false,
|
| 3 |
+
"horizontal_flip": false,
|
| 4 |
+
"mean": [
|
| 5 |
+
0.485,
|
| 6 |
+
0.456,
|
| 7 |
+
0.406
|
| 8 |
+
],
|
| 9 |
+
"preserve_aspect_ratio": true,
|
| 10 |
+
"resize_longest_side_px": 1024,
|
| 11 |
+
"std": [
|
| 12 |
+
0.229,
|
| 13 |
+
0.224,
|
| 14 |
+
0.225
|
| 15 |
+
],
|
| 16 |
+
"stretch": false
|
| 17 |
+
}
|
train.json
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"augmentation": {
|
| 3 |
+
"artifact_codecs": [
|
| 4 |
+
"JPEG",
|
| 5 |
+
"WEBP"
|
| 6 |
+
],
|
| 7 |
+
"artifact_probability": 0.15,
|
| 8 |
+
"artifact_quality_max": 98,
|
| 9 |
+
"artifact_quality_min": 88,
|
| 10 |
+
"brightness_max": 1.1,
|
| 11 |
+
"brightness_min": 0.9,
|
| 12 |
+
"brightness_probability": 0.3,
|
| 13 |
+
"contrast_max": 1.1,
|
| 14 |
+
"contrast_min": 0.9,
|
| 15 |
+
"contrast_probability": 0.3
|
| 16 |
+
},
|
| 17 |
+
"counts": {
|
| 18 |
+
"test_safety": {
|
| 19 |
+
"hot": 1344,
|
| 20 |
+
"nsfw": 1559,
|
| 21 |
+
"safe": 20712
|
| 22 |
+
},
|
| 23 |
+
"test_screen": {
|
| 24 |
+
"audio": 111,
|
| 25 |
+
"calendar": 101,
|
| 26 |
+
"camera": 41,
|
| 27 |
+
"comments": 87,
|
| 28 |
+
"contacts": 33,
|
| 29 |
+
"email": 68,
|
| 30 |
+
"excel": 40,
|
| 31 |
+
"feed": 381,
|
| 32 |
+
"finances": 840,
|
| 33 |
+
"food": 285,
|
| 34 |
+
"gallery": 66,
|
| 35 |
+
"game": 330,
|
| 36 |
+
"generic": 3820,
|
| 37 |
+
"maps": 129,
|
| 38 |
+
"message-chat": 207,
|
| 39 |
+
"message-list": 38,
|
| 40 |
+
"notes": 59,
|
| 41 |
+
"other": 15549,
|
| 42 |
+
"post": 685,
|
| 43 |
+
"profile": 174,
|
| 44 |
+
"reading": 109,
|
| 45 |
+
"shopping": 381,
|
| 46 |
+
"streaming": 51,
|
| 47 |
+
"weather": 30
|
| 48 |
+
},
|
| 49 |
+
"train_safety": {
|
| 50 |
+
"hot": 14997,
|
| 51 |
+
"nsfw": 18086,
|
| 52 |
+
"safe": 234685
|
| 53 |
+
},
|
| 54 |
+
"train_screen": {
|
| 55 |
+
"audio": 1262,
|
| 56 |
+
"calendar": 1152,
|
| 57 |
+
"camera": 477,
|
| 58 |
+
"comments": 993,
|
| 59 |
+
"contacts": 374,
|
| 60 |
+
"email": 781,
|
| 61 |
+
"excel": 455,
|
| 62 |
+
"feed": 4323,
|
| 63 |
+
"finances": 9533,
|
| 64 |
+
"food": 3238,
|
| 65 |
+
"gallery": 753,
|
| 66 |
+
"game": 3748,
|
| 67 |
+
"generic": 43298,
|
| 68 |
+
"maps": 1468,
|
| 69 |
+
"message-chat": 2346,
|
| 70 |
+
"message-list": 442,
|
| 71 |
+
"notes": 678,
|
| 72 |
+
"other": 176223,
|
| 73 |
+
"post": 7773,
|
| 74 |
+
"profile": 1975,
|
| 75 |
+
"reading": 1246,
|
| 76 |
+
"shopping": 4324,
|
| 77 |
+
"streaming": 579,
|
| 78 |
+
"weather": 344
|
| 79 |
+
},
|
| 80 |
+
"val_safety": {
|
| 81 |
+
"hot": 1334,
|
| 82 |
+
"nsfw": 1696,
|
| 83 |
+
"safe": 20585
|
| 84 |
+
},
|
| 85 |
+
"val_screen": {
|
| 86 |
+
"audio": 111,
|
| 87 |
+
"calendar": 101,
|
| 88 |
+
"camera": 41,
|
| 89 |
+
"comments": 87,
|
| 90 |
+
"contacts": 33,
|
| 91 |
+
"email": 68,
|
| 92 |
+
"excel": 40,
|
| 93 |
+
"feed": 381,
|
| 94 |
+
"finances": 840,
|
| 95 |
+
"food": 285,
|
| 96 |
+
"gallery": 66,
|
| 97 |
+
"game": 330,
|
| 98 |
+
"generic": 3820,
|
| 99 |
+
"maps": 129,
|
| 100 |
+
"message-chat": 207,
|
| 101 |
+
"message-list": 38,
|
| 102 |
+
"notes": 59,
|
| 103 |
+
"other": 15549,
|
| 104 |
+
"post": 685,
|
| 105 |
+
"profile": 174,
|
| 106 |
+
"reading": 109,
|
| 107 |
+
"shopping": 381,
|
| 108 |
+
"streaming": 51,
|
| 109 |
+
"weather": 30
|
| 110 |
+
}
|
| 111 |
+
},
|
| 112 |
+
"dataset": {
|
| 113 |
+
"path": "output/dataset/phone-screenshots",
|
| 114 |
+
"repo": "yapwithai/phone-screenshots",
|
| 115 |
+
"safety_field": "safety",
|
| 116 |
+
"screen_field": "label"
|
| 117 |
+
},
|
| 118 |
+
"evaluation": {
|
| 119 |
+
"balanced_eval_max_per_class": 1000
|
| 120 |
+
},
|
| 121 |
+
"labels": {
|
| 122 |
+
"safety": [
|
| 123 |
+
"hot",
|
| 124 |
+
"nsfw",
|
| 125 |
+
"safe"
|
| 126 |
+
],
|
| 127 |
+
"screen": [
|
| 128 |
+
"audio",
|
| 129 |
+
"calendar",
|
| 130 |
+
"camera",
|
| 131 |
+
"comments",
|
| 132 |
+
"contacts",
|
| 133 |
+
"email",
|
| 134 |
+
"excel",
|
| 135 |
+
"feed",
|
| 136 |
+
"finances",
|
| 137 |
+
"food",
|
| 138 |
+
"gallery",
|
| 139 |
+
"game",
|
| 140 |
+
"generic",
|
| 141 |
+
"maps",
|
| 142 |
+
"message-chat",
|
| 143 |
+
"message-list",
|
| 144 |
+
"notes",
|
| 145 |
+
"other",
|
| 146 |
+
"post",
|
| 147 |
+
"profile",
|
| 148 |
+
"reading",
|
| 149 |
+
"shopping",
|
| 150 |
+
"streaming",
|
| 151 |
+
"weather"
|
| 152 |
+
]
|
| 153 |
+
},
|
| 154 |
+
"loss": {
|
| 155 |
+
"safety": "cross_entropy",
|
| 156 |
+
"safety_batch_probability": 0.35,
|
| 157 |
+
"safety_loss_weight": 0.5,
|
| 158 |
+
"screen": "cross_entropy"
|
| 159 |
+
},
|
| 160 |
+
"model": "timm/mobilenetv4_conv_medium.e250_r384_in12k",
|
| 161 |
+
"optimizer": {
|
| 162 |
+
"backbone_lr": 5.9999999999999995e-05,
|
| 163 |
+
"head_lr": 0.0003,
|
| 164 |
+
"lr": 0.0003,
|
| 165 |
+
"weight_decay": 0.05
|
| 166 |
+
},
|
| 167 |
+
"preprocess": {
|
| 168 |
+
"crop": false,
|
| 169 |
+
"horizontal_flip": false,
|
| 170 |
+
"mean": [
|
| 171 |
+
0.485,
|
| 172 |
+
0.456,
|
| 173 |
+
0.406
|
| 174 |
+
],
|
| 175 |
+
"preserve_aspect_ratio": true,
|
| 176 |
+
"resize_longest_side_px": 1024,
|
| 177 |
+
"std": [
|
| 178 |
+
0.229,
|
| 179 |
+
0.224,
|
| 180 |
+
0.225
|
| 181 |
+
],
|
| 182 |
+
"stretch": false
|
| 183 |
+
},
|
| 184 |
+
"sampling": {
|
| 185 |
+
"folded_screen_labels": {},
|
| 186 |
+
"min_train_count": 300,
|
| 187 |
+
"mode": "adaptive_label_aspect_bucketed",
|
| 188 |
+
"safety_max_repeat": 8,
|
| 189 |
+
"safety_target_ratio": 2.0,
|
| 190 |
+
"screen_max_repeat": 6,
|
| 191 |
+
"screen_target_ratio": 5.0
|
| 192 |
+
},
|
| 193 |
+
"schema": 3,
|
| 194 |
+
"training": {
|
| 195 |
+
"batch_size": 8,
|
| 196 |
+
"effective_batch_size": 64,
|
| 197 |
+
"epochs": 4,
|
| 198 |
+
"grad_accum_steps": 8,
|
| 199 |
+
"seed": 1337,
|
| 200 |
+
"target_effective_batch_size": 64,
|
| 201 |
+
"workers": 4
|
| 202 |
+
}
|
| 203 |
+
}
|