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/__init__.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""OMRKit — Modern Optical Mark Recognition SDK, Sheet Generator & Exam Psychometrics."""
|
|
2
|
+
|
|
3
|
+
from omrkit.core.auto_scanner import (
|
|
4
|
+
resolve_template_for_image,
|
|
5
|
+
scan_file_auto,
|
|
6
|
+
scan_image_auto,
|
|
7
|
+
)
|
|
8
|
+
from omrkit.core.benchmark import BenchmarkScenarioResult, run_benchmark
|
|
9
|
+
from omrkit.core.migrator import migrate_legacy_template_dict, migrate_legacy_template_file
|
|
10
|
+
from omrkit.core.scanner import OMRScanner
|
|
11
|
+
from omrkit.core.validators import validate_luhn, validate_tr_tckn
|
|
12
|
+
from omrkit.generator.pdf_sheet import GeneratedSheet, SheetGenerator
|
|
13
|
+
from omrkit.generator.presets import IdGridSpec, SheetSpec, get_sheet_preset, get_sheet_presets
|
|
14
|
+
from omrkit.grading.analytics import compute_exam_analytics
|
|
15
|
+
from omrkit.grading.grader import ExamGrader
|
|
16
|
+
from omrkit.io.exporters import export_csv, export_excel, export_json, export_pdf_scorecard
|
|
17
|
+
from omrkit.models import (
|
|
18
|
+
AnswerKey,
|
|
19
|
+
BatchResult,
|
|
20
|
+
DetectionConfig,
|
|
21
|
+
ExamAnalytics,
|
|
22
|
+
FieldBlock,
|
|
23
|
+
FieldReading,
|
|
24
|
+
GradingPolicy,
|
|
25
|
+
GradingReport,
|
|
26
|
+
RegistrationConfig,
|
|
27
|
+
ReviewItem,
|
|
28
|
+
SheetResult,
|
|
29
|
+
StudentGrade,
|
|
30
|
+
Template,
|
|
31
|
+
)
|
|
32
|
+
from omrkit.vision.grid_finder import detect_layout_from_blank
|
|
33
|
+
from omrkit.vision.qr import detect_sheet_qr
|
|
34
|
+
|
|
35
|
+
__version__ = "2.1.0"
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"AnswerKey",
|
|
39
|
+
"BatchResult",
|
|
40
|
+
"BenchmarkScenarioResult",
|
|
41
|
+
"DetectionConfig",
|
|
42
|
+
"ExamAnalytics",
|
|
43
|
+
"ExamGrader",
|
|
44
|
+
"FieldBlock",
|
|
45
|
+
"FieldReading",
|
|
46
|
+
"GeneratedSheet",
|
|
47
|
+
"GradingPolicy",
|
|
48
|
+
"GradingReport",
|
|
49
|
+
"IdGridSpec",
|
|
50
|
+
"OMRScanner",
|
|
51
|
+
"RegistrationConfig",
|
|
52
|
+
"ReviewItem",
|
|
53
|
+
"SheetGenerator",
|
|
54
|
+
"SheetResult",
|
|
55
|
+
"SheetSpec",
|
|
56
|
+
"StudentGrade",
|
|
57
|
+
"Template",
|
|
58
|
+
"__version__",
|
|
59
|
+
"compute_exam_analytics",
|
|
60
|
+
"detect_layout_from_blank",
|
|
61
|
+
"detect_sheet_qr",
|
|
62
|
+
"export_csv",
|
|
63
|
+
"export_excel",
|
|
64
|
+
"export_json",
|
|
65
|
+
"export_pdf_scorecard",
|
|
66
|
+
"get_sheet_preset",
|
|
67
|
+
"get_sheet_presets",
|
|
68
|
+
"migrate_legacy_template_dict",
|
|
69
|
+
"migrate_legacy_template_file",
|
|
70
|
+
"resolve_template_for_image",
|
|
71
|
+
"run_benchmark",
|
|
72
|
+
"scan_file_auto",
|
|
73
|
+
"scan_image_auto",
|
|
74
|
+
"validate_luhn",
|
|
75
|
+
"validate_tr_tckn",
|
|
76
|
+
]
|
omrkit/__main__.py
ADDED
omrkit/api/__init__.py
ADDED
omrkit/api/app.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""FastAPI application factory serving OMRKit REST API and compiled Web Studio SPA."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Awaitable, Callable
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from fastapi import FastAPI, Request, Response
|
|
9
|
+
from fastapi.middleware.cors import CORSMiddleware
|
|
10
|
+
from fastapi.responses import FileResponse, HTMLResponse
|
|
11
|
+
from fastapi.staticfiles import StaticFiles
|
|
12
|
+
|
|
13
|
+
from omrkit.api.routes import router
|
|
14
|
+
|
|
15
|
+
STATIC_DIR = Path(__file__).parent / "static"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def create_app() -> FastAPI:
|
|
19
|
+
"""Create and configure the OMRKit FastAPI application."""
|
|
20
|
+
app = FastAPI(
|
|
21
|
+
title="OMRKit API & Studio",
|
|
22
|
+
description=(
|
|
23
|
+
"Modern Optical Mark Recognition API: ArUco/marker registration, hybrid "
|
|
24
|
+
"confidence-scored bubble detection, printable PDF sheet generation, "
|
|
25
|
+
"and Classical Test Theory exam psychometrics."
|
|
26
|
+
),
|
|
27
|
+
version="2.1.0",
|
|
28
|
+
docs_url="/docs",
|
|
29
|
+
redoc_url="/redoc",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
app.add_middleware(
|
|
33
|
+
CORSMiddleware,
|
|
34
|
+
allow_origins=["*"],
|
|
35
|
+
allow_credentials=False,
|
|
36
|
+
allow_methods=["*"],
|
|
37
|
+
allow_headers=["*"],
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
@app.middleware("http")
|
|
41
|
+
async def add_security_headers(
|
|
42
|
+
request: Request,
|
|
43
|
+
call_next: Callable[[Request], Awaitable[Response]],
|
|
44
|
+
) -> Response:
|
|
45
|
+
response = await call_next(request)
|
|
46
|
+
response.headers.setdefault("X-Content-Type-Options", "nosniff")
|
|
47
|
+
response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
48
|
+
# Allow self-hosted camera access for Live Browser Camera Scanner on HTTPS demos
|
|
49
|
+
response.headers.setdefault(
|
|
50
|
+
"Permissions-Policy",
|
|
51
|
+
"camera=(self), microphone=(), geolocation=()",
|
|
52
|
+
)
|
|
53
|
+
return response
|
|
54
|
+
|
|
55
|
+
app.include_router(router)
|
|
56
|
+
|
|
57
|
+
assets_dir = STATIC_DIR / "assets"
|
|
58
|
+
if assets_dir.exists():
|
|
59
|
+
app.mount("/assets", StaticFiles(directory=assets_dir), name="studio-assets")
|
|
60
|
+
|
|
61
|
+
index_html = STATIC_DIR / "index.html"
|
|
62
|
+
|
|
63
|
+
@app.get("/", include_in_schema=False, response_model=None)
|
|
64
|
+
def serve_root() -> FileResponse | HTMLResponse:
|
|
65
|
+
if index_html.exists():
|
|
66
|
+
return FileResponse(index_html)
|
|
67
|
+
return HTMLResponse(
|
|
68
|
+
"<html><body style='font-family:sans-serif;padding:2rem;'>"
|
|
69
|
+
"<h1>OMRKit v2.1 API is running</h1>"
|
|
70
|
+
"<p>Interactive API docs: <a href='/docs'>/docs</a></p>"
|
|
71
|
+
"<p>Build the Web Studio frontend via <code>cd studio && npm run build</code>.</p>"
|
|
72
|
+
"</body></html>"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return app
|
omrkit/api/routes.py
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
"""FastAPI REST API routes powering OMRKit Web Studio and third-party integrations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import io
|
|
7
|
+
import json
|
|
8
|
+
import random
|
|
9
|
+
import zipfile
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import cv2
|
|
13
|
+
import numpy as np
|
|
14
|
+
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
|
|
15
|
+
from fastapi.responses import Response
|
|
16
|
+
from pydantic import BaseModel, Field
|
|
17
|
+
|
|
18
|
+
from omrkit.api.settings import APISettings, get_api_settings
|
|
19
|
+
from omrkit.core.auto_scanner import scan_bytes_auto
|
|
20
|
+
from omrkit.core.benchmark import apply_camera_distortion, render_synthetic_filled_sheet
|
|
21
|
+
from omrkit.core.migrator import migrate_legacy_template_dict
|
|
22
|
+
from omrkit.core.scanner import OMRScanner
|
|
23
|
+
from omrkit.generator.pdf_sheet import SheetGenerator
|
|
24
|
+
from omrkit.generator.presets import SheetSpec, get_sheet_preset, get_sheet_presets
|
|
25
|
+
from omrkit.grading.grader import ExamGrader
|
|
26
|
+
from omrkit.io.exporters import (
|
|
27
|
+
export_csv_string,
|
|
28
|
+
export_excel_bytes,
|
|
29
|
+
export_pdf_scorecard_bytes,
|
|
30
|
+
)
|
|
31
|
+
from omrkit.io.loader import DocumentLoadError, load_bytes
|
|
32
|
+
from omrkit.models.grading import AnswerKey, GradingPolicy, GradingReport, StudentGrade
|
|
33
|
+
from omrkit.models.scan import SheetResult
|
|
34
|
+
from omrkit.models.template import Template
|
|
35
|
+
from omrkit.vision.grid_finder import detect_layout_from_blank
|
|
36
|
+
from omrkit.vision.visualizer import render_annotated_sheet
|
|
37
|
+
|
|
38
|
+
router = APIRouter(prefix="/api", tags=["omrkit"])
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def _read_bounded_upload(upload: UploadFile, settings: APISettings) -> bytes:
|
|
42
|
+
"""Read an uploaded file enforcing the configured byte limit cleanly."""
|
|
43
|
+
limit = settings.max_upload_bytes
|
|
44
|
+
data = await upload.read(limit + 1)
|
|
45
|
+
if len(data) > limit:
|
|
46
|
+
raise HTTPException(
|
|
47
|
+
status_code=413,
|
|
48
|
+
detail=(
|
|
49
|
+
f"File '{upload.filename or 'upload'}' exceeds maximum allowed upload size "
|
|
50
|
+
f"of {settings.max_upload_mb} MB."
|
|
51
|
+
),
|
|
52
|
+
)
|
|
53
|
+
return data
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _encode_image_data_url(image_bgr: np.ndarray, fmt: str = ".jpg", quality: int = 86) -> str:
|
|
57
|
+
params = [cv2.IMWRITE_JPEG_QUALITY, quality] if fmt == ".jpg" else []
|
|
58
|
+
ok, encoded = cv2.imencode(fmt, image_bgr, params)
|
|
59
|
+
if not ok:
|
|
60
|
+
raise RuntimeError("Failed to encode image buffer.")
|
|
61
|
+
mime = "image/jpeg" if fmt == ".jpg" else "image/png"
|
|
62
|
+
b64 = base64.b64encode(encoded.tobytes()).decode("ascii")
|
|
63
|
+
return f"data:{mime};base64,{b64}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _encode_overlay(warped_bgr: np.ndarray, result: SheetResult) -> str:
|
|
67
|
+
annotated = render_annotated_sheet(warped_bgr, result)
|
|
68
|
+
h, w = annotated.shape[:2]
|
|
69
|
+
if max(h, w) > 1500:
|
|
70
|
+
scale = 1500.0 / float(max(h, w))
|
|
71
|
+
annotated = cv2.resize(
|
|
72
|
+
annotated,
|
|
73
|
+
(round(w * scale), round(h * scale)),
|
|
74
|
+
interpolation=cv2.INTER_AREA,
|
|
75
|
+
)
|
|
76
|
+
return _encode_image_data_url(annotated, fmt=".jpg", quality=85)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class GradeRequest(BaseModel):
|
|
80
|
+
"""Request body for grading scanned sheets with an answer key and policy."""
|
|
81
|
+
|
|
82
|
+
sheets: list[SheetResult]
|
|
83
|
+
answer_key: AnswerKey
|
|
84
|
+
policy: GradingPolicy = Field(default_factory=GradingPolicy)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ExportRequest(BaseModel):
|
|
88
|
+
"""Request body for exporting scan and optional grading results."""
|
|
89
|
+
|
|
90
|
+
sheets: list[SheetResult]
|
|
91
|
+
report: GradingReport | None = None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class ScorecardRequest(BaseModel):
|
|
95
|
+
"""Request body for rendering a single student's PDF scorecard."""
|
|
96
|
+
|
|
97
|
+
grade: StudentGrade
|
|
98
|
+
exam_name: str = "Exam Scorecard"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class MigrateTemplateRequest(BaseModel):
|
|
102
|
+
"""Request body for migrating a legacy OMRChecker v1 template."""
|
|
103
|
+
|
|
104
|
+
name: str = "migrated_template"
|
|
105
|
+
legacy_template: dict[str, Any]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@router.get("/health")
|
|
109
|
+
def health_check() -> dict[str, Any]:
|
|
110
|
+
"""Return service health, package version, demo mode flag, and upload guardrails."""
|
|
111
|
+
settings = get_api_settings()
|
|
112
|
+
return {
|
|
113
|
+
"status": "ok",
|
|
114
|
+
"service": "omrkit",
|
|
115
|
+
"version": "2.1.0",
|
|
116
|
+
"demo_mode": settings.demo_mode,
|
|
117
|
+
"limits": settings.limits_dict(),
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@router.get("/presets")
|
|
122
|
+
def list_presets() -> dict[str, Any]:
|
|
123
|
+
"""Return built-in optical sheet presets (with exact templates) and grading policies."""
|
|
124
|
+
generator = SheetGenerator()
|
|
125
|
+
sheet_presets: list[dict[str, Any]] = []
|
|
126
|
+
for preset_id, spec in get_sheet_presets().items():
|
|
127
|
+
generated = generator.generate(spec)
|
|
128
|
+
sheet_presets.append(
|
|
129
|
+
{
|
|
130
|
+
"id": preset_id,
|
|
131
|
+
"spec": spec.model_dump(mode="json"),
|
|
132
|
+
"template": generated.template.model_dump(mode="json"),
|
|
133
|
+
"sample_answer_key": generated.sample_answer_key.model_dump(mode="json"),
|
|
134
|
+
}
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
policy_names = ["standard", "yks_tyt", "kpss", "lgs", "sat_legacy"]
|
|
138
|
+
grading_policies = [GradingPolicy.preset(name).model_dump(mode="json") for name in policy_names]
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
"sheet_presets": sheet_presets,
|
|
142
|
+
"grading_policies": grading_policies,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@router.post("/generate")
|
|
147
|
+
def generate_sheet(spec: SheetSpec) -> dict[str, Any]:
|
|
148
|
+
"""Generate a printable PDF (base64), matching exact Template, and sample AnswerKey."""
|
|
149
|
+
generated = SheetGenerator().generate(spec)
|
|
150
|
+
pdf_b64 = base64.b64encode(generated.pdf_bytes).decode("ascii")
|
|
151
|
+
preview_page = load_bytes(generated.pdf_bytes, f"{spec.preset_id}.pdf", dpi=140)[0]
|
|
152
|
+
return {
|
|
153
|
+
"filename": f"{spec.preset_id}_sheet.pdf",
|
|
154
|
+
"pdf_base64": pdf_b64,
|
|
155
|
+
"preview_data_url": _encode_image_data_url(preview_page.image_bgr, fmt=".jpg", quality=88),
|
|
156
|
+
"template": generated.template.model_dump(mode="json"),
|
|
157
|
+
"sample_answer_key": generated.sample_answer_key.model_dump(mode="json"),
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@router.post("/generate/bundle")
|
|
162
|
+
def generate_sheet_bundle(spec: SheetSpec) -> Response:
|
|
163
|
+
"""Download a ZIP archive containing the PDF sheet, template.json, and answer_key.json."""
|
|
164
|
+
generated = SheetGenerator().generate(spec)
|
|
165
|
+
buf = io.BytesIO()
|
|
166
|
+
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
|
167
|
+
zf.writestr(f"{spec.preset_id}_sheet.pdf", generated.pdf_bytes)
|
|
168
|
+
zf.writestr(
|
|
169
|
+
"template.json",
|
|
170
|
+
json.dumps(generated.template.model_dump(mode="json"), indent=2),
|
|
171
|
+
)
|
|
172
|
+
zf.writestr(
|
|
173
|
+
"answer_key.json",
|
|
174
|
+
json.dumps(generated.sample_answer_key.model_dump(mode="json"), indent=2),
|
|
175
|
+
)
|
|
176
|
+
return Response(
|
|
177
|
+
content=buf.getvalue(),
|
|
178
|
+
media_type="application/zip",
|
|
179
|
+
headers={"Content-Disposition": f'attachment; filename="{spec.preset_id}_bundle.zip"'},
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
@router.post("/templates/validate")
|
|
184
|
+
def validate_template(template: Template) -> dict[str, Any]:
|
|
185
|
+
"""Validate a Template payload and return expanded bubble coordinates for canvas preview."""
|
|
186
|
+
preview_bubbles: list[dict[str, Any]] = []
|
|
187
|
+
for block in template.blocks:
|
|
188
|
+
for field_id, coords in block.iter_field_bubbles():
|
|
189
|
+
for c in coords:
|
|
190
|
+
preview_bubbles.append(
|
|
191
|
+
{
|
|
192
|
+
"block": block.name,
|
|
193
|
+
"field_id": field_id,
|
|
194
|
+
"option": c.option,
|
|
195
|
+
"cx": c.cx,
|
|
196
|
+
"cy": c.cy,
|
|
197
|
+
"radius": c.radius,
|
|
198
|
+
}
|
|
199
|
+
)
|
|
200
|
+
return {
|
|
201
|
+
"valid": True,
|
|
202
|
+
"name": template.name,
|
|
203
|
+
"blocks_count": len(template.blocks),
|
|
204
|
+
"fields_count": len(template.all_field_ids()),
|
|
205
|
+
"grouped_columns": template.grouped_field_names(),
|
|
206
|
+
"preview_bubbles": preview_bubbles,
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
@router.post("/templates/auto-detect")
|
|
211
|
+
async def auto_detect_template_layout(
|
|
212
|
+
file: UploadFile = File(...),
|
|
213
|
+
dpi: int = Form(200),
|
|
214
|
+
) -> dict[str, Any]:
|
|
215
|
+
"""Automatically detect circular bubble grids on an uploaded blank sheet image/PDF."""
|
|
216
|
+
settings = get_api_settings()
|
|
217
|
+
data = await _read_bounded_upload(file, settings)
|
|
218
|
+
fname = file.filename or "blank_sheet.png"
|
|
219
|
+
try:
|
|
220
|
+
page = load_bytes(data, filename=fname, dpi=dpi, max_pages=settings.max_pdf_pages)[0]
|
|
221
|
+
template, bubbles_count = detect_layout_from_blank(
|
|
222
|
+
page.image_bgr, template_name=fname.rsplit(".", 1)[0]
|
|
223
|
+
)
|
|
224
|
+
except (DocumentLoadError, ValueError) as exc:
|
|
225
|
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
"template": template.model_dump(mode="json"),
|
|
229
|
+
"detected_bubbles": bubbles_count,
|
|
230
|
+
"blocks_count": len(template.blocks),
|
|
231
|
+
"fields_count": len(template.all_field_ids()),
|
|
232
|
+
"image_data_url": _encode_image_data_url(page.image_bgr, fmt=".jpg", quality=88),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@router.post("/templates/migrate")
|
|
237
|
+
def migrate_legacy_template_endpoint(payload: MigrateTemplateRequest) -> dict[str, Any]:
|
|
238
|
+
"""Convert a legacy OMRChecker v1 template JSON to OMRKit v2.0 format."""
|
|
239
|
+
try:
|
|
240
|
+
template = migrate_legacy_template_dict(payload.legacy_template, name=payload.name)
|
|
241
|
+
except Exception as exc:
|
|
242
|
+
raise HTTPException(status_code=422, detail=f"Migration failed: {exc}") from exc
|
|
243
|
+
return {"template": template.model_dump(mode="json")}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
@router.post("/preview-image")
|
|
247
|
+
async def preview_uploaded_document(
|
|
248
|
+
file: UploadFile = File(...),
|
|
249
|
+
dpi: int = Form(200),
|
|
250
|
+
) -> dict[str, Any]:
|
|
251
|
+
"""Decode any uploaded image or PDF first page for the Visual Template Designer canvas."""
|
|
252
|
+
settings = get_api_settings()
|
|
253
|
+
data = await _read_bounded_upload(file, settings)
|
|
254
|
+
try:
|
|
255
|
+
pages = load_bytes(
|
|
256
|
+
data,
|
|
257
|
+
filename=file.filename or "upload.png",
|
|
258
|
+
dpi=dpi,
|
|
259
|
+
max_pages=settings.max_pdf_pages,
|
|
260
|
+
)
|
|
261
|
+
except DocumentLoadError as exc:
|
|
262
|
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
263
|
+
|
|
264
|
+
page = pages[0]
|
|
265
|
+
return {
|
|
266
|
+
"filename": page.source_name,
|
|
267
|
+
"page_count": len(pages),
|
|
268
|
+
"width": page.original_width,
|
|
269
|
+
"height": page.original_height,
|
|
270
|
+
"image_data_url": _encode_image_data_url(page.image_bgr, fmt=".jpg", quality=90),
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
@router.post("/scan")
|
|
275
|
+
async def scan_uploaded_sheets(
|
|
276
|
+
files: list[UploadFile] = File(...),
|
|
277
|
+
template_json: str = Form("auto"),
|
|
278
|
+
include_overlay: bool = Form(True),
|
|
279
|
+
dpi: int = Form(200),
|
|
280
|
+
) -> dict[str, Any]:
|
|
281
|
+
"""Scan uploaded images/PDFs against a template JSON or 'auto' (QR auto-detection)."""
|
|
282
|
+
settings = get_api_settings()
|
|
283
|
+
if len(files) > settings.max_files_per_scan:
|
|
284
|
+
raise HTTPException(
|
|
285
|
+
status_code=400,
|
|
286
|
+
detail=(
|
|
287
|
+
f"Too many files ({len(files)}); maximum allowed per request is "
|
|
288
|
+
f"{settings.max_files_per_scan}."
|
|
289
|
+
),
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
auto_mode = template_json.strip().lower() in {"", "auto"}
|
|
293
|
+
scanner: OMRScanner | None = None
|
|
294
|
+
template_name = "auto"
|
|
295
|
+
|
|
296
|
+
if not auto_mode:
|
|
297
|
+
try:
|
|
298
|
+
template = Template.model_validate(json.loads(template_json))
|
|
299
|
+
except Exception as exc:
|
|
300
|
+
raise HTTPException(status_code=422, detail=f"Invalid template JSON: {exc}") from exc
|
|
301
|
+
scanner = OMRScanner(template=template, dpi=dpi)
|
|
302
|
+
template_name = template.name
|
|
303
|
+
|
|
304
|
+
sheets: list[dict[str, Any]] = []
|
|
305
|
+
overlays: dict[str, str] = {}
|
|
306
|
+
total_elapsed = 0.0
|
|
307
|
+
flagged_count = 0
|
|
308
|
+
failed_count = 0
|
|
309
|
+
|
|
310
|
+
for upload in files:
|
|
311
|
+
raw_bytes = await _read_bounded_upload(upload, settings)
|
|
312
|
+
fname = upload.filename or "sheet.png"
|
|
313
|
+
try:
|
|
314
|
+
page_results = (
|
|
315
|
+
scan_bytes_auto(
|
|
316
|
+
raw_bytes,
|
|
317
|
+
filename=fname,
|
|
318
|
+
dpi=dpi,
|
|
319
|
+
max_pages=settings.max_pdf_pages,
|
|
320
|
+
)
|
|
321
|
+
if scanner is None
|
|
322
|
+
else scanner.scan_bytes(
|
|
323
|
+
raw_bytes,
|
|
324
|
+
filename=fname,
|
|
325
|
+
max_pages=settings.max_pdf_pages,
|
|
326
|
+
)
|
|
327
|
+
)
|
|
328
|
+
except DocumentLoadError as exc:
|
|
329
|
+
if "exceeding the configured limit" in str(exc):
|
|
330
|
+
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
|
331
|
+
failed_count += 1
|
|
332
|
+
sheets.append(
|
|
333
|
+
SheetResult(
|
|
334
|
+
sheet_id=fname,
|
|
335
|
+
source_file=fname,
|
|
336
|
+
template_name=template_name,
|
|
337
|
+
overall_confidence=0.0,
|
|
338
|
+
registration_method="auto" if auto_mode else "unknown",
|
|
339
|
+
registration_score=0.0,
|
|
340
|
+
error=str(exc),
|
|
341
|
+
).model_dump(mode="json")
|
|
342
|
+
)
|
|
343
|
+
continue
|
|
344
|
+
|
|
345
|
+
for result, warped_bgr in page_results:
|
|
346
|
+
total_elapsed += result.elapsed_ms
|
|
347
|
+
if result.error is not None:
|
|
348
|
+
failed_count += 1
|
|
349
|
+
elif result.review_items:
|
|
350
|
+
flagged_count += 1
|
|
351
|
+
sheets.append(result.model_dump(mode="json"))
|
|
352
|
+
|
|
353
|
+
if include_overlay and warped_bgr is not None:
|
|
354
|
+
overlays[result.sheet_id] = _encode_overlay(warped_bgr, result)
|
|
355
|
+
|
|
356
|
+
return {
|
|
357
|
+
"template_name": template_name,
|
|
358
|
+
"total_sheets": len(sheets),
|
|
359
|
+
"flagged_sheets": flagged_count,
|
|
360
|
+
"failed_sheets": failed_count,
|
|
361
|
+
"total_elapsed_ms": round(total_elapsed, 2),
|
|
362
|
+
"sheets": sheets,
|
|
363
|
+
"overlays": overlays,
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
@router.post("/demo/cohort")
|
|
368
|
+
def run_one_click_demo_cohort(preset_id: str = "quick_quiz_20") -> dict[str, Any]:
|
|
369
|
+
"""Synthesize, scan, and grade a realistic 5-student exam cohort for 1-click live demos."""
|
|
370
|
+
spec = get_sheet_preset(preset_id)
|
|
371
|
+
generated = SheetGenerator().generate(spec)
|
|
372
|
+
template = generated.template
|
|
373
|
+
answer_key = generated.sample_answer_key
|
|
374
|
+
blank = load_bytes(generated.pdf_bytes, f"{preset_id}.pdf", dpi=spec.dpi)[0].image_bgr
|
|
375
|
+
scanner = OMRScanner(template)
|
|
376
|
+
|
|
377
|
+
expected_map = answer_key.resolve_booklet(answer_key.default_booklet)
|
|
378
|
+
profiles = [
|
|
379
|
+
("student_01_top_scorer", 0.95, 0, 0.0, 0.0, "solid", False),
|
|
380
|
+
("student_02_mobile_shadow", 0.80, 0, 0.045, 0.30, "solid", False),
|
|
381
|
+
("student_03_rotated_checkmarks", 0.70, 90, 0.03, 0.18, "checkmark", False),
|
|
382
|
+
("student_04_hitl_multimark", 0.65, 0, 0.02, 0.12, "solid", True),
|
|
383
|
+
("student_05_struggling", 0.35, 180, 0.035, 0.20, "solid", False),
|
|
384
|
+
]
|
|
385
|
+
|
|
386
|
+
scanned_sheets: list[SheetResult] = []
|
|
387
|
+
overlays: dict[str, str] = {}
|
|
388
|
+
total_elapsed = 0.0
|
|
389
|
+
|
|
390
|
+
for idx, (sid, skill, rot, persp, shadow, style, inject_hitl) in enumerate(profiles):
|
|
391
|
+
rng = random.Random(700 + idx)
|
|
392
|
+
answers: dict[str, str] = {}
|
|
393
|
+
for block in template.blocks:
|
|
394
|
+
for f_idx, fid in enumerate(block.expanded_labels()):
|
|
395
|
+
if block.field_type == "mcq":
|
|
396
|
+
correct_opt = str(expected_map.get(fid, block.options[0]))
|
|
397
|
+
if inject_hitl and f_idx == 2:
|
|
398
|
+
# Intentional double-marked bubble to demonstrate HITL review queue
|
|
399
|
+
alt = next(o for o in block.options if o != correct_opt)
|
|
400
|
+
answers[fid] = correct_opt + alt
|
|
401
|
+
elif rng.random() < 0.08:
|
|
402
|
+
answers[fid] = ""
|
|
403
|
+
elif rng.random() < skill:
|
|
404
|
+
answers[fid] = correct_opt
|
|
405
|
+
else:
|
|
406
|
+
wrongs = [o for o in block.options if o != correct_opt]
|
|
407
|
+
answers[fid] = rng.choice(wrongs)
|
|
408
|
+
else:
|
|
409
|
+
answers[fid] = str((idx + f_idx + 1) % len(block.options))
|
|
410
|
+
answers[fid] = block.options[(idx + f_idx + 1) % len(block.options)]
|
|
411
|
+
|
|
412
|
+
marked = render_synthetic_filled_sheet(
|
|
413
|
+
blank, template, answers, mark_style=style, seed=700 + idx
|
|
414
|
+
)
|
|
415
|
+
distorted = apply_camera_distortion(
|
|
416
|
+
marked,
|
|
417
|
+
rotation_deg=rot,
|
|
418
|
+
perspective_strength=persp,
|
|
419
|
+
shadow_strength=shadow,
|
|
420
|
+
seed=700 + idx,
|
|
421
|
+
)
|
|
422
|
+
res, warped = scanner.scan_image(distorted, source_name=f"{sid}.jpg")
|
|
423
|
+
total_elapsed += res.elapsed_ms
|
|
424
|
+
scanned_sheets.append(res)
|
|
425
|
+
if warped is not None:
|
|
426
|
+
overlays[res.sheet_id] = _encode_overlay(warped, res)
|
|
427
|
+
|
|
428
|
+
policy = GradingPolicy.preset("yks_tyt")
|
|
429
|
+
report = ExamGrader(answer_key, policy).grade_batch(scanned_sheets)
|
|
430
|
+
|
|
431
|
+
return {
|
|
432
|
+
"template": template.model_dump(mode="json"),
|
|
433
|
+
"answer_key": answer_key.model_dump(mode="json"),
|
|
434
|
+
"scan_response": {
|
|
435
|
+
"template_name": template.name,
|
|
436
|
+
"total_sheets": len(scanned_sheets),
|
|
437
|
+
"flagged_sheets": sum(1 for s in scanned_sheets if s.review_items),
|
|
438
|
+
"failed_sheets": sum(1 for s in scanned_sheets if s.error is not None),
|
|
439
|
+
"total_elapsed_ms": round(total_elapsed, 2),
|
|
440
|
+
"sheets": [s.model_dump(mode="json") for s in scanned_sheets],
|
|
441
|
+
"overlays": overlays,
|
|
442
|
+
},
|
|
443
|
+
"grading_report": report.model_dump(mode="json"),
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@router.post("/grade")
|
|
448
|
+
def grade_sheets(payload: GradeRequest) -> dict[str, Any]:
|
|
449
|
+
"""Grade scanned sheets and return student grades + Classical Test Theory psychometrics."""
|
|
450
|
+
grader = ExamGrader(answer_key=payload.answer_key, policy=payload.policy)
|
|
451
|
+
report = grader.grade_batch(payload.sheets)
|
|
452
|
+
return report.model_dump(mode="json")
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
@router.post("/export/csv")
|
|
456
|
+
def export_csv_endpoint(payload: ExportRequest) -> Response:
|
|
457
|
+
"""Export scan and optional grading results as downloadable CSV."""
|
|
458
|
+
csv_text = export_csv_string(payload.sheets, report=payload.report)
|
|
459
|
+
return Response(
|
|
460
|
+
content=csv_text.encode("utf-8-sig"),
|
|
461
|
+
media_type="text/csv; charset=utf-8",
|
|
462
|
+
headers={"Content-Disposition": 'attachment; filename="omrkit_results.csv"'},
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
@router.post("/export/xlsx")
|
|
467
|
+
def export_xlsx_endpoint(payload: ExportRequest) -> Response:
|
|
468
|
+
"""Export formatted multi-sheet Excel workbook."""
|
|
469
|
+
try:
|
|
470
|
+
data = export_excel_bytes(payload.sheets, report=payload.report)
|
|
471
|
+
except RuntimeError as exc:
|
|
472
|
+
raise HTTPException(status_code=501, detail=str(exc)) from exc
|
|
473
|
+
return Response(
|
|
474
|
+
content=data,
|
|
475
|
+
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
476
|
+
headers={"Content-Disposition": 'attachment; filename="omrkit_report.xlsx"'},
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
@router.post("/export/scorecard")
|
|
481
|
+
def export_scorecard_endpoint(payload: ScorecardRequest) -> Response:
|
|
482
|
+
"""Export a single student's printable A4 PDF scorecard."""
|
|
483
|
+
pdf_bytes = export_pdf_scorecard_bytes(payload.grade, exam_name=payload.exam_name)
|
|
484
|
+
return Response(
|
|
485
|
+
content=pdf_bytes,
|
|
486
|
+
media_type="application/pdf",
|
|
487
|
+
headers={
|
|
488
|
+
"Content-Disposition": f'attachment; filename="{payload.grade.sheet_id}_scorecard.pdf"'
|
|
489
|
+
},
|
|
490
|
+
)
|