omrkit 2.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- omrkit/__init__.py +76 -0
- omrkit/__main__.py +6 -0
- omrkit/api/__init__.py +5 -0
- omrkit/api/app.py +75 -0
- omrkit/api/routes.py +490 -0
- omrkit/api/settings.py +55 -0
- omrkit/api/static/assets/index-BFfdzDls.js +224 -0
- omrkit/api/static/assets/index-DRPOjlrM.css +1 -0
- omrkit/api/static/index.html +23 -0
- omrkit/cli/__init__.py +5 -0
- omrkit/cli/app.py +440 -0
- omrkit/core/__init__.py +44 -0
- omrkit/core/auto_scanner.py +132 -0
- omrkit/core/benchmark.py +204 -0
- omrkit/core/migrator.py +149 -0
- omrkit/core/scanner.py +281 -0
- omrkit/core/validators.py +62 -0
- omrkit/generator/__init__.py +13 -0
- omrkit/generator/pdf_sheet.py +508 -0
- omrkit/generator/presets.py +109 -0
- omrkit/grading/__init__.py +6 -0
- omrkit/grading/analytics.py +177 -0
- omrkit/grading/grader.py +191 -0
- omrkit/io/__init__.py +37 -0
- omrkit/io/exporters.py +355 -0
- omrkit/io/loader.py +207 -0
- omrkit/models/__init__.py +65 -0
- omrkit/models/grading.py +222 -0
- omrkit/models/scan.py +100 -0
- omrkit/models/template.py +285 -0
- omrkit/py.typed +0 -0
- omrkit/vision/__init__.py +30 -0
- omrkit/vision/detector.py +313 -0
- omrkit/vision/grid_finder.py +280 -0
- omrkit/vision/preprocess.py +57 -0
- omrkit/vision/qr.py +83 -0
- omrkit/vision/registration.py +486 -0
- omrkit/vision/visualizer.py +99 -0
- omrkit-2.1.0.dist-info/METADATA +284 -0
- omrkit-2.1.0.dist-info/RECORD +43 -0
- omrkit-2.1.0.dist-info/WHEEL +4 -0
- omrkit-2.1.0.dist-info/entry_points.txt +2 -0
- omrkit-2.1.0.dist-info/licenses/LICENSE +21 -0
omrkit/models/grading.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Exam grading, scoring policy, and psychometric analytics models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
import yaml
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
VerdictType = Literal["correct", "incorrect", "blank", "bonus"]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class SectionRule(BaseModel):
|
|
16
|
+
"""Optional section-specific scoring weights (e.g., Math vs Verbal)."""
|
|
17
|
+
|
|
18
|
+
name: str
|
|
19
|
+
questions: list[str]
|
|
20
|
+
correct_points: float = 1.0
|
|
21
|
+
incorrect_points: float = 0.0
|
|
22
|
+
blank_points: float = 0.0
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GradingPolicy(BaseModel):
|
|
26
|
+
"""Exam scoring rules including negative marking and section weights."""
|
|
27
|
+
|
|
28
|
+
name: str = "standard"
|
|
29
|
+
correct_points: float = 1.0
|
|
30
|
+
incorrect_points: float = 0.0
|
|
31
|
+
blank_points: float = 0.0
|
|
32
|
+
partial_credit: bool = False
|
|
33
|
+
bonus_questions: list[str] = Field(default_factory=list)
|
|
34
|
+
sections: list[SectionRule] = Field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def preset(cls, preset_name: str) -> GradingPolicy:
|
|
38
|
+
"""Create a well-known grading policy preset."""
|
|
39
|
+
presets: dict[str, GradingPolicy] = {
|
|
40
|
+
"standard": cls(
|
|
41
|
+
name="standard",
|
|
42
|
+
correct_points=1.0,
|
|
43
|
+
incorrect_points=0.0,
|
|
44
|
+
blank_points=0.0,
|
|
45
|
+
),
|
|
46
|
+
"yks_tyt": cls(
|
|
47
|
+
name="yks_tyt",
|
|
48
|
+
correct_points=1.0,
|
|
49
|
+
incorrect_points=-0.25,
|
|
50
|
+
blank_points=0.0,
|
|
51
|
+
),
|
|
52
|
+
"kpss": cls(
|
|
53
|
+
name="kpss",
|
|
54
|
+
correct_points=1.0,
|
|
55
|
+
incorrect_points=-0.25,
|
|
56
|
+
blank_points=0.0,
|
|
57
|
+
),
|
|
58
|
+
"lgs": cls(
|
|
59
|
+
name="lgs",
|
|
60
|
+
correct_points=1.0,
|
|
61
|
+
incorrect_points=-1.0 / 3.0,
|
|
62
|
+
blank_points=0.0,
|
|
63
|
+
),
|
|
64
|
+
"sat_legacy": cls(
|
|
65
|
+
name="sat_legacy",
|
|
66
|
+
correct_points=1.0,
|
|
67
|
+
incorrect_points=-0.25,
|
|
68
|
+
blank_points=0.0,
|
|
69
|
+
),
|
|
70
|
+
}
|
|
71
|
+
if preset_name not in presets:
|
|
72
|
+
available = ", ".join(sorted(presets))
|
|
73
|
+
raise ValueError(f"Unknown grading policy '{preset_name}'. Available: {available}")
|
|
74
|
+
return presets[preset_name]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AnswerKey(BaseModel):
|
|
78
|
+
"""Single- or multi-booklet answer key definition."""
|
|
79
|
+
|
|
80
|
+
exam_name: str = "Untitled Exam"
|
|
81
|
+
booklet_field: str | None = None
|
|
82
|
+
default_booklet: str = "A"
|
|
83
|
+
# Mapping booklet_id -> {question_id: expected_answer (str or list of acceptable answers)}
|
|
84
|
+
booklets: dict[str, dict[str, str | list[str]]] = Field(default_factory=dict)
|
|
85
|
+
# Shorthand when only a single answer key is provided without booklets
|
|
86
|
+
answers: dict[str, str | list[str]] = Field(default_factory=dict)
|
|
87
|
+
|
|
88
|
+
def resolve_booklet(self, booklet_code: str | None) -> dict[str, str | list[str]]:
|
|
89
|
+
"""Resolve question -> expected answer map for the given booklet code."""
|
|
90
|
+
if self.booklets:
|
|
91
|
+
if booklet_code and booklet_code in self.booklets:
|
|
92
|
+
return self.booklets[booklet_code]
|
|
93
|
+
if self.default_booklet in self.booklets:
|
|
94
|
+
return self.booklets[self.default_booklet]
|
|
95
|
+
first_key = next(iter(self.booklets))
|
|
96
|
+
return self.booklets[first_key]
|
|
97
|
+
return self.answers
|
|
98
|
+
|
|
99
|
+
def question_ids(self) -> list[str]:
|
|
100
|
+
"""Return ordered question IDs from the default booklet."""
|
|
101
|
+
return list(self.resolve_booklet(self.default_booklet).keys())
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def from_file(cls, path: str | Path) -> AnswerKey:
|
|
105
|
+
"""Load an AnswerKey from JSON or YAML."""
|
|
106
|
+
file_path = Path(path)
|
|
107
|
+
raw = file_path.read_text(encoding="utf-8")
|
|
108
|
+
if file_path.suffix.lower() in {".yaml", ".yml"}:
|
|
109
|
+
data = yaml.safe_load(raw)
|
|
110
|
+
else:
|
|
111
|
+
data = json.loads(raw)
|
|
112
|
+
return cls.model_validate(data)
|
|
113
|
+
|
|
114
|
+
def to_file(self, path: str | Path) -> Path:
|
|
115
|
+
"""Save an AnswerKey to JSON or YAML."""
|
|
116
|
+
file_path = Path(path)
|
|
117
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
118
|
+
payload = self.model_dump(mode="json")
|
|
119
|
+
if file_path.suffix.lower() in {".yaml", ".yml"}:
|
|
120
|
+
file_path.write_text(
|
|
121
|
+
yaml.safe_dump(payload, sort_keys=False, allow_unicode=True),
|
|
122
|
+
encoding="utf-8",
|
|
123
|
+
)
|
|
124
|
+
else:
|
|
125
|
+
file_path.write_text(
|
|
126
|
+
json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
|
|
127
|
+
encoding="utf-8",
|
|
128
|
+
)
|
|
129
|
+
return file_path
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class QuestionVerdict(BaseModel):
|
|
133
|
+
"""Per-question grading breakdown."""
|
|
134
|
+
|
|
135
|
+
question_id: str
|
|
136
|
+
marked: str
|
|
137
|
+
expected: str
|
|
138
|
+
verdict: VerdictType
|
|
139
|
+
points: float
|
|
140
|
+
confidence: float = 1.0
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class SectionScore(BaseModel):
|
|
144
|
+
"""Per-section subtotal for a student."""
|
|
145
|
+
|
|
146
|
+
name: str
|
|
147
|
+
correct: int
|
|
148
|
+
incorrect: int
|
|
149
|
+
blank: int
|
|
150
|
+
score: float
|
|
151
|
+
max_score: float
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
class StudentGrade(BaseModel):
|
|
155
|
+
"""Complete graded scorecard for one optical sheet."""
|
|
156
|
+
|
|
157
|
+
sheet_id: str
|
|
158
|
+
source_file: str
|
|
159
|
+
student_metadata: dict[str, str] = Field(default_factory=dict)
|
|
160
|
+
booklet: str = "A"
|
|
161
|
+
total_questions: int = 0
|
|
162
|
+
correct: int = 0
|
|
163
|
+
incorrect: int = 0
|
|
164
|
+
blank: int = 0
|
|
165
|
+
bonus: int = 0
|
|
166
|
+
raw_score: float = 0.0
|
|
167
|
+
max_score: float = 0.0
|
|
168
|
+
percentage: float = 0.0
|
|
169
|
+
flagged_for_review: bool = False
|
|
170
|
+
sections: list[SectionScore] = Field(default_factory=list)
|
|
171
|
+
verdicts: list[QuestionVerdict] = Field(default_factory=list)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
class ItemPsychometrics(BaseModel):
|
|
175
|
+
"""Classical Test Theory (CTT) statistics for an individual exam question."""
|
|
176
|
+
|
|
177
|
+
question_id: str
|
|
178
|
+
expected: str
|
|
179
|
+
attempts: int
|
|
180
|
+
correct_count: int
|
|
181
|
+
incorrect_count: int
|
|
182
|
+
blank_count: int
|
|
183
|
+
difficulty_p: float = Field(ge=0.0, le=1.0)
|
|
184
|
+
discrimination_d: float = Field(ge=-1.0, le=1.0)
|
|
185
|
+
omit_rate: float = Field(ge=0.0, le=1.0)
|
|
186
|
+
option_distribution: dict[str, int] = Field(default_factory=dict)
|
|
187
|
+
quality_flag: Literal["good", "too_easy", "too_hard", "poor_discrimination"] = "good"
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class ScoreHistogramBin(BaseModel):
|
|
191
|
+
"""Score range bin for distribution visualization."""
|
|
192
|
+
|
|
193
|
+
label: str
|
|
194
|
+
low: float
|
|
195
|
+
high: float
|
|
196
|
+
count: int
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class ExamAnalytics(BaseModel):
|
|
200
|
+
"""Cohort-level statistical and psychometric exam summary."""
|
|
201
|
+
|
|
202
|
+
student_count: int
|
|
203
|
+
question_count: int
|
|
204
|
+
mean_score: float
|
|
205
|
+
median_score: float
|
|
206
|
+
std_score: float
|
|
207
|
+
min_score: float
|
|
208
|
+
max_score: float
|
|
209
|
+
mean_percentage: float
|
|
210
|
+
percentiles: dict[str, float] = Field(default_factory=dict)
|
|
211
|
+
kr20_reliability: float | None = None
|
|
212
|
+
histogram: list[ScoreHistogramBin] = Field(default_factory=list)
|
|
213
|
+
items: list[ItemPsychometrics] = Field(default_factory=list)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class GradingReport(BaseModel):
|
|
217
|
+
"""Combined grading results and psychometric analytics for an exam batch."""
|
|
218
|
+
|
|
219
|
+
exam_name: str
|
|
220
|
+
policy_name: str
|
|
221
|
+
grades: list[StudentGrade] = Field(default_factory=list)
|
|
222
|
+
analytics: ExamAnalytics
|
omrkit/models/scan.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Scan output, bubble reading, and HITL review queue models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Literal
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
FieldStatus = Literal["ok", "blank", "multi_marked", "low_confidence", "invalid_checksum"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BubbleReading(BaseModel):
|
|
13
|
+
"""Per-bubble optical measurements from the hybrid detector."""
|
|
14
|
+
|
|
15
|
+
option: str
|
|
16
|
+
cx: float
|
|
17
|
+
cy: float
|
|
18
|
+
radius: float
|
|
19
|
+
fill_ratio: float = Field(ge=0.0, le=1.0)
|
|
20
|
+
darkness: float = Field(ge=0.0, le=1.0)
|
|
21
|
+
ink_score: float = Field(ge=0.0, le=1.0)
|
|
22
|
+
combined_score: float = Field(ge=0.0, le=1.0)
|
|
23
|
+
selected: bool = False
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class FieldReading(BaseModel):
|
|
27
|
+
"""Evaluated reading for a single OMR field (question or ID digit)."""
|
|
28
|
+
|
|
29
|
+
field_id: str
|
|
30
|
+
block_name: str
|
|
31
|
+
value: str
|
|
32
|
+
selected_options: list[str] = Field(default_factory=list)
|
|
33
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
34
|
+
status: FieldStatus = "ok"
|
|
35
|
+
bubbles: list[BubbleReading] = Field(default_factory=list)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ReviewItem(BaseModel):
|
|
39
|
+
"""Actionable item queued for Human-in-the-Loop (HITL) verification."""
|
|
40
|
+
|
|
41
|
+
field_id: str
|
|
42
|
+
block_name: str
|
|
43
|
+
reason: FieldStatus
|
|
44
|
+
suggested_value: str
|
|
45
|
+
confidence: float = Field(ge=0.0, le=1.0)
|
|
46
|
+
candidate_options: list[str] = Field(default_factory=list)
|
|
47
|
+
bbox: tuple[int, int, int, int] # (x1, y1, x2, y2) in canonical coordinates
|
|
48
|
+
message: str = ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SheetResult(BaseModel):
|
|
52
|
+
"""Complete scan output for a single optical sheet page."""
|
|
53
|
+
|
|
54
|
+
sheet_id: str
|
|
55
|
+
source_file: str
|
|
56
|
+
page_index: int = 0
|
|
57
|
+
template_name: str
|
|
58
|
+
fields: dict[str, FieldReading] = Field(default_factory=dict)
|
|
59
|
+
grouped_values: dict[str, str] = Field(default_factory=dict)
|
|
60
|
+
review_items: list[ReviewItem] = Field(default_factory=list)
|
|
61
|
+
overall_confidence: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
62
|
+
registration_method: str = "none"
|
|
63
|
+
registration_score: float = Field(default=1.0, ge=0.0, le=1.0)
|
|
64
|
+
rotation_applied: int = 0
|
|
65
|
+
elapsed_ms: float = 0.0
|
|
66
|
+
warnings: list[str] = Field(default_factory=list)
|
|
67
|
+
error: str | None = None
|
|
68
|
+
|
|
69
|
+
def flat_responses(self) -> dict[str, str]:
|
|
70
|
+
"""Return flat mapping of field/group labels to resolved string values."""
|
|
71
|
+
output: dict[str, str] = {}
|
|
72
|
+
for field_id, reading in self.fields.items():
|
|
73
|
+
output[field_id] = reading.value
|
|
74
|
+
output.update(self.grouped_values)
|
|
75
|
+
return output
|
|
76
|
+
|
|
77
|
+
def apply_override(self, field_id: str, new_value: str) -> None:
|
|
78
|
+
"""Apply a human-in-the-loop correction and clear the corresponding review flag."""
|
|
79
|
+
if field_id in self.fields:
|
|
80
|
+
reading = self.fields[field_id]
|
|
81
|
+
reading.value = new_value
|
|
82
|
+
reading.selected_options = list(new_value) if new_value else []
|
|
83
|
+
reading.confidence = 1.0
|
|
84
|
+
reading.status = "blank" if new_value == "" else "ok"
|
|
85
|
+
elif field_id in self.grouped_values:
|
|
86
|
+
self.grouped_values[field_id] = new_value
|
|
87
|
+
self.review_items = [item for item in self.review_items if item.field_id != field_id]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class BatchResult(BaseModel):
|
|
91
|
+
"""Aggregated outcome of scanning multiple images or multi-page PDFs."""
|
|
92
|
+
|
|
93
|
+
template_name: str
|
|
94
|
+
sheets: list[SheetResult] = Field(default_factory=list)
|
|
95
|
+
total_sheets: int = 0
|
|
96
|
+
succeeded: int = 0
|
|
97
|
+
flagged_sheets: int = 0
|
|
98
|
+
failed_sheets: int = 0
|
|
99
|
+
total_elapsed_ms: float = 0.0
|
|
100
|
+
sheets_per_minute: float = 0.0
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Template, field block, and registration schemas for OMRKit."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any, Literal
|
|
9
|
+
|
|
10
|
+
import yaml
|
|
11
|
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
|
12
|
+
|
|
13
|
+
RegistrationMode = Literal["aruco", "markers", "page_quad", "homography", "none"]
|
|
14
|
+
FieldType = Literal["mcq", "grid_digits", "grid_alpha", "custom"]
|
|
15
|
+
BlockDirection = Literal["horizontal", "vertical"]
|
|
16
|
+
OriginMode = Literal["center", "top_left"]
|
|
17
|
+
ValidatorType = Literal["tr_tckn", "luhn", "digits", "non_empty"]
|
|
18
|
+
|
|
19
|
+
_RANGE_PATTERN = re.compile(r"^([^\.\d]+)(\d+)\.{2,3}(\d+)$")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def expand_field_labels(raw_labels: list[str]) -> list[str]:
|
|
23
|
+
"""Expand concise range expressions such as 'q1..25' or 'id01..11'."""
|
|
24
|
+
expanded: list[str] = []
|
|
25
|
+
seen: set[str] = set()
|
|
26
|
+
for token in raw_labels:
|
|
27
|
+
match = _RANGE_PATTERN.match(token)
|
|
28
|
+
if match:
|
|
29
|
+
prefix, start_s, end_s = match.groups()
|
|
30
|
+
start, end = int(start_s), int(end_s)
|
|
31
|
+
if end < start:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
f"Invalid label range '{token}': end ({end}) must be >= start ({start})."
|
|
34
|
+
)
|
|
35
|
+
pad = len(start_s) if start_s.startswith("0") and len(start_s) > 1 else 0
|
|
36
|
+
for idx in range(start, end + 1):
|
|
37
|
+
label = f"{prefix}{idx:0{pad}d}" if pad else f"{prefix}{idx}"
|
|
38
|
+
if label in seen:
|
|
39
|
+
raise ValueError(f"Duplicate expanded label '{label}' in '{token}'.")
|
|
40
|
+
seen.add(label)
|
|
41
|
+
expanded.append(label)
|
|
42
|
+
else:
|
|
43
|
+
if token in seen:
|
|
44
|
+
raise ValueError(f"Duplicate label '{token}'.")
|
|
45
|
+
seen.add(token)
|
|
46
|
+
expanded.append(token)
|
|
47
|
+
return expanded
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class BubbleCoord(BaseModel):
|
|
51
|
+
"""Canonical coordinate specification for a single bubble."""
|
|
52
|
+
|
|
53
|
+
field_id: str
|
|
54
|
+
option: str
|
|
55
|
+
cx: float
|
|
56
|
+
cy: float
|
|
57
|
+
radius: float
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class RegistrationConfig(BaseModel):
|
|
61
|
+
"""Page alignment and perspective rectification settings."""
|
|
62
|
+
|
|
63
|
+
mode: RegistrationMode = "aruco"
|
|
64
|
+
aruco_dict: str = "DICT_4X4_50"
|
|
65
|
+
aruco_ids: tuple[int, int, int, int] = (0, 1, 2, 3)
|
|
66
|
+
target_corners: list[tuple[float, float]] | None = None
|
|
67
|
+
|
|
68
|
+
# Concentric / custom template marker mode
|
|
69
|
+
marker_path: str | None = None
|
|
70
|
+
sheet_to_marker_width_ratio: float = Field(default=17.0, gt=1.0)
|
|
71
|
+
min_match_score: float = Field(default=0.30, ge=0.0, le=1.0)
|
|
72
|
+
max_match_variation: float = Field(default=0.45, ge=0.0, le=1.0)
|
|
73
|
+
scale_range: tuple[float, float] = (0.35, 1.15)
|
|
74
|
+
scale_steps: int = Field(default=16, ge=2, le=64)
|
|
75
|
+
split_ratio_x: float = Field(default=0.50, gt=0.1, lt=0.9)
|
|
76
|
+
split_ratio_y: float = Field(default=0.50, gt=0.1, lt=0.9)
|
|
77
|
+
erode_subtract: bool = True
|
|
78
|
+
auto_rotate: bool = True
|
|
79
|
+
|
|
80
|
+
# Page quad mode
|
|
81
|
+
min_area_ratio: float = Field(default=0.18, gt=0.01, lt=1.0)
|
|
82
|
+
morph_kernel: tuple[int, int] = (9, 9)
|
|
83
|
+
|
|
84
|
+
# Feature-based homography mode
|
|
85
|
+
reference_path: str | None = None
|
|
86
|
+
max_features: int = Field(default=1500, ge=100, le=10000)
|
|
87
|
+
good_match_ratio: float = Field(default=0.20, gt=0.02, le=1.0)
|
|
88
|
+
|
|
89
|
+
@model_validator(mode="after")
|
|
90
|
+
def _validate_target_corners(self) -> RegistrationConfig:
|
|
91
|
+
if self.target_corners is not None and len(self.target_corners) != 4:
|
|
92
|
+
raise ValueError("target_corners must contain exactly 4 (x, y) coordinates.")
|
|
93
|
+
if self.scale_range[0] <= 0 or self.scale_range[1] <= self.scale_range[0]:
|
|
94
|
+
raise ValueError("scale_range must satisfy 0 < min_scale < max_scale.")
|
|
95
|
+
return self
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class DetectionConfig(BaseModel):
|
|
99
|
+
"""Hybrid shape-aware bubble detection and HITL confidence parameters."""
|
|
100
|
+
|
|
101
|
+
fill_threshold: float = Field(default=0.26, gt=0.0, lt=1.0)
|
|
102
|
+
blank_floor: float = Field(default=0.14, ge=0.0, lt=1.0)
|
|
103
|
+
min_separation: float = Field(default=0.09, ge=0.0, lt=1.0)
|
|
104
|
+
review_confidence_threshold: float = Field(default=0.72, ge=0.0, le=1.0)
|
|
105
|
+
inner_radius_ratio: float = Field(default=0.70, gt=0.2, le=1.0)
|
|
106
|
+
ring_inner_ratio: float = Field(default=1.12, gt=1.0, le=2.0)
|
|
107
|
+
ring_outer_ratio: float = Field(default=1.48, gt=1.1, le=2.5)
|
|
108
|
+
fill_delta: float = Field(default=22.0, gt=1.0, le=150.0)
|
|
109
|
+
ink_delta: float = Field(default=36.0, gt=1.0, le=200.0)
|
|
110
|
+
multi_mark_ratio: float = Field(default=0.70, gt=0.2, le=1.0)
|
|
111
|
+
normalize_illumination: bool = True
|
|
112
|
+
|
|
113
|
+
@model_validator(mode="after")
|
|
114
|
+
def _validate_thresholds(self) -> DetectionConfig:
|
|
115
|
+
if self.blank_floor >= self.fill_threshold:
|
|
116
|
+
raise ValueError("blank_floor must be strictly smaller than fill_threshold.")
|
|
117
|
+
if self.ring_outer_ratio <= self.ring_inner_ratio:
|
|
118
|
+
raise ValueError("ring_outer_ratio must be greater than ring_inner_ratio.")
|
|
119
|
+
return self
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class FieldBlock(BaseModel):
|
|
123
|
+
"""A structured rectangular grid of bubbles representing one or more fields."""
|
|
124
|
+
|
|
125
|
+
name: str = Field(min_length=1)
|
|
126
|
+
field_type: FieldType = "mcq"
|
|
127
|
+
direction: BlockDirection = "horizontal"
|
|
128
|
+
origin: tuple[float, float]
|
|
129
|
+
origin_mode: OriginMode = "center"
|
|
130
|
+
bubble_radius: float = Field(default=14.0, gt=2.0)
|
|
131
|
+
bubbles_gap: float = Field(gt=2.0)
|
|
132
|
+
labels_gap: float = Field(gt=2.0)
|
|
133
|
+
options: list[str] = Field(min_length=1)
|
|
134
|
+
labels: list[str] = Field(min_length=1)
|
|
135
|
+
allow_multiple: bool = False
|
|
136
|
+
empty_value: str = ""
|
|
137
|
+
group_as: str | None = None
|
|
138
|
+
validator: ValidatorType | None = None
|
|
139
|
+
|
|
140
|
+
@field_validator("options")
|
|
141
|
+
@classmethod
|
|
142
|
+
def _unique_options(cls, value: list[str]) -> list[str]:
|
|
143
|
+
if len(set(value)) != len(value):
|
|
144
|
+
raise ValueError("Bubble options within a FieldBlock must be unique.")
|
|
145
|
+
return value
|
|
146
|
+
|
|
147
|
+
def expanded_labels(self) -> list[str]:
|
|
148
|
+
"""Return fully expanded field labels in display order."""
|
|
149
|
+
return expand_field_labels(self.labels)
|
|
150
|
+
|
|
151
|
+
def iter_field_bubbles(self) -> list[tuple[str, list[BubbleCoord]]]:
|
|
152
|
+
"""Generate exact canonical bubble center coordinates for every field in this block."""
|
|
153
|
+
labels = self.expanded_labels()
|
|
154
|
+
start_x, start_y = self.origin
|
|
155
|
+
if self.origin_mode == "top_left":
|
|
156
|
+
start_x += self.bubble_radius
|
|
157
|
+
start_y += self.bubble_radius
|
|
158
|
+
|
|
159
|
+
fields: list[tuple[str, list[BubbleCoord]]] = []
|
|
160
|
+
for field_idx, field_id in enumerate(labels):
|
|
161
|
+
coords: list[BubbleCoord] = []
|
|
162
|
+
for opt_idx, option in enumerate(self.options):
|
|
163
|
+
if self.direction == "horizontal":
|
|
164
|
+
cx = start_x + opt_idx * self.bubbles_gap
|
|
165
|
+
cy = start_y + field_idx * self.labels_gap
|
|
166
|
+
else:
|
|
167
|
+
cx = start_x + field_idx * self.labels_gap
|
|
168
|
+
cy = start_y + opt_idx * self.bubbles_gap
|
|
169
|
+
coords.append(
|
|
170
|
+
BubbleCoord(
|
|
171
|
+
field_id=field_id,
|
|
172
|
+
option=option,
|
|
173
|
+
cx=round(cx, 2),
|
|
174
|
+
cy=round(cy, 2),
|
|
175
|
+
radius=self.bubble_radius,
|
|
176
|
+
)
|
|
177
|
+
)
|
|
178
|
+
fields.append((field_id, coords))
|
|
179
|
+
return fields
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class Template(BaseModel):
|
|
183
|
+
"""Complete OMR sheet layout, registration, and detection specification."""
|
|
184
|
+
|
|
185
|
+
version: str = "2.0"
|
|
186
|
+
name: str = Field(min_length=1)
|
|
187
|
+
description: str = ""
|
|
188
|
+
page_width: int = Field(gt=50)
|
|
189
|
+
page_height: int = Field(gt=50)
|
|
190
|
+
registration: RegistrationConfig = Field(default_factory=RegistrationConfig)
|
|
191
|
+
detection: DetectionConfig = Field(default_factory=DetectionConfig)
|
|
192
|
+
blocks: list[FieldBlock] = Field(min_length=1)
|
|
193
|
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
|
194
|
+
|
|
195
|
+
@model_validator(mode="after")
|
|
196
|
+
def _validate_layout(self) -> Template:
|
|
197
|
+
block_names: set[str] = set()
|
|
198
|
+
seen_fields: set[str] = set()
|
|
199
|
+
margin = 1.0
|
|
200
|
+
|
|
201
|
+
for block in self.blocks:
|
|
202
|
+
if block.name in block_names:
|
|
203
|
+
raise ValueError(f"Duplicate block name '{block.name}'.")
|
|
204
|
+
block_names.add(block.name)
|
|
205
|
+
|
|
206
|
+
for field_id, bubbles in block.iter_field_bubbles():
|
|
207
|
+
if field_id in seen_fields:
|
|
208
|
+
raise ValueError(
|
|
209
|
+
f"Field label '{field_id}' in block '{block.name}' overlaps an existing field."
|
|
210
|
+
)
|
|
211
|
+
seen_fields.add(field_id)
|
|
212
|
+
|
|
213
|
+
for bubble in bubbles:
|
|
214
|
+
if (
|
|
215
|
+
bubble.cx - bubble.radius < -margin
|
|
216
|
+
or bubble.cy - bubble.radius < -margin
|
|
217
|
+
or bubble.cx + bubble.radius > self.page_width + margin
|
|
218
|
+
or bubble.cy + bubble.radius > self.page_height + margin
|
|
219
|
+
):
|
|
220
|
+
raise ValueError(
|
|
221
|
+
f"Bubble '{field_id}:{bubble.option}' in block '{block.name}' "
|
|
222
|
+
f"at ({bubble.cx}, {bubble.cy}, r={bubble.radius}) exceeds page "
|
|
223
|
+
f"dimensions ({self.page_width}x{self.page_height})."
|
|
224
|
+
)
|
|
225
|
+
return self
|
|
226
|
+
|
|
227
|
+
def all_field_ids(self) -> list[str]:
|
|
228
|
+
"""Return ordered list of all expanded field IDs."""
|
|
229
|
+
ids: list[str] = []
|
|
230
|
+
for block in self.blocks:
|
|
231
|
+
ids.extend(block.expanded_labels())
|
|
232
|
+
return ids
|
|
233
|
+
|
|
234
|
+
def grouped_field_names(self) -> list[str]:
|
|
235
|
+
"""Return names of logical output columns (grouped blocks collapse into one column)."""
|
|
236
|
+
columns: list[str] = []
|
|
237
|
+
for block in self.blocks:
|
|
238
|
+
if block.group_as:
|
|
239
|
+
if block.group_as not in columns:
|
|
240
|
+
columns.append(block.group_as)
|
|
241
|
+
else:
|
|
242
|
+
columns.extend(block.expanded_labels())
|
|
243
|
+
return columns
|
|
244
|
+
|
|
245
|
+
@classmethod
|
|
246
|
+
def from_file(cls, path: str | Path) -> Template:
|
|
247
|
+
"""Load and validate a Template from JSON or YAML."""
|
|
248
|
+
file_path = Path(path)
|
|
249
|
+
raw = file_path.read_text(encoding="utf-8")
|
|
250
|
+
if file_path.suffix.lower() in {".yaml", ".yml"}:
|
|
251
|
+
data = yaml.safe_load(raw)
|
|
252
|
+
else:
|
|
253
|
+
data = json.loads(raw)
|
|
254
|
+
template = cls.model_validate(data)
|
|
255
|
+
# Resolve relative registration asset paths against the template's parent directory
|
|
256
|
+
if template.registration.marker_path:
|
|
257
|
+
marker_p = Path(template.registration.marker_path)
|
|
258
|
+
if not marker_p.is_absolute():
|
|
259
|
+
resolved = file_path.parent / marker_p
|
|
260
|
+
if resolved.exists():
|
|
261
|
+
template.registration.marker_path = str(resolved)
|
|
262
|
+
if template.registration.reference_path:
|
|
263
|
+
ref_p = Path(template.registration.reference_path)
|
|
264
|
+
if not ref_p.is_absolute():
|
|
265
|
+
resolved = file_path.parent / ref_p
|
|
266
|
+
if resolved.exists():
|
|
267
|
+
template.registration.reference_path = str(resolved)
|
|
268
|
+
return template
|
|
269
|
+
|
|
270
|
+
def to_file(self, path: str | Path) -> Path:
|
|
271
|
+
"""Serialize the template to JSON or YAML."""
|
|
272
|
+
file_path = Path(path)
|
|
273
|
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
|
274
|
+
payload = self.model_dump(mode="json")
|
|
275
|
+
if file_path.suffix.lower() in {".yaml", ".yml"}:
|
|
276
|
+
file_path.write_text(
|
|
277
|
+
yaml.safe_dump(payload, sort_keys=False, allow_unicode=True),
|
|
278
|
+
encoding="utf-8",
|
|
279
|
+
)
|
|
280
|
+
else:
|
|
281
|
+
file_path.write_text(
|
|
282
|
+
json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
|
|
283
|
+
encoding="utf-8",
|
|
284
|
+
)
|
|
285
|
+
return file_path
|
omrkit/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Computer vision pipeline for OMRKit."""
|
|
2
|
+
|
|
3
|
+
from omrkit.vision.detector import HybridBubbleDetector
|
|
4
|
+
from omrkit.vision.grid_finder import DetectedCircle, detect_layout_from_blank
|
|
5
|
+
from omrkit.vision.preprocess import ensure_grayscale, normalize_illumination, rotate_image
|
|
6
|
+
from omrkit.vision.qr import (
|
|
7
|
+
detect_sheet_qr,
|
|
8
|
+
encode_sheet_qr_payload,
|
|
9
|
+
parse_sheet_qr_payload,
|
|
10
|
+
render_qr_matrix,
|
|
11
|
+
)
|
|
12
|
+
from omrkit.vision.registration import RegistrationError, RegistrationResult, register_sheet
|
|
13
|
+
from omrkit.vision.visualizer import render_annotated_sheet
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"DetectedCircle",
|
|
17
|
+
"HybridBubbleDetector",
|
|
18
|
+
"RegistrationError",
|
|
19
|
+
"RegistrationResult",
|
|
20
|
+
"detect_layout_from_blank",
|
|
21
|
+
"detect_sheet_qr",
|
|
22
|
+
"encode_sheet_qr_payload",
|
|
23
|
+
"ensure_grayscale",
|
|
24
|
+
"normalize_illumination",
|
|
25
|
+
"parse_sheet_qr_payload",
|
|
26
|
+
"register_sheet",
|
|
27
|
+
"render_annotated_sheet",
|
|
28
|
+
"render_qr_matrix",
|
|
29
|
+
"rotate_image",
|
|
30
|
+
]
|