Download code/tt_dsocr/metrics.py from changh95/schift-ocr-1-beta: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/changh95/schift-ocr-1-beta/resolve/main/code/tt_dsocr/metrics.py
- Command line
-
hf download hf://changh95/schift-ocr-1-beta/code/tt_dsocr/metrics.py
-
curl -L -o metrics.py https://huggingface.co/changh95/schift-ocr-1-beta/resolve/main/code/tt_dsocr/metrics.py
1.56 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # Adapted from this workspace's GLM-OCR bundle (tt_glmocr/metrics.py, Apache-2.0). | |
| """Accuracy metrics of the gates and the smoke checks (pure Python; ``pcc`` takes torch tensors): edit distance, CER, | |
| token agreement, PCC.""" | |
| from __future__ import annotations | |
| from typing import Dict, Sequence | |
| def edit_distance(a: Sequence, b: Sequence) -> int: | |
| if len(a) < len(b): | |
| a, b = b, a | |
| prev = list(range(len(b) + 1)) | |
| for i, x in enumerate(a, 1): | |
| cur = [i] + [0] * len(b) | |
| for j, y in enumerate(b, 1): | |
| cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x != y)) | |
| prev = cur | |
| return prev[-1] | |
| def cer(hyp: str, ref: str) -> float: | |
| """Character error rate of hyp vs ref (edit distance / len(ref); 0 for two empty strings).""" | |
| if not ref: | |
| return 0.0 if not hyp else 1.0 | |
| return edit_distance(hyp, ref) / len(ref) | |
| def prefix_match(a: Sequence, b: Sequence) -> int: | |
| """Length of the common prefix of two token sequences (first divergence of a greedy run).""" | |
| n = 0 | |
| while n < min(len(a), len(b)) and a[n] == b[n]: | |
| n += 1 | |
| return n | |
| def pcc(a, b) -> float: | |
| a, b = a.double().flatten(), b.double().flatten() | |
| a, b = a - a.mean(), b - b.mean() | |
| return float((a @ b) / (a.norm() * b.norm() + 1e-30)) | |
| def summarize(xs: Sequence[float]) -> Dict[str, float]: | |
| s = sorted(xs) | |
| if not s: | |
| return {"n": 0} | |
| return {"n": len(s), "mean": sum(s) / len(s), "p95": s[int(0.95 * (len(s) - 1))], "max": s[-1]} | |