Upload folder using huggingface_hub
Browse files- README.md +80 -0
- config.json +26 -0
- model.onnx +3 -0
- omr_blindnet/__init__.py +11 -0
- omr_blindnet/architecture.py +91 -0
- omr_blindnet/cli.py +339 -0
- omr_blindnet/inference.py +90 -0
- omr_blindnet/preprocessing.py +106 -0
- omr_blindnet_v1.pt +3 -0
- publish_to_huggingface.py +48 -0
- pyproject.toml +24 -0
- train_omr_blindnet.py +347 -0
README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
tags:
|
| 4 |
+
- omr
|
| 5 |
+
- optical-mark-recognition
|
| 6 |
+
- image-classification
|
| 7 |
+
- computer-vision
|
| 8 |
+
- onnx
|
| 9 |
+
- pytorch
|
| 10 |
+
- education
|
| 11 |
+
library_name: onnxruntime
|
| 12 |
+
pipeline_tag: image-classification
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# OMR-BlindNet-v1 — Blind-Letter Deep Residual CNN for OMR Grading
|
| 16 |
+
|
| 17 |
+
**OMR-BlindNet-v1** is a lightweight, high-accuracy **4-Channel Residual Squeeze-and-Excitation Convolutional Neural Network** trained specifically for real-world MCQ OMR sheets (including red, maroon, blue, green, and black-and-white printed forms).
|
| 18 |
+
|
| 19 |
+
Instead of requiring students to shade 100% of every circle perfectly, **OMR-BlindNet-v1** detects whether the printed option letter (`A`, `B`, `C`, `D`, `E`) inside a bubble has been **blinded / occluded** by student ink — whether via full shading, partial center fill, hurried center dot, tick (`✓`), cross (`×`), slanted scribble, or pencil shading — while cleanly ignoring unoccluded printed red/black letters, shadows, faint erasures, and tiny stray rim dots. **Double/multiple marks in one MCQ are automatically flagged as WRONG.**
|
| 20 |
+
|
| 21 |
+
## Architecture
|
| 22 |
+
|
| 23 |
+
- **Input**: `(batch, 4, 32, 32)` `float32` tensor:
|
| 24 |
+
- Channel `0`: Normalized Red (`R / 255`) — suppresses red/maroon printed OMR forms
|
| 25 |
+
- Channel `1`: Normalized Green (`G / 255`)
|
| 26 |
+
- Channel `2`: Normalized Blue (`B / 255`)
|
| 27 |
+
- Channel `3`: Local background-subtracted **Dark-Ink Occlusion Map** (`[0, 1]`)
|
| 28 |
+
- **Backbone**: Stem Conv (`4→32`) + 3 Residual Squeeze-Excitation stages (`32→64→128→192`) + Dual Avg/Max Pooling (`384→96→1`)
|
| 29 |
+
- **Size**: ~1.7 MB ONNX (`model.onnx`), runs 240 bubbles (~60 MCQs) in **~15 ms on CPU** (no PyTorch required at inference time!)
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## Terminal Quickstart (For Any User)
|
| 34 |
+
|
| 35 |
+
Install the package locally or directly from your published repo:
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
pip install ./omr-blindnet-hf
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Run directly from your terminal on any OMR PDF or image:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
# Detect answers on a single OMR sheet image
|
| 45 |
+
omr-blindnet check student_sheet.jpg
|
| 46 |
+
|
| 47 |
+
# Grade a multi-page exam PDF against an Answer Key and export CSV
|
| 48 |
+
omr-blindnet check exam_batch.pdf --key "1:D,2:C,3:C,4:B,5:B" --out results.csv
|
| 49 |
+
|
| 50 |
+
# Load the model directly from Hugging Face Hub once published
|
| 51 |
+
omr-blindnet check exam_batch.pdf --model YOUR_USERNAME/omr-blindnet-v1 --key key.json
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Python API
|
| 55 |
+
|
| 56 |
+
```python
|
| 57 |
+
import cv2
|
| 58 |
+
from omr_blindnet import OMRBlindNetONNX
|
| 59 |
+
|
| 60 |
+
model = OMRBlindNetONNX.from_pretrained("YOUR_USERNAME/omr-blindnet-v1")
|
| 61 |
+
sheet = cv2.imread("student_sheet.jpg")
|
| 62 |
+
# List of (cx, cy, radius) bubble centers
|
| 63 |
+
probs = model.predict_bubbles_on_sheet(sheet, [(233, 650, 27), (299, 650, 27)])
|
| 64 |
+
print("Blinded probabilities:", probs)
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
---
|
| 68 |
+
|
| 69 |
+
## Publishing to Hugging Face Hub
|
| 70 |
+
|
| 71 |
+
1. Install Hugging Face CLI & login:
|
| 72 |
+
```bash
|
| 73 |
+
pip install huggingface_hub
|
| 74 |
+
huggingface-cli login
|
| 75 |
+
```
|
| 76 |
+
2. Create a repo (e.g., `YOUR_USERNAME/omr-blindnet-v1`) and upload this entire `omr-blindnet-hf/` directory:
|
| 77 |
+
```bash
|
| 78 |
+
huggingface-cli upload YOUR_USERNAME/omr-blindnet-v1 ./omr-blindnet-hf . --repo-type model
|
| 79 |
+
```
|
| 80 |
+
Anyone can then download and run `OMR-BlindNet-v1` directly from their terminal!
|
config.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "omr_blindnet",
|
| 3 |
+
"model_name": "OMR-BlindNet-v1",
|
| 4 |
+
"version": "1.0.0",
|
| 5 |
+
"architecture": "ResidualSE-CNN (4ch 32x32 -> 32/64/128/192 -> Avg+MaxPool -> 96 -> 1)",
|
| 6 |
+
"task": "blind-letter-omr-bubble-classification",
|
| 7 |
+
"input_shape": [
|
| 8 |
+
"batch_size",
|
| 9 |
+
4,
|
| 10 |
+
32,
|
| 11 |
+
32
|
| 12 |
+
],
|
| 13 |
+
"input_channels": [
|
| 14 |
+
"R_norm",
|
| 15 |
+
"G_norm",
|
| 16 |
+
"B_norm",
|
| 17 |
+
"DarkInkOcclusion"
|
| 18 |
+
],
|
| 19 |
+
"output": "blind_logit (apply sigmoid; >= 0.50 = letter blinded / marked)",
|
| 20 |
+
"double_answer_policy": "Multiple blinded circles in one MCQ count as WRONG",
|
| 21 |
+
"parameters": 933985,
|
| 22 |
+
"training_samples": 18000,
|
| 23 |
+
"validation_accuracy": 100.0,
|
| 24 |
+
"trained_at": "2026-11-18T13:19:39.594894+00:00",
|
| 25 |
+
"elapsed_sec": 229.9
|
| 26 |
+
}
|
model.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8bc33536b52710b49d8e480ac2227c8bd1b2f452dd6c6ac36f45254c7408450f
|
| 3 |
+
size 3742092
|
omr_blindnet/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OMR-BlindNet: Deep Residual CNN for Blind-Letter & Optical Mark Detection."""
|
| 2 |
+
|
| 3 |
+
from .preprocessing import extract_4ch_bubble_tensor, extract_4ch_batch_from_sheet
|
| 4 |
+
from .inference import OMRBlindNetONNX
|
| 5 |
+
|
| 6 |
+
__version__ = "1.0.0"
|
| 7 |
+
__all__ = [
|
| 8 |
+
"OMRBlindNetONNX",
|
| 9 |
+
"extract_4ch_bubble_tensor",
|
| 10 |
+
"extract_4ch_batch_from_sheet",
|
| 11 |
+
]
|
omr_blindnet/architecture.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SqueezeExcite(nn.Module):
|
| 8 |
+
"""Channel attention block so the CNN dynamically adapts to red/blue/green/B&W OMR forms."""
|
| 9 |
+
|
| 10 |
+
def __init__(self, channels: int, reduction: int = 4):
|
| 11 |
+
super().__init__()
|
| 12 |
+
mid = max(8, channels // reduction)
|
| 13 |
+
self.fc = nn.Sequential(
|
| 14 |
+
nn.AdaptiveAvgPool2d(1),
|
| 15 |
+
nn.Flatten(),
|
| 16 |
+
nn.Linear(channels, mid),
|
| 17 |
+
nn.SiLU(inplace=True),
|
| 18 |
+
nn.Linear(mid, channels),
|
| 19 |
+
nn.Sigmoid(),
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 23 |
+
w = self.fc(x).unsqueeze(-1).unsqueeze(-1)
|
| 24 |
+
return x * w
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class ResidualSEBlock(nn.Module):
|
| 28 |
+
def __init__(self, in_ch: int, out_ch: int, stride: int = 1):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.conv1 = nn.Conv2d(in_ch, out_ch, kernel_size=3, stride=stride, padding=1, bias=False)
|
| 31 |
+
self.bn1 = nn.BatchNorm2d(out_ch)
|
| 32 |
+
self.act = nn.SiLU(inplace=True)
|
| 33 |
+
self.conv2 = nn.Conv2d(out_ch, out_ch, kernel_size=3, stride=1, padding=1, bias=False)
|
| 34 |
+
self.bn2 = nn.BatchNorm2d(out_ch)
|
| 35 |
+
self.se = SqueezeExcite(out_ch)
|
| 36 |
+
self.shortcut = (
|
| 37 |
+
nn.Sequential(
|
| 38 |
+
nn.Conv2d(in_ch, out_ch, kernel_size=1, stride=stride, bias=False),
|
| 39 |
+
nn.BatchNorm2d(out_ch),
|
| 40 |
+
)
|
| 41 |
+
if (stride != 1 or in_ch != out_ch)
|
| 42 |
+
else nn.Identity()
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 46 |
+
out = self.act(self.bn1(self.conv1(x)))
|
| 47 |
+
out = self.bn2(self.conv2(out))
|
| 48 |
+
out = self.se(out)
|
| 49 |
+
return self.act(out + self.shortcut(x))
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class OMRBlindNet(nn.Module):
|
| 53 |
+
"""
|
| 54 |
+
OMR-BlindNet-v1: Deep Residual Squeeze-Excitation CNN (~430K params) specifically
|
| 55 |
+
designed to classify whether the printed option letter (A/B/C/D/E) inside an OMR
|
| 56 |
+
bubble is BLINDED / OCCLUDED by student ink (full fill, partial center blob, tick,
|
| 57 |
+
cross, scribble, or pencil shade) vs UNOCCLUDED (empty circle with visible letter).
|
| 58 |
+
|
| 59 |
+
Input: (N, 4, 32, 32) float32 tensor [R, G, B, DarkInkOcclusion]
|
| 60 |
+
Output: (N, 1) logit (apply sigmoid -> probability of letter being blinded/marked)
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, in_channels: int = 4, dropout: float = 0.25):
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.stem = nn.Sequential(
|
| 66 |
+
nn.Conv2d(in_channels, 32, kernel_size=3, stride=1, padding=1, bias=False),
|
| 67 |
+
nn.BatchNorm2d(32),
|
| 68 |
+
nn.SiLU(inplace=True),
|
| 69 |
+
)
|
| 70 |
+
self.stage1 = ResidualSEBlock(32, 64, stride=2) # 32x32 -> 16x16
|
| 71 |
+
self.stage2 = ResidualSEBlock(64, 128, stride=2) # 16x16 -> 8x8
|
| 72 |
+
self.stage3 = ResidualSEBlock(128, 192, stride=2) # 8x8 -> 4x4
|
| 73 |
+
|
| 74 |
+
self.avg_pool = nn.AdaptiveAvgPool2d(1)
|
| 75 |
+
self.max_pool = nn.AdaptiveMaxPool2d(1)
|
| 76 |
+
self.head = nn.Sequential(
|
| 77 |
+
nn.Flatten(),
|
| 78 |
+
nn.Dropout(dropout),
|
| 79 |
+
nn.Linear(192 * 2, 96),
|
| 80 |
+
nn.SiLU(inplace=True),
|
| 81 |
+
nn.Dropout(dropout * 0.5),
|
| 82 |
+
nn.Linear(96, 1),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 86 |
+
x = self.stem(x)
|
| 87 |
+
x = self.stage1(x)
|
| 88 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
import re
|
| 8 |
+
import sys
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Dict, List, Tuple
|
| 11 |
+
|
| 12 |
+
import cv2
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pymupdf as fitz
|
| 15 |
+
|
| 16 |
+
from .inference import OMRBlindNetONNX
|
| 17 |
+
from .preprocessing import compute_dark_ink_channel
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _default_model_path() -> Path:
|
| 21 |
+
here = Path(__file__).resolve().parent.parent
|
| 22 |
+
if (here / "model.onnx").exists():
|
| 23 |
+
return here / "model.onnx"
|
| 24 |
+
return Path("model.onnx")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _parse_key(key_str: str) -> Dict[str, str]:
|
| 28 |
+
ans: Dict[str, str] = {}
|
| 29 |
+
if not key_str:
|
| 30 |
+
return ans
|
| 31 |
+
p = Path(key_str)
|
| 32 |
+
if p.exists() and p.is_file():
|
| 33 |
+
key_str = p.read_text(encoding="utf-8")
|
| 34 |
+
try:
|
| 35 |
+
loaded = json.loads(key_str)
|
| 36 |
+
if isinstance(loaded, dict):
|
| 37 |
+
return {str(k).upper(): str(v).upper() for k, v in loaded.items()}
|
| 38 |
+
except Exception:
|
| 39 |
+
pass
|
| 40 |
+
pairs = re.findall(r"(?:Q)?(\d+)\s*[:=\-]\s*([A-Ea-e])", key_str)
|
| 41 |
+
if pairs:
|
| 42 |
+
for num, opt in pairs:
|
| 43 |
+
ans[f"Q{int(num)}"] = opt.upper()
|
| 44 |
+
return ans
|
| 45 |
+
letters = [c for c in key_str.upper() if c in "ABCDE"]
|
| 46 |
+
for idx, ch in enumerate(letters, start=1):
|
| 47 |
+
ans[f"Q{idx}"] = ch
|
| 48 |
+
return ans
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _load_pages(path: Path, dpi: int = 200) -> List[np.ndarray]:
|
| 52 |
+
if path.suffix.lower() == ".pdf":
|
| 53 |
+
doc = fitz.open(str(path))
|
| 54 |
+
mat = fitz.Matrix(dpi / 72.0, dpi / 72.0)
|
| 55 |
+
pages = []
|
| 56 |
+
try:
|
| 57 |
+
for page in doc:
|
| 58 |
+
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB, alpha=False)
|
| 59 |
+
img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 3)
|
| 60 |
+
pages.append(cv2.cvtColor(img, cv2.COLOR_RGB2BGR))
|
| 61 |
+
finally:
|
| 62 |
+
doc.close()
|
| 63 |
+
return pages
|
| 64 |
+
img = cv2.imread(str(path))
|
| 65 |
+
if img is None:
|
| 66 |
+
raise FileNotFoundError(f"Could not read image: {path}")
|
| 67 |
+
return [img]
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _auto_detect_grid(bgr: np.ndarray) -> Tuple[np.ndarray, List[Tuple[str, List[Tuple[str, float, float, float]]]]]:
|
| 71 |
+
"""Self-contained zero-config deskewing + lattice-fitting MCQ bubble grid discoverer."""
|
| 72 |
+
h, w = bgr.shape[:2]
|
| 73 |
+
tw = 1654
|
| 74 |
+
th = int(round(h * (tw / float(w))))
|
| 75 |
+
img = cv2.resize(bgr, (tw, th), interpolation=cv2.INTER_AREA if w > tw else cv2.INTER_CUBIC)
|
| 76 |
+
|
| 77 |
+
def find_circles(im: np.ndarray):
|
| 78 |
+
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
| 79 |
+
ink = compute_dark_ink_channel(im)
|
| 80 |
+
block = max(25, (min(im.shape[:2]) // 48) | 1)
|
| 81 |
+
m1 = cv2.adaptiveThreshold(cv2.GaussianBlur(gray, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block, 8)
|
| 82 |
+
m2 = cv2.adaptiveThreshold(cv2.GaussianBlur(ink, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block, 22)
|
| 83 |
+
min_d, max_d = tw * 0.014, tw * 0.052
|
| 84 |
+
raw = []
|
| 85 |
+
for mask in (m1, m2):
|
| 86 |
+
cnts, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
|
| 87 |
+
for c in cnts:
|
| 88 |
+
x, y, bw, bh = cv2.boundingRect(c)
|
| 89 |
+
if bw < min_d or bh < min_d or bw > max_d or bh > max_d:
|
| 90 |
+
continue
|
| 91 |
+
if not (0.74 <= bw / float(bh) <= 1.35):
|
| 92 |
+
continue
|
| 93 |
+
area = cv2.contourArea(c)
|
| 94 |
+
peri = cv2.arcLength(c, True)
|
| 95 |
+
if peri <= 0 or area < bw * bh * 0.42:
|
| 96 |
+
continue
|
| 97 |
+
circ = 4.0 * math.pi * area / (peri * peri)
|
| 98 |
+
if circ < 0.62:
|
| 99 |
+
continue
|
| 100 |
+
raw.append((x + bw * 0.5, y + bh * 0.5, (bw + bh) * 0.25, area * circ))
|
| 101 |
+
raw.sort(key=lambda t: -t[3])
|
| 102 |
+
kept = []
|
| 103 |
+
for cx, cy, r, _ in raw:
|
| 104 |
+
if all((cx - kx) ** 2 + (cy - ky) ** 2 >= (max(r, kr) * 0.85) ** 2 for kx, ky, kr in kept):
|
| 105 |
+
kept.append((cx, cy, r))
|
| 106 |
+
if not kept:
|
| 107 |
+
return [], 0.0
|
| 108 |
+
radii = np.array([t[2] for t in kept], dtype=np.float32)
|
| 109 |
+
r_med = float(np.median(radii))
|
| 110 |
+
kept = [(cx, cy, r) for cx, cy, r in kept if abs(r - r_med) <= max(4.0, r_med * 0.26)]
|
| 111 |
+
return kept, r_med
|
| 112 |
+
|
| 113 |
+
def modal_gap(vals: List[float], lo: float, hi: float) -> float:
|
| 114 |
+
arr = np.array([v for v in vals if lo <= v <= hi], dtype=np.float32)
|
| 115 |
+
if len(arr) == 0:
|
| 116 |
+
return 0.0
|
| 117 |
+
if len(arr) < 5:
|
| 118 |
+
return float(np.median(arr))
|
| 119 |
+
counts, edges = np.histogram(arr, bins=max(8, int(round((hi - lo) / 2.0))), range=(lo, hi))
|
| 120 |
+
b = int(np.argmax(counts))
|
| 121 |
+
peak = 0.5 * (edges[b] + edges[b + 1])
|
| 122 |
+
close = arr[np.abs(arr - peak) <= max(4.0, peak * 0.14)]
|
| 123 |
+
return float(np.median(close)) if len(close) > 0 else float(np.median(arr))
|
| 124 |
+
|
| 125 |
+
bubs, r_med = find_circles(img)
|
| 126 |
+
if len(bubs) < 12 or r_med <= 0:
|
| 127 |
+
return img, []
|
| 128 |
+
|
| 129 |
+
# Auto-deskew from vertical/horizontal neighbor pairs
|
| 130 |
+
pts = np.array([(b[0], b[1]) for b in bubs], dtype=np.float32)
|
| 131 |
+
angs = []
|
| 132 |
+
for i in range(len(pts)):
|
| 133 |
+
dx = pts[:, 0] - pts[i, 0]
|
| 134 |
+
dy = pts[:, 1] - pts[i, 1]
|
| 135 |
+
for j in np.where((dx > r_med * 1.6) & (dx < r_med * 4.5) & (np.abs(dy) < r_med * 0.65))[0]:
|
| 136 |
+
angs.append(math.degrees(math.atan2(float(dy[j]), float(dx[j]))))
|
| 137 |
+
for j in np.where((dy > r_med * 1.8) & (dy < r_med * 6.5) & (np.abs(dx) < r_med * 0.75))[0]:
|
| 138 |
+
angs.append(-math.degrees(math.atan2(float(dx[j]), float(dy[j]))))
|
| 139 |
+
if len(angs) >= 10:
|
| 140 |
+
ang = float(np.median(angs))
|
| 141 |
+
if 0.06 <= abs(ang) <= 12.0:
|
| 142 |
+
M = cv2.getRotationMatrix2D((tw * 0.5, th * 0.5), ang, 1.0)
|
| 143 |
+
img = cv2.warpAffine(img, M, (tw, th), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
|
| 144 |
+
bubs, r_med = find_circles(img)
|
| 145 |
+
|
| 146 |
+
bubs.sort(key=lambda t: (t[1], t[0]))
|
| 147 |
+
bands = []
|
| 148 |
+
for b in bubs:
|
| 149 |
+
placed = False
|
| 150 |
+
for bd in bands:
|
| 151 |
+
if abs(b[1] - sum(p[1] for p in bd) / len(bd)) <= r_med * 0.85:
|
| 152 |
+
bd.append(b)
|
| 153 |
+
placed = True
|
| 154 |
+
break
|
| 155 |
+
if not placed:
|
| 156 |
+
bands.append([b])
|
| 157 |
+
bands = [sorted(bd, key=lambda t: t[0]) for bd in bands if len(bd) >= 3]
|
| 158 |
+
opt_gap = modal_gap([bd[i + 1][0] - bd[i][0] for bd in bands for i in range(len(bd) - 1)], r_med * 1.75, r_med * 4.8)
|
| 159 |
+
if opt_gap <= 0:
|
| 160 |
+
return img, []
|
| 161 |
+
|
| 162 |
+
runs = []
|
| 163 |
+
for bd in bands:
|
| 164 |
+
cur = [bd[0]]
|
| 165 |
+
for b in bd[1:]:
|
| 166 |
+
if b[0] - cur[-1][0] <= opt_gap * 1.42:
|
| 167 |
+
cur.append(b)
|
| 168 |
+
else:
|
| 169 |
+
if len(cur) >= 3:
|
| 170 |
+
runs.append(cur)
|
| 171 |
+
cur = [b]
|
| 172 |
+
if len(cur) >= 3:
|
| 173 |
+
runs.append(cur)
|
| 174 |
+
|
| 175 |
+
len_cnt: Dict[int, int] = {}
|
| 176 |
+
for rn in runs:
|
| 177 |
+
if 3 <= len(rn) <= 5:
|
| 178 |
+
len_cnt[len(rn)] = len_cnt.get(len(rn), 0) + 1
|
| 179 |
+
if not len_cnt:
|
| 180 |
+
return img, []
|
| 181 |
+
k_opts = max(len_cnt, key=lambda k: (len_cnt[k], 1 if k in (4, 5) else 0))
|
| 182 |
+
opt_letters = ["A", "B", "C", "D", "E"][:k_opts]
|
| 183 |
+
|
| 184 |
+
cols = []
|
| 185 |
+
for rn in sorted([r for r in runs if len(r) == k_opts], key=lambda r: r[0][0]):
|
| 186 |
+
placed = False
|
| 187 |
+
for cl in cols:
|
| 188 |
+
if abs(rn[0][0] - sum(r[0][0] for r in cl) / len(cl)) <= max(r_med * 1.25, opt_gap * 0.55):
|
| 189 |
+
cl.append(rn)
|
| 190 |
+
placed = True
|
| 191 |
+
break
|
| 192 |
+
if not placed:
|
| 193 |
+
cols.append([rn])
|
| 194 |
+
cols = sorted([c for c in cols if len(c) >= 3], key=lambda c: sum(r[0][0] for r in c) / len(c))
|
| 195 |
+
if not cols:
|
| 196 |
+
return img, []
|
| 197 |
+
|
| 198 |
+
all_dy = []
|
| 199 |
+
for cl in cols:
|
| 200 |
+
ys = sorted(sum(p[1] for p in r) / len(r) for r in cl)
|
| 201 |
+
for i in range(len(ys) - 1):
|
| 202 |
+
all_dy.append(ys[i + 1] - ys[i])
|
| 203 |
+
row_gap_global = modal_gap(all_dy, r_med * 1.8, r_med * 8.5)
|
| 204 |
+
if row_gap_global <= 0:
|
| 205 |
+
return img, []
|
| 206 |
+
|
| 207 |
+
# Lattice-fit every column block (recovers rows with heavily scribbled/merged bubbles!)
|
| 208 |
+
questions: List[Tuple[str, List[Tuple[str, float, float, float]]]] = []
|
| 209 |
+
q_num = 1
|
| 210 |
+
for cl in cols:
|
| 211 |
+
cx0 = float(np.median([r[0][0] for r in cl]))
|
| 212 |
+
c_gap = float(np.median([(r[-1][0] - r[0][0]) / float(k_opts - 1) for r in cl]))
|
| 213 |
+
col_b = [b for b in bubs if cx0 - r_med * 1.1 <= b[0] <= cx0 + (k_opts - 1) * c_gap + r_med * 1.1]
|
| 214 |
+
col_rows = []
|
| 215 |
+
for b in sorted(col_b, key=lambda t: t[1]):
|
| 216 |
+
placed = False
|
| 217 |
+
for grp in col_rows:
|
| 218 |
+
if abs(b[1] - sum(p[1] for p in grp) / len(grp)) <= r_med * 0.85:
|
| 219 |
+
grp.append(b)
|
| 220 |
+
placed = True
|
| 221 |
+
break
|
| 222 |
+
if not placed:
|
| 223 |
+
col_rows.append([b])
|
| 224 |
+
valid_ys = sorted(
|
| 225 |
+
float(np.mean([p[1] for p in grp]))
|
| 226 |
+
for grp in col_rows
|
| 227 |
+
if sum(1 for bx, _, _ in grp if 0 <= round((bx - cx0) / max(c_gap, 1.0)) < k_opts) >= 2
|
| 228 |
+
)
|
| 229 |
+
if len(valid_ys) < 2:
|
| 230 |
+
continue
|
| 231 |
+
best_chain, cur_chain = [], [valid_ys[0]]
|
| 232 |
+
for y in valid_ys[1:]:
|
| 233 |
+
if y - cur_chain[-1] <= row_gap_global * 1.38:
|
| 234 |
+
cur_chain.append(y)
|
| 235 |
+
else:
|
| 236 |
+
if len(cur_chain) > len(best_chain):
|
| 237 |
+
best_chain = cur_chain
|
| 238 |
+
cur_chain = [y]
|
| 239 |
+
if len(cur_chain) > len(best_chain):
|
| 240 |
+
best_chain = cur_chain
|
| 241 |
+
if len(best_chain) < 2:
|
| 242 |
+
continue
|
| 243 |
+
|
| 244 |
+
ks = np.array([round((y - best_chain[0]) / row_gap_global) for y in best_chain], dtype=np.float64)
|
| 245 |
+
slope, intercept = np.polyfit(ks, np.array(best_chain, dtype=np.float64), 1)
|
| 246 |
+
row_count = int(round(ks[-1])) + 1
|
| 247 |
+
|
| 248 |
+
slot_xs = [
|
| 249 |
+
(int(round((bx - cx0) / max(c_gap, 1.0))), bx)
|
| 250 |
+
for bx, by, _ in col_b
|
| 251 |
+
if intercept - r_med * 1.1 <= by <= intercept + (row_count - 1) * slope + r_med * 1.1
|
| 252 |
+
and 0 <= int(round((bx - cx0) / max(c_gap, 1.0))) < k_opts
|
| 253 |
+
and abs(bx - (cx0 + int(round((bx - cx0) / max(c_gap, 1.0))) * c_gap)) <= r_med * 0.7
|
| 254 |
+
]
|
| 255 |
+
if len(slot_xs) >= k_opts * 2:
|
| 256 |
+
c_gap, cx0 = np.polyfit([p[0] for p in slot_xs], [p[1] for p in slot_xs], 1)
|
| 257 |
+
|
| 258 |
+
for r_i in range(row_count):
|
| 259 |
+
ry = float(intercept + r_i * slope)
|
| 260 |
+
questions.append(
|
| 261 |
+
(f"Q{q_num}", [(opt_letters[o_i], float(cx0 + o_i * c_gap), ry, r_med) for o_i in range(k_opts)])
|
| 262 |
+
)
|
| 263 |
+
q_num += 1
|
| 264 |
+
return img, questions
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main(argv: List[str] | None = None) -> int:
|
| 268 |
+
parser = argparse.ArgumentParser(
|
| 269 |
+
prog="omr-blindnet",
|
| 270 |
+
description="OMR-BlindNet-v1 CLI: Blind-Letter Deep CNN OMR Sheet Grader (Double Answer = WRONG)",
|
| 271 |
+
)
|
| 272 |
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
| 273 |
+
|
| 274 |
+
p_check = sub.add_parser("check", help="Grade a single image or multi-page OMR PDF")
|
| 275 |
+
p_check.add_argument("input", help="Path to OMR PDF or image (.pdf/.jpg/.png)")
|
| 276 |
+
p_check.add_argument("--key", default="", help="Answer key string (e.g. '1:D,2:C,3:C' or 'DCCBB...') or JSON file")
|
| 277 |
+
p_check.add_argument("--model", default=str(_default_model_path()), help="Local model.onnx path or Hugging Face repo id")
|
| 278 |
+
p_check.add_argument("--threshold", type=float, default=0.50, help="Blind-letter probability threshold (default 0.50)")
|
| 279 |
+
p_check.add_argument("--out", default="", help="Optional CSV output path")
|
| 280 |
+
|
| 281 |
+
p_info = sub.add_parser("info", help="Show model card metadata & local ONNX status")
|
| 282 |
+
p_info.add_argument("--model", default=str(_default_model_path()), help="Path to model.onnx or HF repo id")
|
| 283 |
+
|
| 284 |
+
args = parser.parse_args(argv)
|
| 285 |
+
model = OMRBlindNetONNX.from_pretrained(args.model, threshold=getattr(args, "threshold", 0.50))
|
| 286 |
+
|
| 287 |
+
if args.cmd == "info":
|
| 288 |
+
print(json.dumps({"model_path": str(model.model_path), "config": model.config}, indent=2))
|
| 289 |
+
return 0
|
| 290 |
+
|
| 291 |
+
answer_key = _parse_key(args.key)
|
| 292 |
+
pages = _load_pages(Path(args.input))
|
| 293 |
+
print(f"[OMR-BlindNet-v1] Loaded {len(pages)} page(s) from {args.input}")
|
| 294 |
+
|
| 295 |
+
rows_out = []
|
| 296 |
+
for p_idx, bgr in enumerate(pages):
|
| 297 |
+
img, questions = _auto_detect_grid(bgr)
|
| 298 |
+
flat_coords = [(cx, cy, r) for _, opts in questions for _, cx, cy, r in opts]
|
| 299 |
+
probs = model.predict_bubbles_on_sheet(img, flat_coords)
|
| 300 |
+
|
| 301 |
+
correct = wrong = multi = blank = 0
|
| 302 |
+
cursor = 0
|
| 303 |
+
page_answers = {}
|
| 304 |
+
for qlbl, opts in questions:
|
| 305 |
+
marked = []
|
| 306 |
+
for opt, _, _, _ in opts:
|
| 307 |
+
if float(probs[cursor]) >= model.threshold:
|
| 308 |
+
marked.append(opt)
|
| 309 |
+
cursor += 1
|
| 310 |
+
page_answers[qlbl] = marked
|
| 311 |
+
exp = answer_key.get(qlbl)
|
| 312 |
+
if exp:
|
| 313 |
+
if len(marked) == 0:
|
| 314 |
+
blank += 1
|
| 315 |
+
elif len(marked) > 1:
|
| 316 |
+
multi += 1 # Double/multi answer NOT allowed -> counted as WRONG
|
| 317 |
+
elif marked[0] == exp:
|
| 318 |
+
correct += 1
|
| 319 |
+
else:
|
| 320 |
+
wrong += 1
|
| 321 |
+
|
| 322 |
+
marked_summary = {q: "+".join(v) for q, v in page_answers.items() if v}
|
| 323 |
+
if answer_key:
|
| 324 |
+
print(f"Page {p_idx + 1}: Score={correct}/{len(answer_key)} | Correct={correct} Wrong={wrong} Multi(Wrong)={multi} Blank={blank}")
|
| 325 |
+
else:
|
| 326 |
+
print(f"Page {p_idx + 1}: Detected {len(marked_summary)} answered / {len(questions)} MCQs -> {marked_summary}")
|
| 327 |
+
rows_out.append({"page": p_idx + 1, "correct": correct, "wrong": wrong, "multi_wrong": multi, "blank": blank, "answers": json.dumps(marked_summary)})
|
| 328 |
+
|
| 329 |
+
if args.out:
|
| 330 |
+
with open(args.out, "w", newline="", encoding="utf-8") as f:
|
| 331 |
+
w = csv.DictWriter(f, fieldnames=["page", "correct", "wrong", "multi_wrong", "blank", "answers"])
|
| 332 |
+
w.writeheader()
|
| 333 |
+
w.writerows(rows_out)
|
| 334 |
+
print(f"Saved results to {args.out}")
|
| 335 |
+
return 0
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
if __name__ == "__main__":
|
| 339 |
+
raise SystemExit(main())
|
omr_blindnet/inference.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import math
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import cv2
|
| 9 |
+
import numpy as np
|
| 10 |
+
import onnxruntime as ort
|
| 11 |
+
|
| 12 |
+
from .preprocessing import CNN_INPUT_SIZE, extract_4ch_batch_from_sheet
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class OMRBlindNetONNX:
|
| 16 |
+
"""
|
| 17 |
+
Standalone ONNX Runtime inference engine for OMR-BlindNet-v1.
|
| 18 |
+
Runs 100% locally without PyTorch — ideal for Hugging Face Hub distribution,
|
| 19 |
+
CLI tools, edge devices, and high-speed batch PDF grading.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, model_path: str | Path, threshold: float = 0.50):
|
| 23 |
+
self.model_path = Path(model_path)
|
| 24 |
+
if not self.model_path.exists():
|
| 25 |
+
raise FileNotFoundError(f"ONNX model not found: {self.model_path}")
|
| 26 |
+
self.threshold = float(threshold)
|
| 27 |
+
opts = ort.SessionOptions()
|
| 28 |
+
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
|
| 29 |
+
self.session = ort.InferenceSession(
|
| 30 |
+
str(self.model_path),
|
| 31 |
+
sess_options=opts,
|
| 32 |
+
providers=["CPUExecutionProvider"],
|
| 33 |
+
)
|
| 34 |
+
self.input_name = self.session.get_inputs()[0].name
|
| 35 |
+
self.output_name = self.session.get_outputs()[0].name
|
| 36 |
+
|
| 37 |
+
cfg_path = self.model_path.parent / "config.json"
|
| 38 |
+
self.config: Dict[str, Any] = (
|
| 39 |
+
json.loads(cfg_path.read_text(encoding="utf-8")) if cfg_path.exists() else {}
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
@classmethod
|
| 43 |
+
def from_pretrained(
|
| 44 |
+
cls,
|
| 45 |
+
repo_id_or_dir: str | Path,
|
| 46 |
+
filename: str = "model.onnx",
|
| 47 |
+
threshold: float = 0.50,
|
| 48 |
+
) -> "OMRBlindNetONNX":
|
| 49 |
+
"""
|
| 50 |
+
Load OMR-BlindNet either from a local folder or directly from Hugging Face Hub!
|
| 51 |
+
Example:
|
| 52 |
+
model = OMRBlindNetONNX.from_pretrained("your-username/omr-blindnet-v1")
|
| 53 |
+
"""
|
| 54 |
+
local = Path(repo_id_or_dir)
|
| 55 |
+
if local.is_file():
|
| 56 |
+
return cls(local, threshold=threshold)
|
| 57 |
+
if (local / filename).exists():
|
| 58 |
+
return cls(local / filename, threshold=threshold)
|
| 59 |
+
try:
|
| 60 |
+
from huggingface_hub import hf_hub_download
|
| 61 |
+
except ImportError as exc:
|
| 62 |
+
raise ImportError(
|
| 63 |
+
"Install huggingface_hub (`pip install huggingface_hub`) to download models from Hugging Face."
|
| 64 |
+
) from exc
|
| 65 |
+
downloaded = hf_hub_download(repo_id=str(repo_id_or_dir), filename=filename)
|
| 66 |
+
try:
|
| 67 |
+
hf_hub_download(repo_id=str(repo_id_or_dir), filename="config.json")
|
| 68 |
+
except Exception:
|
| 69 |
+
pass
|
| 70 |
+
return cls(downloaded, threshold=threshold)
|
| 71 |
+
|
| 72 |
+
def predict_tensors(self, x: np.ndarray) -> np.ndarray:
|
| 73 |
+
"""Run ONNX CNN inference on (N, 4, 32, 32) float32 tensor -> (N,) probabilities in [0, 1]."""
|
| 74 |
+
if x.shape[0] == 0:
|
| 75 |
+
return np.empty((0,), dtype=np.float32)
|
| 76 |
+
logits = self.session.run(
|
| 77 |
+
[self.output_name],
|
| 78 |
+
{self.input_name: np.ascontiguousarray(x, dtype=np.float32)},
|
| 79 |
+
)[0].reshape(-1)
|
| 80 |
+
probs = 1.0 / (1.0 + np.exp(-np.clip(logits, -20.0, 20.0)))
|
| 81 |
+
return probs.astype(np.float32)
|
| 82 |
+
|
| 83 |
+
def predict_bubbles_on_sheet(
|
| 84 |
+
self,
|
| 85 |
+
bgr_sheet: np.ndarray,
|
| 86 |
+
bubbles: List[Tuple[float, float, float]],
|
| 87 |
+
) -> np.ndarray:
|
| 88 |
+
"""Extract 4-channel crops for all (cx, cy, r) bubbles and return blind-letter probabilities."""
|
| 89 |
+
batch = extract_4ch_batch_from_sheet(bgr_sheet, bubbles)
|
| 90 |
+
return self.predict_tensors(batch)
|
omr_blindnet/preprocessing.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Iterable, Tuple
|
| 4 |
+
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
CNN_INPUT_SIZE = 32
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def compute_dark_ink_channel(bgr: np.ndarray) -> np.ndarray:
|
| 13 |
+
"""
|
| 14 |
+
Produce a color-suppressed dark-ink grayscale image where colored printed
|
| 15 |
+
form lines & A/B/C/D letters (red/maroon/orange/blue/green) are suppressed
|
| 16 |
+
while student pen/pencil ink covering a letter stays intensely dark.
|
| 17 |
+
"""
|
| 18 |
+
b, g, r = cv2.split(bgr)
|
| 19 |
+
sat_red = float(np.mean(r.astype(np.float32) - b.astype(np.float32)))
|
| 20 |
+
if sat_red > 6.5:
|
| 21 |
+
return r
|
| 22 |
+
gray = cv2.cvtColor(bgr, cv2.COLOR_BGR2GRAY)
|
| 23 |
+
max_ch = np.maximum(np.maximum(b, g), r)
|
| 24 |
+
return cv2.addWeighted(gray, 0.55, max_ch, 0.45, 0)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def extract_4ch_bubble_tensor(
|
| 28 |
+
bgr_sheet: np.ndarray,
|
| 29 |
+
cx: float,
|
| 30 |
+
cy: float,
|
| 31 |
+
radius: float,
|
| 32 |
+
ink_sheet: np.ndarray | None = None,
|
| 33 |
+
) -> np.ndarray:
|
| 34 |
+
"""
|
| 35 |
+
Extract a normalized 4-channel (4, 32, 32) float32 tensor centered on a single bubble:
|
| 36 |
+
- Ch 0: Red channel / 255.0 (suppresses red printed A/B/C/D letters!)
|
| 37 |
+
- Ch 1: Green channel / 255.0
|
| 38 |
+
- Ch 2: Blue channel / 255.0
|
| 39 |
+
- Ch 3: Local background-subtracted dark-ink occlusion map in [0, 1]
|
| 40 |
+
(0 = clean paper / unoccluded letter, 1 = heavy student ink blinding the letter)
|
| 41 |
+
"""
|
| 42 |
+
h, w = bgr_sheet.shape[:2]
|
| 43 |
+
r = max(6.0, float(radius))
|
| 44 |
+
half = int(round(r * 1.30))
|
| 45 |
+
ix, iy = int(round(cx)), int(round(cy))
|
| 46 |
+
|
| 47 |
+
# Pad safely if near border
|
| 48 |
+
x0, x1 = ix - half, ix + half + 1
|
| 49 |
+
y0, y1 = iy - half, iy + half + 1
|
| 50 |
+
pad_l = max(0, -x0)
|
| 51 |
+
pad_t = max(0, -y0)
|
| 52 |
+
pad_r = max(0, x1 - w)
|
| 53 |
+
pad_b = max(0, y1 - h)
|
| 54 |
+
|
| 55 |
+
cx0, cx1 = max(0, x0), min(w, x1)
|
| 56 |
+
cy0, cy1 = max(0, y0), min(h, y1)
|
| 57 |
+
crop_bgr = bgr_sheet[cy0:cy1, cx0:cx1]
|
| 58 |
+
if crop_bgr.size == 0:
|
| 59 |
+
return np.zeros((4, CNN_INPUT_SIZE, CNN_INPUT_SIZE), dtype=np.float32)
|
| 60 |
+
|
| 61 |
+
if pad_l or pad_t or pad_r or pad_b:
|
| 62 |
+
crop_bgr = cv2.copyMakeBorder(
|
| 63 |
+
crop_bgr, pad_t, pad_b, pad_l, pad_r, cv2.BORDER_REPLICATE
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
crop_rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB)
|
| 67 |
+
rgb_32 = cv2.resize(crop_rgb, (CNN_INPUT_SIZE, CNN_INPUT_SIZE), interpolation=cv2.INTER_AREA)
|
| 68 |
+
rgb_norm = rgb_32.astype(np.float32) / 255.0 # (32, 32, 3)
|
| 69 |
+
|
| 70 |
+
if ink_sheet is not None:
|
| 71 |
+
crop_ink = ink_sheet[cy0:cy1, cx0:cx1]
|
| 72 |
+
if pad_l or pad_t or pad_r or pad_b:
|
| 73 |
+
crop_ink = cv2.copyMakeBorder(
|
| 74 |
+
crop_ink, pad_t, pad_b, pad_l, pad_r, cv2.BORDER_REPLICATE
|
| 75 |
+
)
|
| 76 |
+
else:
|
| 77 |
+
crop_ink = compute_dark_ink_channel(crop_bgr)
|
| 78 |
+
|
| 79 |
+
ink_32 = cv2.resize(crop_ink, (CNN_INPUT_SIZE, CNN_INPUT_SIZE), interpolation=cv2.INTER_AREA).astype(np.float32)
|
| 80 |
+
# Estimate local paper brightness from outer border pixels of the 32x32 crop
|
| 81 |
+
border = np.concatenate([ink_32[0, :], ink_32[-1, :], ink_32[:, 0], ink_32[:, -1]])
|
| 82 |
+
local_paper = max(130.0, float(np.percentile(border, 80)))
|
| 83 |
+
# Ink occlusion map: high where student ink darkens below local paper level
|
| 84 |
+
occ = np.clip((local_paper - ink_32) / local_paper, 0.0, 1.0)
|
| 85 |
+
|
| 86 |
+
tensor = np.empty((4, CNN_INPUT_SIZE, CNN_INPUT_SIZE), dtype=np.float32)
|
| 87 |
+
tensor[0] = rgb_norm[:, :, 0]
|
| 88 |
+
tensor[1] = rgb_norm[:, :, 1]
|
| 89 |
+
tensor[2] = rgb_norm[:, :, 2]
|
| 90 |
+
tensor[3] = occ
|
| 91 |
+
return tensor
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def extract_4ch_batch_from_sheet(
|
| 95 |
+
bgr_sheet: np.ndarray,
|
| 96 |
+
bubbles: Iterable[Tuple[float, float, float]],
|
| 97 |
+
) -> np.ndarray:
|
| 98 |
+
"""Extract a (N, 4, 32, 32) float32 tensor batch for all bubbles on a sheet."""
|
| 99 |
+
ink_sheet = compute_dark_ink_channel(bgr_sheet)
|
| 100 |
+
tensors = [
|
| 101 |
+
extract_4ch_bubble_tensor(bgr_sheet, cx, cy, rad, ink_sheet=ink_sheet)
|
| 102 |
+
for cx, cy, rad in bubbles
|
| 103 |
+
]
|
| 104 |
+
if not tensors:
|
| 105 |
+
return np.empty((0, 4, CNN_INPUT_SIZE, CNN_INPUT_SIZE), dtype=np.float32)
|
| 106 |
+
return np.stack(tensors, axis=0).astype(np.float32)
|
omr_blindnet_v1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:84789c916b0e7ff42400b1392cc2a6a55cc8b49e059929598bbbbead8ec111a6
|
| 3 |
+
size 3771407
|
publish_to_huggingface.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
One-command Hugging Face Model Hub uploader for OMR-BlindNet-v1.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
pip install huggingface_hub
|
| 6 |
+
huggingface-cli login
|
| 7 |
+
python publish_to_huggingface.py YOUR_HF_USERNAME/omr-blindnet-v1
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def main() -> int:
|
| 16 |
+
if len(sys.argv) < 2:
|
| 17 |
+
print("Usage: python publish_to_huggingface.py <YOUR_HF_USERNAME/omr-blindnet-v1>")
|
| 18 |
+
return 1
|
| 19 |
+
|
| 20 |
+
repo_id = sys.argv[1].strip()
|
| 21 |
+
try:
|
| 22 |
+
from huggingface_hub import HfApi
|
| 23 |
+
except ImportError:
|
| 24 |
+
print("Please install huggingface_hub first: pip install huggingface_hub")
|
| 25 |
+
return 1
|
| 26 |
+
|
| 27 |
+
folder = Path(__file__).resolve().parent
|
| 28 |
+
if not (folder / "model.onnx").exists():
|
| 29 |
+
print("Error: model.onnx not found. Run train_omr_blindnet.py first.")
|
| 30 |
+
return 1
|
| 31 |
+
|
| 32 |
+
api = HfApi()
|
| 33 |
+
api.create_repo(repo_id=repo_id, repo_type="model", exist_ok=True)
|
| 34 |
+
print(f"Uploading {folder} to https://huggingface.co/{repo_id} ...")
|
| 35 |
+
api.upload_folder(
|
| 36 |
+
folder_path=str(folder),
|
| 37 |
+
repo_id=repo_id,
|
| 38 |
+
repo_type="model",
|
| 39 |
+
ignore_patterns=["__pycache__", "*.egg-info", "*.pyc"],
|
| 40 |
+
)
|
| 41 |
+
print(f"\nPublished successfully! Share with any user:")
|
| 42 |
+
print(f" https://huggingface.co/{repo_id}")
|
| 43 |
+
print(f" omr-blindnet check exam.pdf --model {repo_id} --key \"1:D,2:C,3:C\"")
|
| 44 |
+
return 0
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
raise SystemExit(main())
|
pyproject.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=68.0"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "omr-blindnet"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "OMR-BlindNet-v1: Deep Residual CNN for Blind-Letter OMR Mark Detection (ONNX + Hugging Face Ready)"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.9"
|
| 11 |
+
dependencies = [
|
| 12 |
+
"onnxruntime>=1.18.0",
|
| 13 |
+
"opencv-python-headless>=4.9.0",
|
| 14 |
+
"numpy>=1.26.0",
|
| 15 |
+
"pymupdf>=1.24.0",
|
| 16 |
+
"huggingface_hub>=0.23.0",
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
[project.scripts]
|
| 20 |
+
omr-blindnet = "omr_blindnet.cli:main"
|
| 21 |
+
|
| 22 |
+
[tool.setuptools.packages.find]
|
| 23 |
+
where = ["."]
|
| 24 |
+
include = ["omr_blindnet*"]
|
train_omr_blindnet.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 6 |
+
from datetime import datetime, timezone
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Tuple
|
| 9 |
+
|
| 10 |
+
import cv2
|
| 11 |
+
import numpy as np
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 15 |
+
|
| 16 |
+
THIS_DIR = Path(__file__).resolve().parent
|
| 17 |
+
sys.path.insert(0, str(THIS_DIR))
|
| 18 |
+
|
| 19 |
+
from omr_blindnet.architecture import OMRBlindNet
|
| 20 |
+
from omr_blindnet.inference import OMRBlindNetONNX
|
| 21 |
+
from omr_blindnet.preprocessing import CNN_INPUT_SIZE, extract_4ch_bubble_tensor
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def synthesize_blind_letter_dataset(
|
| 25 |
+
n_samples: int = 18000, seed: int = 2026
|
| 26 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 27 |
+
"""
|
| 28 |
+
Generate a rich, realistic RGB dataset of OMR bubbles specifically modeling
|
| 29 |
+
'Blind-Letter Detection':
|
| 30 |
+
Label 1 = The printed letter (A/B/C/D/E) inside the circle is BLINDED / OCCLUDED
|
| 31 |
+
by student pen/pencil ink (full fill, partial center blob, small dark dot
|
| 32 |
+
covering the letter, tick/cross/slash over the letter, slanted scribble, or pencil).
|
| 33 |
+
Label 0 = The printed letter inside the circle remains UNOCCLUDED / VISIBLE
|
| 34 |
+
(clean red/maroon/orange/blue/green/B&W printed circles, shadows, blur,
|
| 35 |
+
faint erasure smudge, or tiny stray rim speck leaving the letter readable).
|
| 36 |
+
"""
|
| 37 |
+
rng = np.random.default_rng(seed)
|
| 38 |
+
letters = ["A", "B", "C", "D", "E", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
| 39 |
+
fonts = [cv2.FONT_HERSHEY_SIMPLEX, cv2.FONT_HERSHEY_DUPLEX, cv2.FONT_HERSHEY_TRIPLEX]
|
| 40 |
+
|
| 41 |
+
# Realistic OMR form print colors in BGR (heavily covering red/maroon forms + blue/green/B&W)
|
| 42 |
+
form_palettes = [
|
| 43 |
+
(75, 78, 178), # Red/maroon (Savar Science Society style!)
|
| 44 |
+
(60, 72, 195), # Bright red OMR form
|
| 45 |
+
(88, 95, 165), # Soft brick-red form
|
| 46 |
+
(70, 115, 205), # Orange-red form
|
| 47 |
+
(175, 95, 65), # Blue OMR form
|
| 48 |
+
(85, 145, 75), # Green OMR form
|
| 49 |
+
(78, 78, 78), # Dark gray B&W photocopy
|
| 50 |
+
(45, 45, 45), # Crisp black B&W print
|
| 51 |
+
]
|
| 52 |
+
palette_probs = [0.24, 0.18, 0.14, 0.08, 0.08, 0.06, 0.12, 0.10]
|
| 53 |
+
|
| 54 |
+
# Student pen/pencil ink colors in BGR
|
| 55 |
+
ink_palettes = [
|
| 56 |
+
(22, 20, 24), # Black ballpoint pen
|
| 57 |
+
(38, 34, 38), # Charcoal dark pen
|
| 58 |
+
(115, 48, 25), # Blue ballpoint pen
|
| 59 |
+
(75, 72, 74), # Dark HB/2B pencil
|
| 60 |
+
(102, 98, 100), # Medium pencil
|
| 61 |
+
]
|
| 62 |
+
|
| 63 |
+
X = np.empty((n_samples, 4, CNN_INPUT_SIZE, CNN_INPUT_SIZE), dtype=np.float32)
|
| 64 |
+
y = np.empty((n_samples,), dtype=np.float32)
|
| 65 |
+
|
| 66 |
+
cell = 76
|
| 67 |
+
r = 25.0
|
| 68 |
+
|
| 69 |
+
for i in range(n_samples):
|
| 70 |
+
is_blinded = i % 2 == 1
|
| 71 |
+
y[i] = 1.0 if is_blinded else 0.0
|
| 72 |
+
|
| 73 |
+
# Paper background with subtle warm/cool tint & directional phone-camera shadow
|
| 74 |
+
base_b = float(rng.uniform(222, 250))
|
| 75 |
+
base_g = float(rng.uniform(224, 251))
|
| 76 |
+
base_r = float(rng.uniform(228, 253))
|
| 77 |
+
canvas = np.empty((cell, cell, 3), dtype=np.float32)
|
| 78 |
+
canvas[:, :, 0] = base_b
|
| 79 |
+
canvas[:, :, 1] = base_g
|
| 80 |
+
canvas[:, :, 2] = base_r
|
| 81 |
+
|
| 82 |
+
gx = float(rng.uniform(-22, 22))
|
| 83 |
+
gy = float(rng.uniform(-18, 18))
|
| 84 |
+
xs = np.linspace(-0.5, 0.5, cell, dtype=np.float32)
|
| 85 |
+
ys = np.linspace(-0.5, 0.5, cell, dtype=np.float32)
|
| 86 |
+
canvas += (gx * xs[None, :] + gy * ys[:, None])[:, :, None]
|
| 87 |
+
canvas += rng.normal(0, rng.uniform(1.5, 5.5), size=(cell, cell, 3)).astype(np.float32)
|
| 88 |
+
img = np.clip(canvas, 0, 255).astype(np.uint8)
|
| 89 |
+
|
| 90 |
+
# Pick printed form color
|
| 91 |
+
p_idx = int(rng.choice(len(form_palettes), p=palette_probs))
|
| 92 |
+
fb, fg, fr = form_palettes[p_idx]
|
| 93 |
+
jitter = rng.integers(-18, 19, size=3)
|
| 94 |
+
ring_bgr = (
|
| 95 |
+
int(np.clip(fb + jitter[0], 20, 220)),
|
| 96 |
+
int(np.clip(fg + jitter[1], 20, 220)),
|
| 97 |
+
int(np.clip(fr + jitter[2], 20, 235)),
|
| 98 |
+
)
|
| 99 |
+
letter_bgr = (
|
| 100 |
+
int(min(225, ring_bgr[0] + rng.integers(8, 28))),
|
| 101 |
+
int(min(225, ring_bgr[1] + rng.integers(8, 28))),
|
| 102 |
+
int(min(238, ring_bgr[2] + rng.integers(8, 28))),
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
# Bubble center with realistic slight alignment jitter
|
| 106 |
+
cx = cell / 2.0 + float(rng.uniform(-2.6, 2.6))
|
| 107 |
+
cy = cell / 2.0 + float(rng.uniform(-2.6, 2.6))
|
| 108 |
+
rr = int(round(r + rng.uniform(-1.5, 1.5)))
|
| 109 |
+
ring_th = int(rng.choice([1, 2]))
|
| 110 |
+
|
| 111 |
+
# Draw printed circle & printed option letter
|
| 112 |
+
cv2.circle(img, (int(round(cx)), int(round(cy))), rr, ring_bgr, ring_th, cv2.LINE_AA)
|
| 113 |
+
ch = letters[int(rng.integers(0, len(letters)))]
|
| 114 |
+
font = fonts[int(rng.integers(0, len(fonts)))]
|
| 115 |
+
fscale = float(rng.uniform(0.58, 0.78))
|
| 116 |
+
cv2.putText(
|
| 117 |
+
img,
|
| 118 |
+
ch,
|
| 119 |
+
(int(round(cx - rr * 0.34)), int(round(cy + rr * 0.32))),
|
| 120 |
+
font,
|
| 121 |
+
fscale,
|
| 122 |
+
letter_bgr,
|
| 123 |
+
int(rng.choice([1, 2])),
|
| 124 |
+
cv2.LINE_AA,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
if is_blinded:
|
| 128 |
+
# Pick realistic student ink color
|
| 129 |
+
ib, ig, ir = ink_palettes[int(rng.integers(0, len(ink_palettes)))]
|
| 130 |
+
ink_col = (
|
| 131 |
+
int(np.clip(ib + rng.integers(-12, 16), 5, 155)),
|
| 132 |
+
int(np.clip(ig + rng.integers(-12, 16), 5, 145)),
|
| 133 |
+
int(np.clip(ir + rng.integers(-12, 16), 5, 145)),
|
| 134 |
+
)
|
| 135 |
+
style = rng.random()
|
| 136 |
+
if style < 0.32:
|
| 137 |
+
# 1. Solid full fill (80-100%)
|
| 138 |
+
fill_r = int(round(rr * rng.uniform(0.78, 1.03)))
|
| 139 |
+
ox, oy = rng.uniform(-2.2, 2.2), rng.uniform(-2.2, 2.2)
|
| 140 |
+
cv2.circle(img, (int(round(cx + ox)), int(round(cy + oy))), fill_r, ink_col, -1, cv2.LINE_AA)
|
| 141 |
+
elif style < 0.54:
|
| 142 |
+
# 2. Partial center fill blinding the letter (45-75%, like Q14-C / Q15-B)
|
| 143 |
+
ax1 = int(round(rr * rng.uniform(0.48, 0.80)))
|
| 144 |
+
ax2 = int(round(rr * rng.uniform(0.45, 0.78)))
|
| 145 |
+
ang = float(rng.uniform(0, 180))
|
| 146 |
+
ox, oy = rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)
|
| 147 |
+
cv2.ellipse(img, (int(round(cx + ox)), int(round(cy + oy))), (ax1, ax2), ang, 0, 360, ink_col, -1, cv2.LINE_AA)
|
| 148 |
+
elif style < 0.72:
|
| 149 |
+
# 3. Hurried small dark dot / scribble directly blinding the center letter (like Q20-B!)
|
| 150 |
+
fill_r = int(round(rr * rng.uniform(0.35, 0.52)))
|
| 151 |
+
ox, oy = rng.uniform(-3.2, 3.2), rng.uniform(-3.2, 3.2)
|
| 152 |
+
cv2.circle(img, (int(round(cx + ox)), int(round(cy + oy))), fill_r, ink_col, -1, cv2.LINE_AA)
|
| 153 |
+
if rng.random() < 0.5:
|
| 154 |
+
# Optional pen tail/flick like Q20-B
|
| 155 |
+
tx = int(round(cx + ox + rng.uniform(-rr * 0.7, rr * 0.7)))
|
| 156 |
+
ty = int(round(cy + oy + rng.uniform(-rr * 0.7, rr * 0.7)))
|
| 157 |
+
cv2.line(img, (int(round(cx + ox)), int(round(cy + oy))), (tx, ty), ink_col, 2, cv2.LINE_AA)
|
| 158 |
+
elif style < 0.86:
|
| 159 |
+
# 4. Tick / Cross / Diagonal slash directly over the center letter
|
| 160 |
+
th = int(rng.integers(4, 8))
|
| 161 |
+
if rng.random() < 0.5:
|
| 162 |
+
# Cross X over letter
|
| 163 |
+
d = int(round(rr * rng.uniform(0.45, 0.72)))
|
| 164 |
+
cv2.line(img, (int(cx - d), int(cy - d)), (int(cx + d), int(cy + d)), ink_col, th, cv2.LINE_AA)
|
| 165 |
+
cv2.line(img, (int(cx + d), int(cy - d)), (int(cx - d), int(cy + d)), ink_col, th, cv2.LINE_AA)
|
| 166 |
+
else:
|
| 167 |
+
# Heavy tick / scribble zig-zag blinding the letter
|
| 168 |
+
pts = np.array([
|
| 169 |
+
[int(cx - rr * 0.48), int(cy - rr * 0.1)],
|
| 170 |
+
[int(cx - rr * 0.08), int(cy + rr * 0.42)],
|
| 171 |
+
[int(cx + rr * 0.58), int(cy - rr * 0.45)],
|
| 172 |
+
], dtype=np.int32)
|
| 173 |
+
cv2.polylines(img, [pts], False, ink_col, th, cv2.LINE_AA)
|
| 174 |
+
else:
|
| 175 |
+
# 5. Light/textured graphite pencil shade blinding the letter
|
| 176 |
+
fill_r = int(round(rr * rng.uniform(0.58, 0.94)))
|
| 177 |
+
mask = np.zeros((cell, cell), dtype=np.uint8)
|
| 178 |
+
cv2.circle(mask, (int(round(cx)), int(round(cy))), fill_r, 255, -1, cv2.LINE_AA)
|
| 179 |
+
shade = int(rng.uniform(55, 138))
|
| 180 |
+
tex = np.clip(shade + rng.normal(0, 18, size=(cell, cell, 3)), 18, 175).astype(np.uint8)
|
| 181 |
+
img = np.where(mask[:, :, None] > 0, np.minimum(img, tex), img)
|
| 182 |
+
else:
|
| 183 |
+
# Hard Negatives: letter remains clearly readable!
|
| 184 |
+
neg = rng.random()
|
| 185 |
+
if neg < 0.14:
|
| 186 |
+
# Faint erasure smudge (letter still visible underneath)
|
| 187 |
+
smudge = int(rng.uniform(182, 222))
|
| 188 |
+
overlay = img.copy()
|
| 189 |
+
cv2.circle(overlay, (int(round(cx)), int(round(cy))), int(round(rr * 0.75)), (smudge, smudge, smudge), -1, cv2.LINE_AA)
|
| 190 |
+
img = cv2.addWeighted(img, 0.62, overlay, 0.38, 0)
|
| 191 |
+
elif neg < 0.24:
|
| 192 |
+
# Tiny stray pen speck on outer rim (leaving central letter visible, like Q15-A!)
|
| 193 |
+
ang = float(rng.uniform(0, 2 * np.pi))
|
| 194 |
+
dist_edge = rr * float(rng.uniform(0.55, 0.88))
|
| 195 |
+
sx = int(round(cx + np.cos(ang) * dist_edge))
|
| 196 |
+
sy = int(round(cy + np.sin(ang) * dist_edge))
|
| 197 |
+
cv2.circle(img, (sx, sy), int(rng.integers(2, 4)), (35, 35, 40), -1, cv2.LINE_AA)
|
| 198 |
+
elif neg < 0.30:
|
| 199 |
+
# Tiny accidental edge tick near border
|
| 200 |
+
ang = float(rng.uniform(0, 2 * np.pi))
|
| 201 |
+
sx = int(round(cx + np.cos(ang) * rr * 0.65))
|
| 202 |
+
sy = int(round(cy + np.sin(ang) * rr * 0.65))
|
| 203 |
+
cv2.line(img, (sx, sy), (sx + int(rng.integers(-4, 5)), sy + int(rng.integers(-4, 5))), (40, 40, 45), 2, cv2.LINE_AA)
|
| 204 |
+
|
| 205 |
+
# Realistic camera blur
|
| 206 |
+
if rng.random() < 0.55:
|
| 207 |
+
img = cv2.GaussianBlur(img, (3, 3), float(rng.uniform(0.3, 1.1)))
|
| 208 |
+
|
| 209 |
+
X[i] = extract_4ch_bubble_tensor(img, cell / 2.0, cell / 2.0, r)
|
| 210 |
+
|
| 211 |
+
return X, y
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def train_and_export() -> None:
|
| 215 |
+
t0 = time.perf_counter()
|
| 216 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 217 |
+
print(f"[OMR-BlindNet-v1] Training device: {device}")
|
| 218 |
+
|
| 219 |
+
n_total = 18000
|
| 220 |
+
print(f"[OMR-BlindNet-v1] Synthesizing {n_total} multi-color Blind-Letter OMR samples...")
|
| 221 |
+
X, y = synthesize_blind_letter_dataset(n_samples=n_total, seed=2026)
|
| 222 |
+
|
| 223 |
+
rng = np.random.default_rng(42)
|
| 224 |
+
perm = rng.permutation(n_total)
|
| 225 |
+
X, y = X[perm], y[perm]
|
| 226 |
+
|
| 227 |
+
split = int(n_total * 0.85)
|
| 228 |
+
X_tr, y_tr = X[:split], y[:split]
|
| 229 |
+
X_va, y_va = X[split:], y[split:]
|
| 230 |
+
|
| 231 |
+
tr_loader = DataLoader(
|
| 232 |
+
TensorDataset(torch.from_numpy(X_tr), torch.from_numpy(y_tr)),
|
| 233 |
+
batch_size=128,
|
| 234 |
+
shuffle=True,
|
| 235 |
+
)
|
| 236 |
+
va_loader = DataLoader(
|
| 237 |
+
TensorDataset(torch.from_numpy(X_va), torch.from_numpy(y_va)),
|
| 238 |
+
batch_size=256,
|
| 239 |
+
shuffle=False,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
model = OMRBlindNet(in_channels=4, dropout=0.25).to(device)
|
| 243 |
+
param_count = sum(p.numel() for p in model.parameters())
|
| 244 |
+
print(f"[OMR-BlindNet-v1] Model parameters: {param_count:,}")
|
| 245 |
+
|
| 246 |
+
epochs = 12
|
| 247 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2.0e-3, weight_decay=1e-4)
|
| 248 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs)
|
| 249 |
+
criterion = nn.BCEWithLogitsLoss()
|
| 250 |
+
|
| 251 |
+
best_acc = 0.0
|
| 252 |
+
best_state = None
|
| 253 |
+
|
| 254 |
+
for ep in range(1, epochs + 1):
|
| 255 |
+
model.train()
|
| 256 |
+
tr_loss = 0.0
|
| 257 |
+
for bx, by in tr_loader:
|
| 258 |
+
bx = bx.to(device)
|
| 259 |
+
# Subtle label smoothing (0.015) for crisp calibrated probabilities
|
| 260 |
+
by = by.to(device).unsqueeze(1) * 0.97 + 0.015
|
| 261 |
+
optimizer.zero_grad(set_to_none=True)
|
| 262 |
+
logits = model(bx)
|
| 263 |
+
loss = criterion(logits, by)
|
| 264 |
+
loss.backward()
|
| 265 |
+
optimizer.step()
|
| 266 |
+
tr_loss += float(loss.item()) * bx.size(0)
|
| 267 |
+
scheduler.step()
|
| 268 |
+
|
| 269 |
+
model.eval()
|
| 270 |
+
correct = 0
|
| 271 |
+
total = 0
|
| 272 |
+
with torch.no_grad():
|
| 273 |
+
for bx, by in va_loader:
|
| 274 |
+
bx = bx.to(device)
|
| 275 |
+
by = by.to(device)
|
| 276 |
+
probs = torch.sigmoid(model(bx).squeeze(1))
|
| 277 |
+
preds = (probs >= 0.5).float()
|
| 278 |
+
correct += int((preds == by).sum().item())
|
| 279 |
+
total += int(by.size(0))
|
| 280 |
+
val_acc = (correct / total) * 100.0
|
| 281 |
+
print(f" Epoch {ep:02d}/{epochs} | train_loss={tr_loss/len(X_tr):.4f} | val_acc={val_acc:.2f}%")
|
| 282 |
+
if val_acc >= best_acc:
|
| 283 |
+
best_acc = val_acc
|
| 284 |
+
best_state = {k: v.cpu().clone() for k, v in model.state_dict().items()}
|
| 285 |
+
|
| 286 |
+
if best_state is not None:
|
| 287 |
+
model.load_state_dict(best_state)
|
| 288 |
+
model = model.cpu().eval()
|
| 289 |
+
|
| 290 |
+
# 1. Save PyTorch checkpoint
|
| 291 |
+
pt_path = THIS_DIR / "omr_blindnet_v1.pt"
|
| 292 |
+
torch.save(
|
| 293 |
+
{
|
| 294 |
+
"model_name": "OMR-BlindNet-v1",
|
| 295 |
+
"architecture": "ResidualSE-CNN-4ch-32x32",
|
| 296 |
+
"val_accuracy": round(best_acc, 3),
|
| 297 |
+
"params": param_count,
|
| 298 |
+
"state_dict": model.state_dict(),
|
| 299 |
+
},
|
| 300 |
+
pt_path,
|
| 301 |
+
)
|
| 302 |
+
print(f"[OMR-BlindNet-v1] Saved PyTorch weights -> {pt_path} ({pt_path.stat().st_size / 1024:.1f} KB)")
|
| 303 |
+
|
| 304 |
+
# 2. Export Universal ONNX Model (model.onnx)
|
| 305 |
+
onnx_path = THIS_DIR / "model.onnx"
|
| 306 |
+
dummy = torch.randn(1, 4, CNN_INPUT_SIZE, CNN_INPUT_SIZE, dtype=torch.float32)
|
| 307 |
+
torch.onnx.export(
|
| 308 |
+
model,
|
| 309 |
+
dummy,
|
| 310 |
+
str(onnx_path),
|
| 311 |
+
input_names=["bubble_tensor"],
|
| 312 |
+
output_names=["blind_logit"],
|
| 313 |
+
dynamic_axes={"bubble_tensor": {0: "batch_size"}, "blind_logit": {0: "batch_size"}},
|
| 314 |
+
opset_version=17,
|
| 315 |
+
dynamo=False,
|
| 316 |
+
)
|
| 317 |
+
print(f"[OMR-BlindNet-v1] Exported ONNX model -> {onnx_path} ({onnx_path.stat().st_size / 1024:.1f} KB)")
|
| 318 |
+
|
| 319 |
+
# 3. Verify ONNX Runtime parity
|
| 320 |
+
ort_model = OMRBlindNetONNX(onnx_path)
|
| 321 |
+
sample_probs = ort_model.predict_tensors(X_va[:256])
|
| 322 |
+
ort_acc = float(np.mean((sample_probs >= 0.5) == y_va[:256])) * 100.0
|
| 323 |
+
print(f"[OMR-BlindNet-v1] ONNX Runtime verification accuracy (256 batch): {ort_acc:.2f}%")
|
| 324 |
+
|
| 325 |
+
# 4. Save Hugging Face config.json
|
| 326 |
+
cfg = {
|
| 327 |
+
"model_type": "omr_blindnet",
|
| 328 |
+
"model_name": "OMR-BlindNet-v1",
|
| 329 |
+
"version": "1.0.0",
|
| 330 |
+
"architecture": "ResidualSE-CNN (4ch 32x32 -> 32/64/128/192 -> Avg+MaxPool -> 96 -> 1)",
|
| 331 |
+
"task": "blind-letter-omr-bubble-classification",
|
| 332 |
+
"input_shape": ["batch_size", 4, 32, 32],
|
| 333 |
+
"input_channels": ["R_norm", "G_norm", "B_norm", "DarkInkOcclusion"],
|
| 334 |
+
"output": "blind_logit (apply sigmoid; >= 0.50 = letter blinded / marked)",
|
| 335 |
+
"double_answer_policy": "Multiple blinded circles in one MCQ count as WRONG",
|
| 336 |
+
"parameters": param_count,
|
| 337 |
+
"training_samples": n_total,
|
| 338 |
+
"validation_accuracy": round(best_acc, 2),
|
| 339 |
+
"trained_at": datetime.now(timezone.utc).isoformat(),
|
| 340 |
+
"elapsed_sec": round(time.perf_counter() - t0, 1),
|
| 341 |
+
}
|
| 342 |
+
(THIS_DIR / "config.json").write_text(json.dumps(cfg, indent=2), encoding="utf-8")
|
| 343 |
+
print(f"[OMR-BlindNet-v1] Done in {cfg['elapsed_sec']}s! Best val_acc = {best_acc:.2f}%")
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
if __name__ == "__main__":
|
| 347 |
+
train_and_export()
|