Datasets:
Add cls_degrees and Exact CLS metric
Browse files- README.md +51 -20
- data/test-00000-of-00001.parquet +2 -2
- dataset/metadata.json +0 -0
- scripts/build_parquet.py +2 -0
- scripts/evaluate.py +176 -28
- scripts/upload.py +58 -12
README.md
CHANGED
|
@@ -43,6 +43,8 @@ dataset_info:
|
|
| 43 |
dtype: float32
|
| 44 |
- name: orientation_degrees
|
| 45 |
dtype: int32
|
|
|
|
|
|
|
| 46 |
- name: font
|
| 47 |
dtype: string
|
| 48 |
- name: font_size
|
|
@@ -70,8 +72,8 @@ A compact, **deterministic**, bilingual (Chinese + English) synthetic OCR set:
|
|
| 70 |
**100 JPEGs**, **1,036 text lines**, about **26,456 characters**.
|
| 71 |
|
| 72 |
Fixed-seed regression images for a PaddleOCR-style detect → classify →
|
| 73 |
-
recognize pipeline. Official accuracy metrics: **Exact lines**
|
| 74 |
-
The same images also work for latency benches.
|
| 75 |
|
| 76 |
Generator: [`Sdcb.SimdPaddleOCR.TestData`](https://github.com/sdcb/SimdPaddleOCR/tree/master/test/Sdcb.SimdPaddleOCR.TestData)
|
| 77 |
in [sdcb/SimdPaddleOCR](https://github.com/sdcb/SimdPaddleOCR), seed `20260830`.
|
|
@@ -80,8 +82,8 @@ Mirrors: [Hugging Face](https://huggingface.co/datasets/sdcb/simdpaddleocr-datas
|
|
| 80 |
|
| 81 |
## 中文简介
|
| 82 |
|
| 83 |
-
固定种子生成的中英合成评测集,用来回归 PaddleOCR 式检测 + 识别流水线。
|
| 84 |
-
官方正确率
|
| 85 |
同一批图也可以用来测耗时。
|
| 86 |
|
| 87 |
## Preview
|
|
@@ -124,7 +126,8 @@ dotnet run --project test/Sdcb.SimdPaddleOCR.Tests -c Release -- --benchmark --i
|
|
| 124 |
- Unique text templates: 30 (sampled with replacement)
|
| 125 |
- Canvas: width 640–1792 px (mean 1233), height 480–1392 px (mean 928)
|
| 126 |
- Languages: Chinese and English, including mixed lines and digits
|
| 127 |
-
- Orientation: 0° × 628, 180° × 223, −90° × 100, 90° × 85
|
|
|
|
| 128 |
- Fonts used at render time (files are **not** redistributed):
|
| 129 |
`arial.ttf`, `calibri.ttf`, `times.ttf`, `segoeui.ttf`, `consola.ttf`,
|
| 130 |
`simhei.ttf`, `msyh.ttc`, `simsun.ttc`
|
|
@@ -155,7 +158,8 @@ Each `lines[]` item:
|
|
| 155 |
| `bbox` | int32[4] | axis-aligned `[x0, y0, x1, y1]`, top-left origin |
|
| 156 |
| `natural_width_at_height_48` | int32 | rendered width if the line height were 48 px (REC width hint) |
|
| 157 |
| `angle_degrees` | float32 | in-plane tilt, about −20° to +20° |
|
| 158 |
-
| `orientation_degrees` | int32 | `0`, `90`, `-90`, or `180` |
|
|
|
|
| 159 |
| `font` | string | font file name, e.g. `arial.ttf` |
|
| 160 |
| `font_size` | int32 | pixel size used by SkiaSharp |
|
| 161 |
| `color_rgb` | uint8[3] | ink color |
|
|
@@ -163,19 +167,25 @@ Each `lines[]` item:
|
|
| 163 |
`bbox` is the axis-aligned box after rotation (`[x0, y0, x1, y1]`).
|
| 164 |
Rotated or vertical text therefore occupies a larger rectangle than the ink.
|
| 165 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
The same records live in [`dataset/metadata.json`](dataset/metadata.json) for
|
| 167 |
tools that do not use `datasets`.
|
| 168 |
|
| 169 |
## Official accuracy metrics
|
| 170 |
|
| 171 |
-
|
| 172 |
-
[`BenchSummary
|
| 173 |
and mirrored in [`scripts/evaluate.py`](scripts/evaluate.py).
|
| 174 |
|
| 175 |
-
|
| 176 |
-
`metadata.json`. Predicted lines and GT lines are compared as
|
| 177 |
-
multisets** (order and boxes do not matter). Extra predictions
|
| 178 |
-
match a GT line are ignored.
|
|
|
|
|
|
|
| 179 |
|
| 180 |
### 1. Exact lines
|
| 181 |
|
|
@@ -191,7 +201,22 @@ exact_line_rate = exact_lines / total_gt_lines
|
|
| 191 |
This is the strict score: one missing character, a full-width digit, or a
|
| 192 |
split/merge of a line all count as a miss.
|
| 193 |
|
| 194 |
-
### 2.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 195 |
|
| 196 |
For every GT line that was **not** an exact match, take the minimum
|
| 197 |
Levenshtein distance to the remaining predictions (the closest leftover
|
|
@@ -206,16 +231,15 @@ char_acc = 1 - CER
|
|
| 206 |
CER is the soft score. It still credits a line that is almost right
|
| 207 |
(`128.50` vs `128.5`, one wrong CJK character, etc.).
|
| 208 |
|
| 209 |
-
### Alongside the
|
| 210 |
|
| 211 |
| Number | Meaning |
|
| 212 |
| --- | --- |
|
| 213 |
| `char_acc` | `1 - CER` |
|
| 214 |
| `exact_img` | Images whose every GT line was an exact match |
|
| 215 |
|
| 216 |
-
`
|
| 217 |
-
|
| 218 |
-
this protocol.
|
| 219 |
|
| 220 |
Latency (`mean ms/image`, images/s) is a separate bench on the same files.
|
| 221 |
|
|
@@ -226,7 +250,7 @@ which cut you used.
|
|
| 226 |
### Reference implementation
|
| 227 |
|
| 228 |
```python
|
| 229 |
-
# Same pairing rules as BenchSummary.ComputeAccuracy
|
| 230 |
def score_image(gt_lines: list[str], pred_lines: list[str]):
|
| 231 |
remaining = list(pred_lines)
|
| 232 |
exact = errors = chars = 0
|
|
@@ -247,8 +271,10 @@ def score_image(gt_lines: list[str], pred_lines: list[str]):
|
|
| 247 |
python scripts/evaluate.py predictions.json --metadata dataset/metadata.json
|
| 248 |
```
|
| 249 |
|
| 250 |
-
`predictions.json` may be `{ "img-001.jpg": ["...", "..."] }`
|
| 251 |
-
|
|
|
|
|
|
|
| 252 |
|
| 253 |
### Reported baseline
|
| 254 |
|
|
@@ -259,6 +285,11 @@ Ryzen 7 5800X, 2026-09-05 (warmup excluded, n=99):
|
|
| 259 |
- CER: 0.61% (`char_acc` 99.39%)
|
| 260 |
- Exact images: 43 / 99 (derived)
|
| 261 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
## How it was generated
|
| 263 |
|
| 264 |
```text
|
|
|
|
| 43 |
dtype: float32
|
| 44 |
- name: orientation_degrees
|
| 45 |
dtype: int32
|
| 46 |
+
- name: cls_degrees
|
| 47 |
+
dtype: int32
|
| 48 |
- name: font
|
| 49 |
dtype: string
|
| 50 |
- name: font_size
|
|
|
|
| 72 |
**100 JPEGs**, **1,036 text lines**, about **26,456 characters**.
|
| 73 |
|
| 74 |
Fixed-seed regression images for a PaddleOCR-style detect → classify →
|
| 75 |
+
recognize pipeline. Official accuracy metrics: **Exact lines**, **Exact CLS**,
|
| 76 |
+
and **CER**. The same images also work for latency benches.
|
| 77 |
|
| 78 |
Generator: [`Sdcb.SimdPaddleOCR.TestData`](https://github.com/sdcb/SimdPaddleOCR/tree/master/test/Sdcb.SimdPaddleOCR.TestData)
|
| 79 |
in [sdcb/SimdPaddleOCR](https://github.com/sdcb/SimdPaddleOCR), seed `20260830`.
|
|
|
|
| 82 |
|
| 83 |
## 中文简介
|
| 84 |
|
| 85 |
+
固定种子生成的中英合成评测集,用来回归 PaddleOCR 式检测 + 方向分类 + 识别流水线。
|
| 86 |
+
官方正确率三项:**Exact lines**(行级精确匹配)、**Exact CLS**(方向分类)和 **CER**(字符错误率)。
|
| 87 |
同一批图也可以用来测耗时。
|
| 88 |
|
| 89 |
## Preview
|
|
|
|
| 126 |
- Unique text templates: 30 (sampled with replacement)
|
| 127 |
- Canvas: width 640–1792 px (mean 1233), height 480–1392 px (mean 928)
|
| 128 |
- Languages: Chinese and English, including mixed lines and digits
|
| 129 |
+
- Orientation (world-space draw): 0° × 628, 180° × 223, −90° × 100, 90° × 85
|
| 130 |
+
- Required CLS after DET unwarp (`cls_degrees`): 0° × 728, 180° × 308
|
| 131 |
- Fonts used at render time (files are **not** redistributed):
|
| 132 |
`arial.ttf`, `calibri.ttf`, `times.ttf`, `segoeui.ttf`, `consola.ttf`,
|
| 133 |
`simhei.ttf`, `msyh.ttc`, `simsun.ttc`
|
|
|
|
| 158 |
| `bbox` | int32[4] | axis-aligned `[x0, y0, x1, y1]`, top-left origin |
|
| 159 |
| `natural_width_at_height_48` | int32 | rendered width if the line height were 48 px (REC width hint) |
|
| 160 |
| `angle_degrees` | float32 | in-plane tilt, about −20° to +20° |
|
| 161 |
+
| `orientation_degrees` | int32 | world-space draw: `0`, `90`, `-90`, or `180` |
|
| 162 |
+
| `cls_degrees` | int32 | required CLS after DET unwarp: `0` or `180` |
|
| 163 |
| `font` | string | font file name, e.g. `arial.ttf` |
|
| 164 |
| `font_size` | int32 | pixel size used by SkiaSharp |
|
| 165 |
| `color_rgb` | uint8[3] | ink color |
|
|
|
|
| 167 |
`bbox` is the axis-aligned box after rotation (`[x0, y0, x1, y1]`).
|
| 168 |
Rotated or vertical text therefore occupies a larger rectangle than the ink.
|
| 169 |
|
| 170 |
+
`cls_degrees` is the 0/180 label the classifier should emit **after** DET
|
| 171 |
+
perspective unwarp (and the 90° CW vertical-line correction). Map from
|
| 172 |
+
`orientation_degrees`: `0 → 0`, `180 → 180`, `90 → 180`, `−90 → 0`.
|
| 173 |
+
|
| 174 |
The same records live in [`dataset/metadata.json`](dataset/metadata.json) for
|
| 175 |
tools that do not use `datasets`.
|
| 176 |
|
| 177 |
## Official accuracy metrics
|
| 178 |
|
| 179 |
+
Three accuracy numbers are official. They are defined by
|
| 180 |
+
[`BenchSummary`](https://github.com/sdcb/SimdPaddleOCR/blob/master/test/Sdcb.SimdPaddleOCR.Tests/BenchSummary.cs)
|
| 181 |
and mirrored in [`scripts/evaluate.py`](scripts/evaluate.py).
|
| 182 |
|
| 183 |
+
Exact lines and CER are **line-text only**. Ground truth is the `text`
|
| 184 |
+
strings in `metadata.json`. Predicted lines and GT lines are compared as
|
| 185 |
+
**unordered multisets** (order and boxes do not matter). Extra predictions
|
| 186 |
+
that never match a GT line are ignored.
|
| 187 |
+
|
| 188 |
+
Exact CLS is a separate orientation score on `cls_degrees`.
|
| 189 |
|
| 190 |
### 1. Exact lines
|
| 191 |
|
|
|
|
| 201 |
This is the strict score: one missing character, a full-width digit, or a
|
| 202 |
split/merge of a line all count as a miss.
|
| 203 |
|
| 204 |
+
### 2. Exact CLS
|
| 205 |
+
|
| 206 |
+
A predicted line is paired to a GT line, then its applied rotation
|
| 207 |
+
(`0` or `180`) is compared to `cls_degrees`. Prefer AABB IoU ≥ 0.3 when
|
| 208 |
+
predicted boxes are present; otherwise pair by exact text. DET misses
|
| 209 |
+
(unpaired GT lines) are **excluded** from the denominator.
|
| 210 |
+
|
| 211 |
+
```text
|
| 212 |
+
exact_cls = paired lines whose rotation == cls_degrees
|
| 213 |
+
cls_total = paired lines
|
| 214 |
+
exact_cls_rate = exact_cls / cls_total
|
| 215 |
+
```
|
| 216 |
+
|
| 217 |
+
Text-only prediction files without `rotations` report `exact_cls=n/a`.
|
| 218 |
+
|
| 219 |
+
### 3. CER
|
| 220 |
|
| 221 |
For every GT line that was **not** an exact match, take the minimum
|
| 222 |
Levenshtein distance to the remaining predictions (the closest leftover
|
|
|
|
| 231 |
CER is the soft score. It still credits a line that is almost right
|
| 232 |
(`128.50` vs `128.5`, one wrong CJK character, etc.).
|
| 233 |
|
| 234 |
+
### Alongside the three scores
|
| 235 |
|
| 236 |
| Number | Meaning |
|
| 237 |
| --- | --- |
|
| 238 |
| `char_acc` | `1 - CER` |
|
| 239 |
| `exact_img` | Images whose every GT line was an exact match |
|
| 240 |
|
| 241 |
+
`orientation_degrees` is render metadata. Official CLS uses `cls_degrees`.
|
| 242 |
+
Detection IoU is only used to pair CLS, not to score DET.
|
|
|
|
| 243 |
|
| 244 |
Latency (`mean ms/image`, images/s) is a separate bench on the same files.
|
| 245 |
|
|
|
|
| 250 |
### Reference implementation
|
| 251 |
|
| 252 |
```python
|
| 253 |
+
# Same pairing rules as BenchSummary.ComputeAccuracy / ScoreCls
|
| 254 |
def score_image(gt_lines: list[str], pred_lines: list[str]):
|
| 255 |
remaining = list(pred_lines)
|
| 256 |
exact = errors = chars = 0
|
|
|
|
| 271 |
python scripts/evaluate.py predictions.json --metadata dataset/metadata.json
|
| 272 |
```
|
| 273 |
|
| 274 |
+
`predictions.json` may be `{ "img-001.jpg": ["...", "..."] }`,
|
| 275 |
+
`{ "img-001.jpg": { "texts": [...], "rotations": [...], "boxes": [...] } }`,
|
| 276 |
+
or a SimdPaddleOCR bench JSON (`rows[].file` / `rows[].texts` /
|
| 277 |
+
`rows[].rotations`).
|
| 278 |
|
| 279 |
### Reported baseline
|
| 280 |
|
|
|
|
| 285 |
- CER: 0.61% (`char_acc` 99.39%)
|
| 286 |
- Exact images: 43 / 99 (derived)
|
| 287 |
|
| 288 |
+
SimdPaddleOCR 1.4.2 `sharp` engine, PP-OCRv6 **tiny**, 4 workers, full 100
|
| 289 |
+
images (no warmup skip), `boxThreshold=0.4`:
|
| 290 |
+
|
| 291 |
+
- Exact CLS: 1,022 / 1,022 (100%) when DET pairs the line
|
| 292 |
+
|
| 293 |
## How it was generated
|
| 294 |
|
| 295 |
```text
|
data/test-00000-of-00001.parquet
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0e76592e354ae0f205fda8dd04eb5e6658062119f321aa093879638f7ed4a699
|
| 3 |
+
size 16339460
|
dataset/metadata.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
scripts/build_parquet.py
CHANGED
|
@@ -32,6 +32,7 @@ FEATURES = Features(
|
|
| 32 |
"natural_width_at_height_48": Value("int32"),
|
| 33 |
"angle_degrees": Value("float32"),
|
| 34 |
"orientation_degrees": Value("int32"),
|
|
|
|
| 35 |
"font": Value("string"),
|
| 36 |
"font_size": Value("int32"),
|
| 37 |
"color_rgb": Sequence(Value("uint8")),
|
|
@@ -60,6 +61,7 @@ def load_rows(dataset_dir: Path) -> list[dict]:
|
|
| 60 |
"natural_width_at_height_48": int(line["natural_width_at_height_48"]),
|
| 61 |
"angle_degrees": float(line["angle_degrees"]),
|
| 62 |
"orientation_degrees": int(line["orientation_degrees"]),
|
|
|
|
| 63 |
"font": line["font"],
|
| 64 |
"font_size": int(line["font_size"]),
|
| 65 |
"color_rgb": [int(v) for v in line["color_rgb"]],
|
|
|
|
| 32 |
"natural_width_at_height_48": Value("int32"),
|
| 33 |
"angle_degrees": Value("float32"),
|
| 34 |
"orientation_degrees": Value("int32"),
|
| 35 |
+
"cls_degrees": Value("int32"),
|
| 36 |
"font": Value("string"),
|
| 37 |
"font_size": Value("int32"),
|
| 38 |
"color_rgb": Sequence(Value("uint8")),
|
|
|
|
| 61 |
"natural_width_at_height_48": int(line["natural_width_at_height_48"]),
|
| 62 |
"angle_degrees": float(line["angle_degrees"]),
|
| 63 |
"orientation_degrees": int(line["orientation_degrees"]),
|
| 64 |
+
"cls_degrees": int(line["cls_degrees"]),
|
| 65 |
"font": line["font"],
|
| 66 |
"font_size": int(line["font_size"]),
|
| 67 |
"color_rgb": [int(v) for v in line["color_rgb"]],
|
scripts/evaluate.py
CHANGED
|
@@ -1,21 +1,38 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
-
"""Reference Exact-lines / CER scoring.
|
| 3 |
|
| 4 |
-
Matches SimdPaddleOCR BenchSummary
|
| 5 |
https://github.com/sdcb/SimdPaddleOCR/blob/master/test/Sdcb.SimdPaddleOCR.Tests/BenchSummary.cs
|
| 6 |
|
| 7 |
Predictions file: either
|
| 8 |
{ "img-001.jpg": ["line a", "line b"], ... }
|
| 9 |
-
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
from __future__ import annotations
|
| 13 |
|
| 14 |
import argparse
|
| 15 |
import json
|
|
|
|
| 16 |
from pathlib import Path
|
| 17 |
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
def levenshtein(a: str, b: str) -> int:
|
| 20 |
if a == b:
|
| 21 |
return 0
|
|
@@ -34,64 +51,188 @@ def levenshtein(a: str, b: str) -> int:
|
|
| 34 |
return previous[len(b)]
|
| 35 |
|
| 36 |
|
| 37 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
meta = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
-
|
|
|
|
| 46 |
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 47 |
if isinstance(payload, dict) and "rows" in payload:
|
| 48 |
-
predicted: dict[str, list[
|
| 49 |
for row in payload["rows"]:
|
| 50 |
if row.get("warmup"):
|
| 51 |
continue
|
| 52 |
file = row.get("file")
|
| 53 |
-
if file:
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
return predicted
|
| 56 |
if not isinstance(payload, dict):
|
| 57 |
raise ValueError("predictions must be an object or a bench JSON with rows")
|
| 58 |
-
return {key:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
|
|
|
|
| 62 |
exact_lines = 0
|
| 63 |
total_lines = 0
|
| 64 |
exact_images = 0
|
| 65 |
images = 0
|
| 66 |
errors = 0
|
| 67 |
total_chars = 0
|
|
|
|
|
|
|
| 68 |
|
| 69 |
for file, gt_lines in ground_truth.items():
|
| 70 |
if file not in predicted:
|
| 71 |
continue
|
| 72 |
-
|
| 73 |
images += 1
|
| 74 |
-
image_exact =
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
remaining.remove(expected)
|
| 80 |
-
exact_lines += 1
|
| 81 |
-
continue
|
| 82 |
-
image_exact = False
|
| 83 |
-
best = len(expected)
|
| 84 |
-
for actual in remaining:
|
| 85 |
-
best = min(best, levenshtein(expected, actual))
|
| 86 |
-
errors += best
|
| 87 |
if image_exact:
|
| 88 |
exact_images += 1
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
cer = (errors / total_chars) if total_chars else 0.0
|
| 91 |
return {
|
| 92 |
"exact_lines": exact_lines,
|
| 93 |
"total_lines": total_lines,
|
| 94 |
"exact_line_rate": exact_lines / total_lines if total_lines else 0.0,
|
|
|
|
|
|
|
|
|
|
| 95 |
"cer": cer,
|
| 96 |
"char_acc": 1.0 - cer,
|
| 97 |
"exact_img": exact_images,
|
|
@@ -112,9 +253,16 @@ def main() -> int:
|
|
| 112 |
args = parser.parse_args()
|
| 113 |
|
| 114 |
result = score(load_ground_truth(args.metadata), load_predictions(args.predictions))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
print(
|
| 116 |
f"exact_lines={result['exact_lines']}/{result['total_lines']} "
|
| 117 |
f"({result['exact_line_rate'] * 100:.2f}%) "
|
|
|
|
| 118 |
f"CER={result['cer'] * 100:.2f}% "
|
| 119 |
f"char_acc={result['char_acc'] * 100:.2f}% "
|
| 120 |
f"exact_img={result['exact_img']}/{result['images']}"
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
"""Reference Exact-lines / Exact CLS / CER scoring.
|
| 3 |
|
| 4 |
+
Matches SimdPaddleOCR BenchSummary:
|
| 5 |
https://github.com/sdcb/SimdPaddleOCR/blob/master/test/Sdcb.SimdPaddleOCR.Tests/BenchSummary.cs
|
| 6 |
|
| 7 |
Predictions file: either
|
| 8 |
{ "img-001.jpg": ["line a", "line b"], ... }
|
| 9 |
+
{ "img-001.jpg": { "texts": [...], "rotations": [...], "boxes": [...] }, ... }
|
| 10 |
+
or a SimdPaddleOCR bench JSON with rows[].file / rows[].texts /
|
| 11 |
+
rows[].rotations / rows[].warmup.
|
| 12 |
"""
|
| 13 |
|
| 14 |
from __future__ import annotations
|
| 15 |
|
| 16 |
import argparse
|
| 17 |
import json
|
| 18 |
+
from dataclasses import dataclass
|
| 19 |
from pathlib import Path
|
| 20 |
|
| 21 |
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class GtLine:
|
| 24 |
+
text: str
|
| 25 |
+
cls_degrees: int
|
| 26 |
+
bbox: list[int]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class PredLine:
|
| 31 |
+
text: str
|
| 32 |
+
rotation: int | None
|
| 33 |
+
box: list[float] | None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
def levenshtein(a: str, b: str) -> int:
|
| 37 |
if a == b:
|
| 38 |
return 0
|
|
|
|
| 51 |
return previous[len(b)]
|
| 52 |
|
| 53 |
|
| 54 |
+
def aabb_iou(ax0: float, ay0: float, ax1: float, ay1: float,
|
| 55 |
+
bx0: float, by0: float, bx1: float, by1: float) -> float:
|
| 56 |
+
ix0, iy0 = max(ax0, bx0), max(ay0, by0)
|
| 57 |
+
ix1, iy1 = min(ax1, bx1), min(ay1, by1)
|
| 58 |
+
iw, ih = ix1 - ix0, iy1 - iy0
|
| 59 |
+
if iw <= 0 or ih <= 0:
|
| 60 |
+
return 0.0
|
| 61 |
+
inter = iw * ih
|
| 62 |
+
area_a = max(0.0, ax1 - ax0) * max(0.0, ay1 - ay0)
|
| 63 |
+
area_b = max(0.0, bx1 - bx0) * max(0.0, by1 - by0)
|
| 64 |
+
union = area_a + area_b - inter
|
| 65 |
+
return inter / union if union > 0 else 0.0
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def load_ground_truth(metadata_path: Path) -> dict[str, list[GtLine]]:
|
| 69 |
meta = json.loads(metadata_path.read_text(encoding="utf-8"))
|
| 70 |
+
out: dict[str, list[GtLine]] = {}
|
| 71 |
+
for image in meta["images"]:
|
| 72 |
+
lines: list[GtLine] = []
|
| 73 |
+
for line in image["lines"]:
|
| 74 |
+
cls = int(line["cls_degrees"])
|
| 75 |
+
if cls not in (0, 180):
|
| 76 |
+
raise ValueError(f"{image['file']} cls_degrees must be 0 or 180, got {cls}")
|
| 77 |
+
bbox = [int(v) for v in line["bbox"]]
|
| 78 |
+
if len(bbox) < 4:
|
| 79 |
+
raise ValueError(f"{image['file']} bbox must have 4 values")
|
| 80 |
+
lines.append(GtLine(line["text"], cls, bbox))
|
| 81 |
+
out[image["file"]] = lines
|
| 82 |
+
return out
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _as_int_list(value, expected: int) -> list[int | None]:
|
| 86 |
+
if value is None:
|
| 87 |
+
return [None] * expected
|
| 88 |
+
items = list(value)
|
| 89 |
+
if len(items) != expected:
|
| 90 |
+
raise ValueError(f"expected {expected} rotations, got {len(items)}")
|
| 91 |
+
return [None if v is None else int(v) for v in items]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _as_box_list(value, expected: int) -> list[list[float] | None]:
|
| 95 |
+
if value is None:
|
| 96 |
+
return [None] * expected
|
| 97 |
+
items = list(value)
|
| 98 |
+
if len(items) != expected:
|
| 99 |
+
raise ValueError(f"expected {expected} boxes, got {len(items)}")
|
| 100 |
+
boxes: list[list[float] | None] = []
|
| 101 |
+
for item in items:
|
| 102 |
+
if item is None:
|
| 103 |
+
boxes.append(None)
|
| 104 |
+
continue
|
| 105 |
+
box = [float(v) for v in item]
|
| 106 |
+
boxes.append(box if len(box) >= 4 else None)
|
| 107 |
+
return boxes
|
| 108 |
+
|
| 109 |
|
| 110 |
+
def _pred_lines_from_value(value) -> list[PredLine]:
|
| 111 |
+
if isinstance(value, dict):
|
| 112 |
+
texts = list(value.get("texts") or [])
|
| 113 |
+
rotations = _as_int_list(value.get("rotations"), len(texts))
|
| 114 |
+
boxes = _as_box_list(value.get("boxes"), len(texts))
|
| 115 |
+
return [PredLine(texts[i], rotations[i], boxes[i]) for i in range(len(texts))]
|
| 116 |
+
texts = list(value)
|
| 117 |
+
return [PredLine(text, None, None) for text in texts]
|
| 118 |
|
| 119 |
+
|
| 120 |
+
def load_predictions(path: Path) -> dict[str, list[PredLine]]:
|
| 121 |
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 122 |
if isinstance(payload, dict) and "rows" in payload:
|
| 123 |
+
predicted: dict[str, list[PredLine]] = {}
|
| 124 |
for row in payload["rows"]:
|
| 125 |
if row.get("warmup"):
|
| 126 |
continue
|
| 127 |
file = row.get("file")
|
| 128 |
+
if not file:
|
| 129 |
+
continue
|
| 130 |
+
texts = list(row.get("texts") or [])
|
| 131 |
+
rotations = _as_int_list(row.get("rotations"), len(texts))
|
| 132 |
+
boxes = _as_box_list(row.get("boxes"), len(texts))
|
| 133 |
+
predicted[file] = [PredLine(texts[i], rotations[i], boxes[i]) for i in range(len(texts))]
|
| 134 |
return predicted
|
| 135 |
if not isinstance(payload, dict):
|
| 136 |
raise ValueError("predictions must be an object or a bench JSON with rows")
|
| 137 |
+
return {key: _pred_lines_from_value(value) for key, value in payload.items()}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def score_text(gt_lines: list[GtLine], pred_lines: list[PredLine]) -> tuple[int, int, int, bool]:
|
| 141 |
+
remaining = [p.text for p in pred_lines]
|
| 142 |
+
exact = errors = 0
|
| 143 |
+
image_exact = True
|
| 144 |
+
for expected in gt_lines:
|
| 145 |
+
if expected.text in remaining:
|
| 146 |
+
remaining.remove(expected.text)
|
| 147 |
+
exact += 1
|
| 148 |
+
continue
|
| 149 |
+
image_exact = False
|
| 150 |
+
best = len(expected.text)
|
| 151 |
+
for actual in remaining:
|
| 152 |
+
best = min(best, levenshtein(expected.text, actual))
|
| 153 |
+
errors += best
|
| 154 |
+
return exact, errors, sum(len(g.text) for g in gt_lines), image_exact
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def score_cls(gt_lines: list[GtLine], pred_lines: list[PredLine]) -> tuple[int, int]:
|
| 158 |
+
if not gt_lines or not pred_lines:
|
| 159 |
+
return 0, 0
|
| 160 |
+
if all(p.rotation is None for p in pred_lines):
|
| 161 |
+
return 0, 0
|
| 162 |
|
| 163 |
+
use_boxes = any(p.box is not None and len(p.box) >= 4 for p in pred_lines) and any(
|
| 164 |
+
g.bbox[2] > g.bbox[0] and g.bbox[3] > g.bbox[1] for g in gt_lines
|
| 165 |
+
)
|
| 166 |
+
if use_boxes:
|
| 167 |
+
pairs: list[tuple[int, int, float]] = []
|
| 168 |
+
for gi, g in enumerate(gt_lines):
|
| 169 |
+
for pi, p in enumerate(pred_lines):
|
| 170 |
+
if p.box is None or len(p.box) < 4:
|
| 171 |
+
continue
|
| 172 |
+
iou = aabb_iou(g.bbox[0], g.bbox[1], g.bbox[2], g.bbox[3],
|
| 173 |
+
p.box[0], p.box[1], p.box[2], p.box[3])
|
| 174 |
+
if iou >= 0.3:
|
| 175 |
+
pairs.append((gi, pi, iou))
|
| 176 |
+
pairs.sort(key=lambda item: item[2], reverse=True)
|
| 177 |
+
gt_used = [False] * len(gt_lines)
|
| 178 |
+
pred_used = [False] * len(pred_lines)
|
| 179 |
+
correct = total = 0
|
| 180 |
+
for gi, pi, _ in pairs:
|
| 181 |
+
if gt_used[gi] or pred_used[pi]:
|
| 182 |
+
continue
|
| 183 |
+
gt_used[gi] = pred_used[pi] = True
|
| 184 |
+
total += 1
|
| 185 |
+
if pred_lines[pi].rotation == gt_lines[gi].cls_degrees:
|
| 186 |
+
correct += 1
|
| 187 |
+
return correct, total
|
| 188 |
+
|
| 189 |
+
remaining = list(pred_lines)
|
| 190 |
+
correct = total = 0
|
| 191 |
+
for gt in gt_lines:
|
| 192 |
+
index = next((i for i, p in enumerate(remaining) if p.text == gt.text), -1)
|
| 193 |
+
if index < 0:
|
| 194 |
+
continue
|
| 195 |
+
total += 1
|
| 196 |
+
if remaining[index].rotation == gt.cls_degrees:
|
| 197 |
+
correct += 1
|
| 198 |
+
remaining.pop(index)
|
| 199 |
+
return correct, total
|
| 200 |
|
| 201 |
+
|
| 202 |
+
def score(ground_truth: dict[str, list[GtLine]], predicted: dict[str, list[PredLine]]) -> dict:
|
| 203 |
exact_lines = 0
|
| 204 |
total_lines = 0
|
| 205 |
exact_images = 0
|
| 206 |
images = 0
|
| 207 |
errors = 0
|
| 208 |
total_chars = 0
|
| 209 |
+
exact_cls = 0
|
| 210 |
+
cls_total = 0
|
| 211 |
|
| 212 |
for file, gt_lines in ground_truth.items():
|
| 213 |
if file not in predicted:
|
| 214 |
continue
|
| 215 |
+
pred_lines = predicted[file]
|
| 216 |
images += 1
|
| 217 |
+
exact, image_errors, chars, image_exact = score_text(gt_lines, pred_lines)
|
| 218 |
+
exact_lines += exact
|
| 219 |
+
total_lines += len(gt_lines)
|
| 220 |
+
errors += image_errors
|
| 221 |
+
total_chars += chars
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
if image_exact:
|
| 223 |
exact_images += 1
|
| 224 |
+
correct, total = score_cls(gt_lines, pred_lines)
|
| 225 |
+
exact_cls += correct
|
| 226 |
+
cls_total += total
|
| 227 |
|
| 228 |
cer = (errors / total_chars) if total_chars else 0.0
|
| 229 |
return {
|
| 230 |
"exact_lines": exact_lines,
|
| 231 |
"total_lines": total_lines,
|
| 232 |
"exact_line_rate": exact_lines / total_lines if total_lines else 0.0,
|
| 233 |
+
"exact_cls": exact_cls,
|
| 234 |
+
"cls_total": cls_total,
|
| 235 |
+
"exact_cls_rate": exact_cls / cls_total if cls_total else 0.0,
|
| 236 |
"cer": cer,
|
| 237 |
"char_acc": 1.0 - cer,
|
| 238 |
"exact_img": exact_images,
|
|
|
|
| 253 |
args = parser.parse_args()
|
| 254 |
|
| 255 |
result = score(load_ground_truth(args.metadata), load_predictions(args.predictions))
|
| 256 |
+
cls = (
|
| 257 |
+
f"exact_cls={result['exact_cls']}/{result['cls_total']} "
|
| 258 |
+
f"({result['exact_cls_rate'] * 100:.2f}%) "
|
| 259 |
+
if result["cls_total"]
|
| 260 |
+
else "exact_cls=n/a (no rotations) "
|
| 261 |
+
)
|
| 262 |
print(
|
| 263 |
f"exact_lines={result['exact_lines']}/{result['total_lines']} "
|
| 264 |
f"({result['exact_line_rate'] * 100:.2f}%) "
|
| 265 |
+
f"{cls}"
|
| 266 |
f"CER={result['cer'] * 100:.2f}% "
|
| 267 |
f"char_acc={result['char_acc'] * 100:.2f}% "
|
| 268 |
f"exact_img={result['exact_img']}/{result['images']}"
|
scripts/upload.py
CHANGED
|
@@ -1,17 +1,27 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
|
| 4 |
-
Requires:
|
|
|
|
|
|
|
| 5 |
"""
|
| 6 |
|
| 7 |
from __future__ import annotations
|
| 8 |
|
|
|
|
|
|
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
-
from huggingface_hub import HfApi
|
| 12 |
-
|
| 13 |
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
IGNORE = [
|
| 16 |
".venv/**",
|
| 17 |
".venv",
|
|
@@ -22,20 +32,56 @@ IGNORE = [
|
|
| 22 |
]
|
| 23 |
|
| 24 |
|
| 25 |
-
def
|
|
|
|
|
|
|
| 26 |
api = HfApi()
|
| 27 |
user = api.whoami()
|
| 28 |
-
print(f"logged in as {user['name']}")
|
| 29 |
-
url = api.create_repo(
|
| 30 |
-
print(f"repo {url}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
api.upload_folder(
|
|
|
|
| 32 |
folder_path=str(ROOT),
|
| 33 |
-
repo_id=REPO_ID,
|
| 34 |
repo_type="dataset",
|
|
|
|
| 35 |
ignore_patterns=IGNORE,
|
| 36 |
-
commit_message=
|
| 37 |
)
|
| 38 |
-
print(f"uploaded https://
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
return 0
|
| 40 |
|
| 41 |
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
+
"""Upload the dataset to Hugging Face and ModelScope.
|
| 3 |
|
| 4 |
+
Requires:
|
| 5 |
+
hf auth login
|
| 6 |
+
modelscope login (or MODELSCOPE_API_TOKEN)
|
| 7 |
"""
|
| 8 |
|
| 9 |
from __future__ import annotations
|
| 10 |
|
| 11 |
+
import argparse
|
| 12 |
+
import os
|
| 13 |
from pathlib import Path
|
| 14 |
|
|
|
|
|
|
|
| 15 |
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
HF_REPO = "sdcb/simdpaddleocr-dataset-v1"
|
| 17 |
+
MS_REPO = "sdflysha/simdpaddleocr-dataset-v1"
|
| 18 |
+
COMMIT = "Add cls_degrees and Exact CLS metric"
|
| 19 |
+
ALLOW = [
|
| 20 |
+
"README.md",
|
| 21 |
+
"dataset/**",
|
| 22 |
+
"data/**",
|
| 23 |
+
"scripts/*.py",
|
| 24 |
+
]
|
| 25 |
IGNORE = [
|
| 26 |
".venv/**",
|
| 27 |
".venv",
|
|
|
|
| 32 |
]
|
| 33 |
|
| 34 |
|
| 35 |
+
def upload_hf() -> None:
|
| 36 |
+
from huggingface_hub import HfApi
|
| 37 |
+
|
| 38 |
api = HfApi()
|
| 39 |
user = api.whoami()
|
| 40 |
+
print(f"HF logged in as {user['name']}")
|
| 41 |
+
url = api.create_repo(HF_REPO, repo_type="dataset", exist_ok=True, private=False)
|
| 42 |
+
print(f"HF repo {url}")
|
| 43 |
+
api.upload_folder(
|
| 44 |
+
folder_path=str(ROOT),
|
| 45 |
+
repo_id=HF_REPO,
|
| 46 |
+
repo_type="dataset",
|
| 47 |
+
allow_patterns=ALLOW,
|
| 48 |
+
ignore_patterns=IGNORE,
|
| 49 |
+
commit_message=COMMIT,
|
| 50 |
+
)
|
| 51 |
+
print(f"uploaded https://huggingface.co/datasets/{HF_REPO}")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def upload_ms() -> None:
|
| 55 |
+
from modelscope.hub.api import HubApi
|
| 56 |
+
|
| 57 |
+
token = os.environ.get("MODELSCOPE_API_TOKEN") or os.environ.get("MODELSCOPE_TOKEN")
|
| 58 |
+
api = HubApi()
|
| 59 |
+
if token:
|
| 60 |
+
api.login(token)
|
| 61 |
+
print(f"MS uploading {MS_REPO}")
|
| 62 |
api.upload_folder(
|
| 63 |
+
repo_id=MS_REPO,
|
| 64 |
folder_path=str(ROOT),
|
|
|
|
| 65 |
repo_type="dataset",
|
| 66 |
+
allow_patterns=ALLOW,
|
| 67 |
ignore_patterns=IGNORE,
|
| 68 |
+
commit_message=COMMIT,
|
| 69 |
)
|
| 70 |
+
print(f"uploaded https://www.modelscope.cn/datasets/{MS_REPO}")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def main() -> int:
|
| 74 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 75 |
+
parser.add_argument("--hf-only", action="store_true")
|
| 76 |
+
parser.add_argument("--ms-only", action="store_true")
|
| 77 |
+
args = parser.parse_args()
|
| 78 |
+
|
| 79 |
+
do_hf = not args.ms_only
|
| 80 |
+
do_ms = not args.hf_only
|
| 81 |
+
if do_hf:
|
| 82 |
+
upload_hf()
|
| 83 |
+
if do_ms:
|
| 84 |
+
upload_ms()
|
| 85 |
return 0
|
| 86 |
|
| 87 |
|