omrkit 2.1.0__tar.gz → 2.1.1__tar.gz

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.
Files changed (45) hide show
  1. {omrkit-2.1.0 → omrkit-2.1.1}/PKG-INFO +16 -13
  2. {omrkit-2.1.0 → omrkit-2.1.1}/README.md +14 -12
  3. {omrkit-2.1.0 → omrkit-2.1.1}/pyproject.toml +2 -1
  4. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/__init__.py +1 -2
  5. omrkit-2.1.1/src/omrkit/_version.py +3 -0
  6. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/api/app.py +3 -2
  7. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/api/routes.py +102 -21
  8. omrkit-2.1.1/src/omrkit/api/static/assets/index-DJfyticU.js +224 -0
  9. omrkit-2.1.0/src/omrkit/api/static/assets/index-DRPOjlrM.css → omrkit-2.1.1/src/omrkit/api/static/assets/index-qnvuF9WA.css +1 -1
  10. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/api/static/index.html +2 -2
  11. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/cli/app.py +16 -7
  12. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/benchmark.py +3 -1
  13. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/migrator.py +44 -6
  14. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/scanner.py +42 -0
  15. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/validators.py +3 -3
  16. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/generator/pdf_sheet.py +3 -2
  17. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/generator/presets.py +63 -9
  18. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/grading/grader.py +16 -8
  19. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/io/exporters.py +51 -25
  20. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/io/loader.py +24 -0
  21. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/models/scan.py +16 -1
  22. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/models/template.py +19 -4
  23. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/grid_finder.py +18 -7
  24. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/registration.py +12 -9
  25. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/visualizer.py +4 -1
  26. omrkit-2.1.0/src/omrkit/api/static/assets/index-BFfdzDls.js +0 -224
  27. {omrkit-2.1.0 → omrkit-2.1.1}/.gitignore +0 -0
  28. {omrkit-2.1.0 → omrkit-2.1.1}/LICENSE +0 -0
  29. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/__main__.py +0 -0
  30. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/api/__init__.py +0 -0
  31. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/api/settings.py +0 -0
  32. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/cli/__init__.py +0 -0
  33. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/__init__.py +0 -0
  34. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/core/auto_scanner.py +0 -0
  35. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/generator/__init__.py +0 -0
  36. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/grading/__init__.py +0 -0
  37. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/grading/analytics.py +0 -0
  38. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/io/__init__.py +0 -0
  39. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/models/__init__.py +0 -0
  40. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/models/grading.py +0 -0
  41. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/py.typed +0 -0
  42. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/__init__.py +0 -0
  43. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/detector.py +0 -0
  44. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/preprocess.py +0 -0
  45. {omrkit-2.1.0 → omrkit-2.1.1}/src/omrkit/vision/qr.py +0 -0
@@ -1,8 +1,9 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: omrkit
3
- Version: 2.1.0
3
+ Version: 2.1.1
4
4
  Summary: Modern Optical Mark Recognition engine with PDF/ArUco alignment, confidence-scored hybrid bubble detection, printable sheet generation, exam psychometrics, REST API, and Visual Web Studio.
5
5
  Project-URL: Homepage, https://github.com/duhanguler/omr
6
+ Project-URL: Live Demo, https://omrkit-studio.onrender.com/
6
7
  Project-URL: Repository, https://github.com/duhanguler/omr
7
8
  Project-URL: Documentation, https://github.com/duhanguler/omr#readme
8
9
  Project-URL: Changelog, https://github.com/duhanguler/omr/blob/main/CHANGELOG.md
@@ -63,15 +64,19 @@ Description-Content-Type: text/markdown
63
64
  **Zero-calibration Optical Mark Recognition engine with QR auto-template detection, blank-form auto-grid finder, live browser camera scanner, printable ArUco sheet generator, Classical Test Theory psychometrics, FastAPI REST API, and React Web Studio.**
64
65
 
65
66
  [![CI](https://github.com/duhanguler/omr/actions/workflows/ci.yml/badge.svg)](https://github.com/duhanguler/omr/actions/workflows/ci.yml)
66
- [![Release](https://img.shields.io/github/v/release/duhanguler/omr?style=flat-square&color=1D4ED8)](https://github.com/duhanguler/omr/releases)
67
+ [![PyPI](https://img.shields.io/pypi/v/omrkit?style=flat-square&color=0F8A5F&logo=pypi&logoColor=white)](https://pypi.org/project/omrkit/)
68
+ [![Live Demo](https://img.shields.io/badge/Live_Demo-OMRKit_Studio-1D4ED8?style=flat-square&logo=render&logoColor=white)](https://omrkit-studio.onrender.com/)
69
+ [![Release](https://img.shields.io/github/v/release/duhanguler/omr?style=flat-square&color=14181F)](https://github.com/duhanguler/omr/releases)
67
70
  [![License: MIT](https://img.shields.io/badge/License-MIT-0F8A5F.svg?style=flat-square)](LICENSE)
68
71
  [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-14181F.svg?style=flat-square)](pyproject.toml)
69
72
  [![Docker GHCR](https://img.shields.io/badge/Docker-ghcr.io%2Fduhanguler%2Fomr-2496ED.svg?style=flat-square)](https://github.com/duhanguler/omr/pkgs/container/omr)
70
73
 
71
- [English](README.md) · [Türkçe](README.tr.md) · [Deployment & PyPI Guide](docs/DEPLOYMENT.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md)
74
+ [**Try Live Demo**](https://omrkit-studio.onrender.com/) · [**PyPI**](https://pypi.org/project/omrkit/) · [English](README.md) · [Türkçe](README.tr.md) · [Deployment Guide](docs/DEPLOYMENT.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md)
72
75
 
73
76
  </div>
74
77
 
78
+ > **Live Web Studio Demo:** Try OMRKit directly in your browser at **[omrkit-studio.onrender.com](https://omrkit-studio.onrender.com/)** — click **Try Demo** in the top bar to scan & grade a 5-student exam cohort, test **Live Camera**, or generate printable ArUco + QR sheets. *(Hosted on Render's free tier; first load after inactivity may take ~20–30s to wake up.)*
79
+
75
80
  ---
76
81
 
77
82
  ## Why OMRKit?
@@ -114,21 +119,19 @@ Traditional open-source OMR scripts force you to hand-edit pixel coordinates in
114
119
 
115
120
  ## Quickstart (60 Seconds)
116
121
 
117
- ### 1. Run Instantly (Docker / One-Click Cloud Demo / Python)
122
+ ### 1. Install from PyPI, Run via Docker, or Try Online
118
123
 
119
124
  ```bash
120
- # Option A: Prebuilt official Docker image (zero build!)
121
- docker run -p 8000:8000 ghcr.io/duhanguler/omr:latest
125
+ # Option A: Install from PyPI (recommended)
126
+ pip install omrkit # Core CV engine + PDF + ArUco/QR + Sheet Generator + CLI
127
+ pip install "omrkit[all]" # Full platform: adds Web Studio, FastAPI REST API & Excel
122
128
 
123
- # Option B: Install from source (or `pip install "omrkit[all]"` once PyPI publishing is enabled)
124
- git clone https://github.com/duhanguler/omr.git
125
- cd omr
126
- pip install -e ".[all]"
129
+ # Option B: Prebuilt official Docker image (zero build!)
130
+ docker run -p 8000:8000 ghcr.io/duhanguler/omr:latest
127
131
  ```
128
132
 
129
- **One-Click Free Cloud Live Demo:**
130
- - **Render Blueprint:** [![Deploy to Render](https://img.shields.io/badge/Deploy_to-Render-14181F?style=flat-square&logo=render)](https://dashboard.render.com/blueprint/new?repo=https://github.com/duhanguler/omr)
131
- - **HuggingFace Spaces (Docker + Auto-Sync):** See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for the 2-minute free HTTPS setup (supports browser **Live Camera**!).
133
+ - **Live Public Demo:** [https://omrkit-studio.onrender.com/](https://omrkit-studio.onrender.com/) (OpenAPI docs at [`/docs`](https://omrkit-studio.onrender.com/docs))
134
+ - **Self-Host Your Own Copy (1-Click Free Render Blueprint):** [![Deploy to Render](https://img.shields.io/badge/Deploy_to-Render-14181F?style=flat-square&logo=render)](https://dashboard.render.com/blueprint/new?repo=https://github.com/duhanguler/omr) · See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for GHCR, Render & HuggingFace PRO options.
132
135
 
133
136
  ### 2. Generate a Print-Ready ArUco + QR Sheet
134
137
 
@@ -5,15 +5,19 @@
5
5
  **Zero-calibration Optical Mark Recognition engine with QR auto-template detection, blank-form auto-grid finder, live browser camera scanner, printable ArUco sheet generator, Classical Test Theory psychometrics, FastAPI REST API, and React Web Studio.**
6
6
 
7
7
  [![CI](https://github.com/duhanguler/omr/actions/workflows/ci.yml/badge.svg)](https://github.com/duhanguler/omr/actions/workflows/ci.yml)
8
- [![Release](https://img.shields.io/github/v/release/duhanguler/omr?style=flat-square&color=1D4ED8)](https://github.com/duhanguler/omr/releases)
8
+ [![PyPI](https://img.shields.io/pypi/v/omrkit?style=flat-square&color=0F8A5F&logo=pypi&logoColor=white)](https://pypi.org/project/omrkit/)
9
+ [![Live Demo](https://img.shields.io/badge/Live_Demo-OMRKit_Studio-1D4ED8?style=flat-square&logo=render&logoColor=white)](https://omrkit-studio.onrender.com/)
10
+ [![Release](https://img.shields.io/github/v/release/duhanguler/omr?style=flat-square&color=14181F)](https://github.com/duhanguler/omr/releases)
9
11
  [![License: MIT](https://img.shields.io/badge/License-MIT-0F8A5F.svg?style=flat-square)](LICENSE)
10
12
  [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-14181F.svg?style=flat-square)](pyproject.toml)
11
13
  [![Docker GHCR](https://img.shields.io/badge/Docker-ghcr.io%2Fduhanguler%2Fomr-2496ED.svg?style=flat-square)](https://github.com/duhanguler/omr/pkgs/container/omr)
12
14
 
13
- [English](README.md) · [Türkçe](README.tr.md) · [Deployment & PyPI Guide](docs/DEPLOYMENT.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md)
15
+ [**Try Live Demo**](https://omrkit-studio.onrender.com/) · [**PyPI**](https://pypi.org/project/omrkit/) · [English](README.md) · [Türkçe](README.tr.md) · [Deployment Guide](docs/DEPLOYMENT.md) · [Examples](examples/) · [Contributing](CONTRIBUTING.md)
14
16
 
15
17
  </div>
16
18
 
19
+ > **Live Web Studio Demo:** Try OMRKit directly in your browser at **[omrkit-studio.onrender.com](https://omrkit-studio.onrender.com/)** — click **Try Demo** in the top bar to scan & grade a 5-student exam cohort, test **Live Camera**, or generate printable ArUco + QR sheets. *(Hosted on Render's free tier; first load after inactivity may take ~20–30s to wake up.)*
20
+
17
21
  ---
18
22
 
19
23
  ## Why OMRKit?
@@ -56,21 +60,19 @@ Traditional open-source OMR scripts force you to hand-edit pixel coordinates in
56
60
 
57
61
  ## Quickstart (60 Seconds)
58
62
 
59
- ### 1. Run Instantly (Docker / One-Click Cloud Demo / Python)
63
+ ### 1. Install from PyPI, Run via Docker, or Try Online
60
64
 
61
65
  ```bash
62
- # Option A: Prebuilt official Docker image (zero build!)
63
- docker run -p 8000:8000 ghcr.io/duhanguler/omr:latest
66
+ # Option A: Install from PyPI (recommended)
67
+ pip install omrkit # Core CV engine + PDF + ArUco/QR + Sheet Generator + CLI
68
+ pip install "omrkit[all]" # Full platform: adds Web Studio, FastAPI REST API & Excel
64
69
 
65
- # Option B: Install from source (or `pip install "omrkit[all]"` once PyPI publishing is enabled)
66
- git clone https://github.com/duhanguler/omr.git
67
- cd omr
68
- pip install -e ".[all]"
70
+ # Option B: Prebuilt official Docker image (zero build!)
71
+ docker run -p 8000:8000 ghcr.io/duhanguler/omr:latest
69
72
  ```
70
73
 
71
- **One-Click Free Cloud Live Demo:**
72
- - **Render Blueprint:** [![Deploy to Render](https://img.shields.io/badge/Deploy_to-Render-14181F?style=flat-square&logo=render)](https://dashboard.render.com/blueprint/new?repo=https://github.com/duhanguler/omr)
73
- - **HuggingFace Spaces (Docker + Auto-Sync):** See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for the 2-minute free HTTPS setup (supports browser **Live Camera**!).
74
+ - **Live Public Demo:** [https://omrkit-studio.onrender.com/](https://omrkit-studio.onrender.com/) (OpenAPI docs at [`/docs`](https://omrkit-studio.onrender.com/docs))
75
+ - **Self-Host Your Own Copy (1-Click Free Render Blueprint):** [![Deploy to Render](https://img.shields.io/badge/Deploy_to-Render-14181F?style=flat-square&logo=render)](https://dashboard.render.com/blueprint/new?repo=https://github.com/duhanguler/omr) · See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for GHCR, Render & HuggingFace PRO options.
74
76
 
75
77
  ### 2. Generate a Print-Ready ArUco + QR Sheet
76
78
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "omrkit"
7
- version = "2.1.0"
7
+ version = "2.1.1"
8
8
  description = "Modern Optical Mark Recognition engine with PDF/ArUco alignment, confidence-scored hybrid bubble detection, printable sheet generation, exam psychometrics, REST API, and Visual Web Studio."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -76,6 +76,7 @@ dev = [
76
76
 
77
77
  [project.urls]
78
78
  Homepage = "https://github.com/duhanguler/omr"
79
+ "Live Demo" = "https://omrkit-studio.onrender.com/"
79
80
  Repository = "https://github.com/duhanguler/omr"
80
81
  Documentation = "https://github.com/duhanguler/omr#readme"
81
82
  Changelog = "https://github.com/duhanguler/omr/blob/main/CHANGELOG.md"
@@ -1,5 +1,6 @@
1
1
  """OMRKit — Modern Optical Mark Recognition SDK, Sheet Generator & Exam Psychometrics."""
2
2
 
3
+ from omrkit._version import __version__
3
4
  from omrkit.core.auto_scanner import (
4
5
  resolve_template_for_image,
5
6
  scan_file_auto,
@@ -32,8 +33,6 @@ from omrkit.models import (
32
33
  from omrkit.vision.grid_finder import detect_layout_from_blank
33
34
  from omrkit.vision.qr import detect_sheet_qr
34
35
 
35
- __version__ = "2.1.0"
36
-
37
36
  __all__ = [
38
37
  "AnswerKey",
39
38
  "BatchResult",
@@ -0,0 +1,3 @@
1
+ """Single source of truth for the OMRKit package version."""
2
+
3
+ __version__ = "2.1.1"
@@ -10,6 +10,7 @@ from fastapi.middleware.cors import CORSMiddleware
10
10
  from fastapi.responses import FileResponse, HTMLResponse
11
11
  from fastapi.staticfiles import StaticFiles
12
12
 
13
+ from omrkit._version import __version__
13
14
  from omrkit.api.routes import router
14
15
 
15
16
  STATIC_DIR = Path(__file__).parent / "static"
@@ -24,7 +25,7 @@ def create_app() -> FastAPI:
24
25
  "confidence-scored bubble detection, printable PDF sheet generation, "
25
26
  "and Classical Test Theory exam psychometrics."
26
27
  ),
27
- version="2.1.0",
28
+ version=__version__,
28
29
  docs_url="/docs",
29
30
  redoc_url="/redoc",
30
31
  )
@@ -66,7 +67,7 @@ def create_app() -> FastAPI:
66
67
  return FileResponse(index_html)
67
68
  return HTMLResponse(
68
69
  "<html><body style='font-family:sans-serif;padding:2rem;'>"
69
- "<h1>OMRKit v2.1 API is running</h1>"
70
+ f"<h1>OMRKit v{__version__} API is running</h1>"
70
71
  "<p>Interactive API docs: <a href='/docs'>/docs</a></p>"
71
72
  "<p>Build the Web Studio frontend via <code>cd studio && npm run build</code>.</p>"
72
73
  "</body></html>"
@@ -6,7 +6,9 @@ import base64
6
6
  import io
7
7
  import json
8
8
  import random
9
+ import re
9
10
  import zipfile
11
+ from functools import lru_cache
10
12
  from typing import Any
11
13
 
12
14
  import cv2
@@ -15,6 +17,7 @@ from fastapi import APIRouter, File, Form, HTTPException, UploadFile
15
17
  from fastapi.responses import Response
16
18
  from pydantic import BaseModel, Field
17
19
 
20
+ from omrkit._version import __version__
18
21
  from omrkit.api.settings import APISettings, get_api_settings
19
22
  from omrkit.core.auto_scanner import scan_bytes_auto
20
23
  from omrkit.core.benchmark import apply_camera_distortion, render_synthetic_filled_sheet
@@ -37,6 +40,29 @@ from omrkit.vision.visualizer import render_annotated_sheet
37
40
 
38
41
  router = APIRouter(prefix="/api", tags=["omrkit"])
39
42
 
43
+ _TURKISH_ASCII_MAP = str.maketrans("çğıöşüÇĞİÖŞÜ", "cgiosuCGIOSU")
44
+ _SAFE_FILENAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
45
+
46
+
47
+ def _safe_download_filename(raw_stem: str, suffix: str) -> str:
48
+ """Produce an ASCII-safe, header-injection-proof download filename."""
49
+ cleaned = raw_stem.translate(_TURKISH_ASCII_MAP)
50
+ cleaned = _SAFE_FILENAME_RE.sub("_", cleaned).strip("._-")
51
+ if not cleaned:
52
+ cleaned = "omrkit"
53
+ return f"{cleaned[:80]}{suffix}"
54
+
55
+
56
+ def _make_valid_demo_tckn(seed_index: int) -> str:
57
+ """Synthesize a checksum-valid 11-digit Turkish TC Kimlik No for demo cohorts."""
58
+ base = 100000001 + seed_index * 13729
59
+ digits = [int(ch) for ch in str(base)[:9]]
60
+ odd_sum = sum(digits[0:9:2])
61
+ even_sum = sum(digits[1:8:2])
62
+ d10 = ((odd_sum * 7) - even_sum) % 10
63
+ d11 = (sum(digits) + d10) % 10
64
+ return "".join(str(d) for d in (*digits, d10, d11))
65
+
40
66
 
41
67
  async def _read_bounded_upload(upload: UploadFile, settings: APISettings) -> bytes:
42
68
  """Read an uploaded file enforcing the configured byte limit cleanly."""
@@ -112,15 +138,14 @@ def health_check() -> dict[str, Any]:
112
138
  return {
113
139
  "status": "ok",
114
140
  "service": "omrkit",
115
- "version": "2.1.0",
141
+ "version": __version__,
116
142
  "demo_mode": settings.demo_mode,
117
143
  "limits": settings.limits_dict(),
118
144
  }
119
145
 
120
146
 
121
- @router.get("/presets")
122
- def list_presets() -> dict[str, Any]:
123
- """Return built-in optical sheet presets (with exact templates) and grading policies."""
147
+ @lru_cache(maxsize=1)
148
+ def _cached_presets_payload() -> dict[str, Any]:
124
149
  generator = SheetGenerator()
125
150
  sheet_presets: list[dict[str, Any]] = []
126
151
  for preset_id, spec in get_sheet_presets().items():
@@ -143,14 +168,23 @@ def list_presets() -> dict[str, Any]:
143
168
  }
144
169
 
145
170
 
171
+ @router.get("/presets")
172
+ def list_presets() -> dict[str, Any]:
173
+ """Return built-in optical sheet presets (with exact templates) and grading policies."""
174
+ return _cached_presets_payload()
175
+
176
+
146
177
  @router.post("/generate")
147
178
  def generate_sheet(spec: SheetSpec) -> dict[str, Any]:
148
179
  """Generate a printable PDF (base64), matching exact Template, and sample AnswerKey."""
149
- generated = SheetGenerator().generate(spec)
180
+ try:
181
+ generated = SheetGenerator().generate(spec)
182
+ except ValueError as exc:
183
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
150
184
  pdf_b64 = base64.b64encode(generated.pdf_bytes).decode("ascii")
151
185
  preview_page = load_bytes(generated.pdf_bytes, f"{spec.preset_id}.pdf", dpi=140)[0]
152
186
  return {
153
- "filename": f"{spec.preset_id}_sheet.pdf",
187
+ "filename": _safe_download_filename(spec.preset_id, "_sheet.pdf"),
154
188
  "pdf_base64": pdf_b64,
155
189
  "preview_data_url": _encode_image_data_url(preview_page.image_bgr, fmt=".jpg", quality=88),
156
190
  "template": generated.template.model_dump(mode="json"),
@@ -161,10 +195,15 @@ def generate_sheet(spec: SheetSpec) -> dict[str, Any]:
161
195
  @router.post("/generate/bundle")
162
196
  def generate_sheet_bundle(spec: SheetSpec) -> Response:
163
197
  """Download a ZIP archive containing the PDF sheet, template.json, and answer_key.json."""
164
- generated = SheetGenerator().generate(spec)
198
+ try:
199
+ generated = SheetGenerator().generate(spec)
200
+ except ValueError as exc:
201
+ raise HTTPException(status_code=422, detail=str(exc)) from exc
202
+ pdf_name = _safe_download_filename(spec.preset_id, "_sheet.pdf")
203
+ zip_name = _safe_download_filename(spec.preset_id, "_bundle.zip")
165
204
  buf = io.BytesIO()
166
205
  with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
167
- zf.writestr(f"{spec.preset_id}_sheet.pdf", generated.pdf_bytes)
206
+ zf.writestr(pdf_name, generated.pdf_bytes)
168
207
  zf.writestr(
169
208
  "template.json",
170
209
  json.dumps(generated.template.model_dump(mode="json"), indent=2),
@@ -176,7 +215,7 @@ def generate_sheet_bundle(spec: SheetSpec) -> Response:
176
215
  return Response(
177
216
  content=buf.getvalue(),
178
217
  media_type="application/zip",
179
- headers={"Content-Disposition": f'attachment; filename="{spec.preset_id}_bundle.zip"'},
218
+ headers={"Content-Disposition": f'attachment; filename="{zip_name}"'},
180
219
  )
181
220
 
182
221
 
@@ -210,14 +249,17 @@ def validate_template(template: Template) -> dict[str, Any]:
210
249
  @router.post("/templates/auto-detect")
211
250
  async def auto_detect_template_layout(
212
251
  file: UploadFile = File(...),
213
- dpi: int = Form(200),
252
+ dpi: int = Form(200, ge=72, le=350),
214
253
  ) -> dict[str, Any]:
215
254
  """Automatically detect circular bubble grids on an uploaded blank sheet image/PDF."""
216
255
  settings = get_api_settings()
217
256
  data = await _read_bounded_upload(file, settings)
218
257
  fname = file.filename or "blank_sheet.png"
219
258
  try:
220
- page = load_bytes(data, filename=fname, dpi=dpi, max_pages=settings.max_pdf_pages)[0]
259
+ pages = load_bytes(data, filename=fname, dpi=dpi, max_pages=settings.max_pdf_pages)
260
+ if not pages:
261
+ raise DocumentLoadError(f"Document '{fname}' contains 0 pages.")
262
+ page = pages[0]
221
263
  template, bubbles_count = detect_layout_from_blank(
222
264
  page.image_bgr, template_name=fname.rsplit(".", 1)[0]
223
265
  )
@@ -246,7 +288,7 @@ def migrate_legacy_template_endpoint(payload: MigrateTemplateRequest) -> dict[st
246
288
  @router.post("/preview-image")
247
289
  async def preview_uploaded_document(
248
290
  file: UploadFile = File(...),
249
- dpi: int = Form(200),
291
+ dpi: int = Form(200, ge=72, le=350),
250
292
  ) -> dict[str, Any]:
251
293
  """Decode any uploaded image or PDF first page for the Visual Template Designer canvas."""
252
294
  settings = get_api_settings()
@@ -258,6 +300,8 @@ async def preview_uploaded_document(
258
300
  dpi=dpi,
259
301
  max_pages=settings.max_pdf_pages,
260
302
  )
303
+ if not pages:
304
+ raise DocumentLoadError("Uploaded document contains 0 pages.")
261
305
  except DocumentLoadError as exc:
262
306
  raise HTTPException(status_code=400, detail=str(exc)) from exc
263
307
 
@@ -276,7 +320,7 @@ async def scan_uploaded_sheets(
276
320
  files: list[UploadFile] = File(...),
277
321
  template_json: str = Form("auto"),
278
322
  include_overlay: bool = Form(True),
279
- dpi: int = Form(200),
323
+ dpi: int = Form(200, ge=72, le=350),
280
324
  ) -> dict[str, Any]:
281
325
  """Scan uploaded images/PDFs against a template JSON or 'auto' (QR auto-detection)."""
282
326
  settings = get_api_settings()
@@ -298,15 +342,40 @@ async def scan_uploaded_sheets(
298
342
  template = Template.model_validate(json.loads(template_json))
299
343
  except Exception as exc:
300
344
  raise HTTPException(status_code=422, detail=f"Invalid template JSON: {exc}") from exc
345
+
346
+ # Security guardrail: disallow probing or reading local server paths via HTTP API
347
+ if template.registration.marker_path or template.registration.reference_path:
348
+ raise HTTPException(
349
+ status_code=400,
350
+ detail=(
351
+ "Local server filesystem paths ('marker_path' / 'reference_path') are "
352
+ "disabled on the HTTP API for security. Use 'aruco', 'page_quad', or 'none' "
353
+ "over HTTP, or run local marker/homography templates via the CLI/Python SDK."
354
+ ),
355
+ )
301
356
  scanner = OMRScanner(template=template, dpi=dpi)
302
357
  template_name = template.name
303
358
 
304
359
  sheets: list[dict[str, Any]] = []
305
360
  overlays: dict[str, str] = {}
361
+ seen_ids: dict[str, int] = {}
306
362
  total_elapsed = 0.0
307
363
  flagged_count = 0
308
364
  failed_count = 0
309
365
 
366
+ def _next_unique_id(base_id: str) -> str:
367
+ count = seen_ids.get(base_id, 0)
368
+ if count == 0:
369
+ seen_ids[base_id] = 1
370
+ return base_id
371
+ candidate = f"{base_id}_{count + 1}"
372
+ while candidate in seen_ids:
373
+ count += 1
374
+ candidate = f"{base_id}_{count + 1}"
375
+ seen_ids[base_id] = count + 1
376
+ seen_ids[candidate] = 1
377
+ return candidate
378
+
310
379
  for upload in files:
311
380
  raw_bytes = await _read_bounded_upload(upload, settings)
312
381
  fname = upload.filename or "sheet.png"
@@ -329,9 +398,10 @@ async def scan_uploaded_sheets(
329
398
  if "exceeding the configured limit" in str(exc):
330
399
  raise HTTPException(status_code=400, detail=str(exc)) from exc
331
400
  failed_count += 1
401
+ unique_err_id = _next_unique_id(fname)
332
402
  sheets.append(
333
403
  SheetResult(
334
- sheet_id=fname,
404
+ sheet_id=unique_err_id,
335
405
  source_file=fname,
336
406
  template_name=template_name,
337
407
  overall_confidence=0.0,
@@ -343,6 +413,7 @@ async def scan_uploaded_sheets(
343
413
  continue
344
414
 
345
415
  for result, warped_bgr in page_results:
416
+ result.sheet_id = _next_unique_id(result.sheet_id)
346
417
  total_elapsed += result.elapsed_ms
347
418
  if result.error is not None:
348
419
  failed_count += 1
@@ -367,7 +438,10 @@ async def scan_uploaded_sheets(
367
438
  @router.post("/demo/cohort")
368
439
  def run_one_click_demo_cohort(preset_id: str = "quick_quiz_20") -> dict[str, Any]:
369
440
  """Synthesize, scan, and grade a realistic 5-student exam cohort for 1-click live demos."""
370
- spec = get_sheet_preset(preset_id)
441
+ try:
442
+ spec = get_sheet_preset(preset_id)
443
+ except ValueError as exc:
444
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
371
445
  generated = SheetGenerator().generate(spec)
372
446
  template = generated.template
373
447
  answer_key = generated.sample_answer_key
@@ -390,8 +464,14 @@ def run_one_click_demo_cohort(preset_id: str = "quick_quiz_20") -> dict[str, Any
390
464
  for idx, (sid, skill, rot, persp, shadow, style, inject_hitl) in enumerate(profiles):
391
465
  rng = random.Random(700 + idx)
392
466
  answers: dict[str, str] = {}
467
+ valid_tckn = _make_valid_demo_tckn(idx)
393
468
  for block in template.blocks:
394
- for f_idx, fid in enumerate(block.expanded_labels()):
469
+ labels = block.expanded_labels()
470
+ if block.validator == "tr_tckn" and len(labels) == 11:
471
+ for f_idx, fid in enumerate(labels):
472
+ answers[fid] = valid_tckn[f_idx]
473
+ continue
474
+ for f_idx, fid in enumerate(labels):
395
475
  if block.field_type == "mcq":
396
476
  correct_opt = str(expected_map.get(fid, block.options[0]))
397
477
  if inject_hitl and f_idx == 2:
@@ -406,7 +486,6 @@ def run_one_click_demo_cohort(preset_id: str = "quick_quiz_20") -> dict[str, Any
406
486
  wrongs = [o for o in block.options if o != correct_opt]
407
487
  answers[fid] = rng.choice(wrongs)
408
488
  else:
409
- answers[fid] = str((idx + f_idx + 1) % len(block.options))
410
489
  answers[fid] = block.options[(idx + f_idx + 1) % len(block.options)]
411
490
 
412
491
  marked = render_synthetic_filled_sheet(
@@ -447,7 +526,10 @@ def run_one_click_demo_cohort(preset_id: str = "quick_quiz_20") -> dict[str, Any
447
526
  @router.post("/grade")
448
527
  def grade_sheets(payload: GradeRequest) -> dict[str, Any]:
449
528
  """Grade scanned sheets and return student grades + Classical Test Theory psychometrics."""
450
- grader = ExamGrader(answer_key=payload.answer_key, policy=payload.policy)
529
+ try:
530
+ grader = ExamGrader(answer_key=payload.answer_key, policy=payload.policy)
531
+ except ValueError as exc:
532
+ raise HTTPException(status_code=422, detail=f"Invalid grading policy: {exc}") from exc
451
533
  report = grader.grade_batch(payload.sheets)
452
534
  return report.model_dump(mode="json")
453
535
 
@@ -481,10 +563,9 @@ def export_xlsx_endpoint(payload: ExportRequest) -> Response:
481
563
  def export_scorecard_endpoint(payload: ScorecardRequest) -> Response:
482
564
  """Export a single student's printable A4 PDF scorecard."""
483
565
  pdf_bytes = export_pdf_scorecard_bytes(payload.grade, exam_name=payload.exam_name)
566
+ safe_name = _safe_download_filename(payload.grade.sheet_id, "_scorecard.pdf")
484
567
  return Response(
485
568
  content=pdf_bytes,
486
569
  media_type="application/pdf",
487
- headers={
488
- "Content-Disposition": f'attachment; filename="{payload.grade.sheet_id}_scorecard.pdf"'
489
- },
570
+ headers={"Content-Disposition": f'attachment; filename="{safe_name}"'},
490
571
  )