Download omr_blindnet/cli.py from Hujaifa01/OMR-Scanner: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/Hujaifa01/OMR-Scanner/resolve/main/omr_blindnet/cli.py
- Command line
-
hf download hf://Hujaifa01/OMR-Scanner/omr_blindnet/cli.py
-
curl -L -o cli.py https://huggingface.co/Hujaifa01/OMR-Scanner/resolve/main/omr_blindnet/cli.py
13.9 kB
| from __future__ import annotations | |
| import argparse | |
| import csv | |
| import json | |
| import math | |
| import re | |
| import sys | |
| from pathlib import Path | |
| from typing import Dict, List, Tuple | |
| import cv2 | |
| import numpy as np | |
| import pymupdf as fitz | |
| from .inference import OMRBlindNetONNX | |
| from .preprocessing import compute_dark_ink_channel | |
| def _default_model_path() -> Path: | |
| here = Path(__file__).resolve().parent.parent | |
| if (here / "model.onnx").exists(): | |
| return here / "model.onnx" | |
| return Path("model.onnx") | |
| def _parse_key(key_str: str) -> Dict[str, str]: | |
| ans: Dict[str, str] = {} | |
| if not key_str: | |
| return ans | |
| p = Path(key_str) | |
| if p.exists() and p.is_file(): | |
| key_str = p.read_text(encoding="utf-8") | |
| try: | |
| loaded = json.loads(key_str) | |
| if isinstance(loaded, dict): | |
| return {str(k).upper(): str(v).upper() for k, v in loaded.items()} | |
| except Exception: | |
| pass | |
| pairs = re.findall(r"(?:Q)?(\d+)\s*[:=\-]\s*([A-Ea-e])", key_str) | |
| if pairs: | |
| for num, opt in pairs: | |
| ans[f"Q{int(num)}"] = opt.upper() | |
| return ans | |
| letters = [c for c in key_str.upper() if c in "ABCDE"] | |
| for idx, ch in enumerate(letters, start=1): | |
| ans[f"Q{idx}"] = ch | |
| return ans | |
| def _load_pages(path: Path, dpi: int = 200) -> List[np.ndarray]: | |
| if path.suffix.lower() == ".pdf": | |
| doc = fitz.open(str(path)) | |
| mat = fitz.Matrix(dpi / 72.0, dpi / 72.0) | |
| pages = [] | |
| try: | |
| for page in doc: | |
| pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB, alpha=False) | |
| img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 3) | |
| pages.append(cv2.cvtColor(img, cv2.COLOR_RGB2BGR)) | |
| finally: | |
| doc.close() | |
| return pages | |
| img = cv2.imread(str(path)) | |
| if img is None: | |
| raise FileNotFoundError(f"Could not read image: {path}") | |
| return [img] | |
| def _auto_detect_grid(bgr: np.ndarray) -> Tuple[np.ndarray, List[Tuple[str, List[Tuple[str, float, float, float]]]]]: | |
| """Self-contained zero-config deskewing + lattice-fitting MCQ bubble grid discoverer.""" | |
| h, w = bgr.shape[:2] | |
| tw = 1654 | |
| th = int(round(h * (tw / float(w)))) | |
| img = cv2.resize(bgr, (tw, th), interpolation=cv2.INTER_AREA if w > tw else cv2.INTER_CUBIC) | |
| def find_circles(im: np.ndarray): | |
| gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) | |
| ink = compute_dark_ink_channel(im) | |
| block = max(25, (min(im.shape[:2]) // 48) | 1) | |
| m1 = cv2.adaptiveThreshold(cv2.GaussianBlur(gray, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block, 8) | |
| m2 = cv2.adaptiveThreshold(cv2.GaussianBlur(ink, (5, 5), 0), 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, block, 22) | |
| min_d, max_d = tw * 0.014, tw * 0.052 | |
| raw = [] | |
| for mask in (m1, m2): | |
| cnts, _ = cv2.findContours(mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) | |
| for c in cnts: | |
| x, y, bw, bh = cv2.boundingRect(c) | |
| if bw < min_d or bh < min_d or bw > max_d or bh > max_d: | |
| continue | |
| if not (0.74 <= bw / float(bh) <= 1.35): | |
| continue | |
| area = cv2.contourArea(c) | |
| peri = cv2.arcLength(c, True) | |
| if peri <= 0 or area < bw * bh * 0.42: | |
| continue | |
| circ = 4.0 * math.pi * area / (peri * peri) | |
| if circ < 0.62: | |
| continue | |
| raw.append((x + bw * 0.5, y + bh * 0.5, (bw + bh) * 0.25, area * circ)) | |
| raw.sort(key=lambda t: -t[3]) | |
| kept = [] | |
| for cx, cy, r, _ in raw: | |
| if all((cx - kx) ** 2 + (cy - ky) ** 2 >= (max(r, kr) * 0.85) ** 2 for kx, ky, kr in kept): | |
| kept.append((cx, cy, r)) | |
| if not kept: | |
| return [], 0.0 | |
| radii = np.array([t[2] for t in kept], dtype=np.float32) | |
| r_med = float(np.median(radii)) | |
| kept = [(cx, cy, r) for cx, cy, r in kept if abs(r - r_med) <= max(4.0, r_med * 0.26)] | |
| return kept, r_med | |
| def modal_gap(vals: List[float], lo: float, hi: float) -> float: | |
| arr = np.array([v for v in vals if lo <= v <= hi], dtype=np.float32) | |
| if len(arr) == 0: | |
| return 0.0 | |
| if len(arr) < 5: | |
| return float(np.median(arr)) | |
| counts, edges = np.histogram(arr, bins=max(8, int(round((hi - lo) / 2.0))), range=(lo, hi)) | |
| b = int(np.argmax(counts)) | |
| peak = 0.5 * (edges[b] + edges[b + 1]) | |
| close = arr[np.abs(arr - peak) <= max(4.0, peak * 0.14)] | |
| return float(np.median(close)) if len(close) > 0 else float(np.median(arr)) | |
| bubs, r_med = find_circles(img) | |
| if len(bubs) < 12 or r_med <= 0: | |
| return img, [] | |
| # Auto-deskew from vertical/horizontal neighbor pairs | |
| pts = np.array([(b[0], b[1]) for b in bubs], dtype=np.float32) | |
| angs = [] | |
| for i in range(len(pts)): | |
| dx = pts[:, 0] - pts[i, 0] | |
| dy = pts[:, 1] - pts[i, 1] | |
| for j in np.where((dx > r_med * 1.6) & (dx < r_med * 4.5) & (np.abs(dy) < r_med * 0.65))[0]: | |
| angs.append(math.degrees(math.atan2(float(dy[j]), float(dx[j])))) | |
| for j in np.where((dy > r_med * 1.8) & (dy < r_med * 6.5) & (np.abs(dx) < r_med * 0.75))[0]: | |
| angs.append(-math.degrees(math.atan2(float(dx[j]), float(dy[j])))) | |
| if len(angs) >= 10: | |
| ang = float(np.median(angs)) | |
| if 0.06 <= abs(ang) <= 12.0: | |
| M = cv2.getRotationMatrix2D((tw * 0.5, th * 0.5), ang, 1.0) | |
| img = cv2.warpAffine(img, M, (tw, th), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE) | |
| bubs, r_med = find_circles(img) | |
| bubs.sort(key=lambda t: (t[1], t[0])) | |
| bands = [] | |
| for b in bubs: | |
| placed = False | |
| for bd in bands: | |
| if abs(b[1] - sum(p[1] for p in bd) / len(bd)) <= r_med * 0.85: | |
| bd.append(b) | |
| placed = True | |
| break | |
| if not placed: | |
| bands.append([b]) | |
| bands = [sorted(bd, key=lambda t: t[0]) for bd in bands if len(bd) >= 3] | |
| 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) | |
| if opt_gap <= 0: | |
| return img, [] | |
| runs = [] | |
| for bd in bands: | |
| cur = [bd[0]] | |
| for b in bd[1:]: | |
| if b[0] - cur[-1][0] <= opt_gap * 1.42: | |
| cur.append(b) | |
| else: | |
| if len(cur) >= 3: | |
| runs.append(cur) | |
| cur = [b] | |
| if len(cur) >= 3: | |
| runs.append(cur) | |
| len_cnt: Dict[int, int] = {} | |
| for rn in runs: | |
| if 3 <= len(rn) <= 5: | |
| len_cnt[len(rn)] = len_cnt.get(len(rn), 0) + 1 | |
| if not len_cnt: | |
| return img, [] | |
| k_opts = max(len_cnt, key=lambda k: (len_cnt[k], 1 if k in (4, 5) else 0)) | |
| opt_letters = ["A", "B", "C", "D", "E"][:k_opts] | |
| cols = [] | |
| for rn in sorted([r for r in runs if len(r) == k_opts], key=lambda r: r[0][0]): | |
| placed = False | |
| for cl in cols: | |
| if abs(rn[0][0] - sum(r[0][0] for r in cl) / len(cl)) <= max(r_med * 1.25, opt_gap * 0.55): | |
| cl.append(rn) | |
| placed = True | |
| break | |
| if not placed: | |
| cols.append([rn]) | |
| cols = sorted([c for c in cols if len(c) >= 3], key=lambda c: sum(r[0][0] for r in c) / len(c)) | |
| if not cols: | |
| return img, [] | |
| all_dy = [] | |
| for cl in cols: | |
| ys = sorted(sum(p[1] for p in r) / len(r) for r in cl) | |
| for i in range(len(ys) - 1): | |
| all_dy.append(ys[i + 1] - ys[i]) | |
| row_gap_global = modal_gap(all_dy, r_med * 1.8, r_med * 8.5) | |
| if row_gap_global <= 0: | |
| return img, [] | |
| # Lattice-fit every column block (recovers rows with heavily scribbled/merged bubbles!) | |
| questions: List[Tuple[str, List[Tuple[str, float, float, float]]]] = [] | |
| q_num = 1 | |
| for cl in cols: | |
| cx0 = float(np.median([r[0][0] for r in cl])) | |
| c_gap = float(np.median([(r[-1][0] - r[0][0]) / float(k_opts - 1) for r in cl])) | |
| 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] | |
| col_rows = [] | |
| for b in sorted(col_b, key=lambda t: t[1]): | |
| placed = False | |
| for grp in col_rows: | |
| if abs(b[1] - sum(p[1] for p in grp) / len(grp)) <= r_med * 0.85: | |
| grp.append(b) | |
| placed = True | |
| break | |
| if not placed: | |
| col_rows.append([b]) | |
| valid_ys = sorted( | |
| float(np.mean([p[1] for p in grp])) | |
| for grp in col_rows | |
| if sum(1 for bx, _, _ in grp if 0 <= round((bx - cx0) / max(c_gap, 1.0)) < k_opts) >= 2 | |
| ) | |
| if len(valid_ys) < 2: | |
| continue | |
| best_chain, cur_chain = [], [valid_ys[0]] | |
| for y in valid_ys[1:]: | |
| if y - cur_chain[-1] <= row_gap_global * 1.38: | |
| cur_chain.append(y) | |
| else: | |
| if len(cur_chain) > len(best_chain): | |
| best_chain = cur_chain | |
| cur_chain = [y] | |
| if len(cur_chain) > len(best_chain): | |
| best_chain = cur_chain | |
| if len(best_chain) < 2: | |
| continue | |
| ks = np.array([round((y - best_chain[0]) / row_gap_global) for y in best_chain], dtype=np.float64) | |
| slope, intercept = np.polyfit(ks, np.array(best_chain, dtype=np.float64), 1) | |
| row_count = int(round(ks[-1])) + 1 | |
| slot_xs = [ | |
| (int(round((bx - cx0) / max(c_gap, 1.0))), bx) | |
| for bx, by, _ in col_b | |
| if intercept - r_med * 1.1 <= by <= intercept + (row_count - 1) * slope + r_med * 1.1 | |
| and 0 <= int(round((bx - cx0) / max(c_gap, 1.0))) < k_opts | |
| and abs(bx - (cx0 + int(round((bx - cx0) / max(c_gap, 1.0))) * c_gap)) <= r_med * 0.7 | |
| ] | |
| if len(slot_xs) >= k_opts * 2: | |
| c_gap, cx0 = np.polyfit([p[0] for p in slot_xs], [p[1] for p in slot_xs], 1) | |
| for r_i in range(row_count): | |
| ry = float(intercept + r_i * slope) | |
| questions.append( | |
| (f"Q{q_num}", [(opt_letters[o_i], float(cx0 + o_i * c_gap), ry, r_med) for o_i in range(k_opts)]) | |
| ) | |
| q_num += 1 | |
| return img, questions | |
| def main(argv: List[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser( | |
| prog="omr-blindnet", | |
| description="OMR-BlindNet-v1 CLI: Blind-Letter Deep CNN OMR Sheet Grader (Double Answer = WRONG)", | |
| ) | |
| sub = parser.add_subparsers(dest="cmd", required=True) | |
| p_check = sub.add_parser("check", help="Grade a single image or multi-page OMR PDF") | |
| p_check.add_argument("input", help="Path to OMR PDF or image (.pdf/.jpg/.png)") | |
| p_check.add_argument("--key", default="", help="Answer key string (e.g. '1:D,2:C,3:C' or 'DCCBB...') or JSON file") | |
| p_check.add_argument("--model", default=str(_default_model_path()), help="Local model.onnx path or Hugging Face repo id") | |
| p_check.add_argument("--threshold", type=float, default=0.50, help="Blind-letter probability threshold (default 0.50)") | |
| p_check.add_argument("--out", default="", help="Optional CSV output path") | |
| p_info = sub.add_parser("info", help="Show model card metadata & local ONNX status") | |
| p_info.add_argument("--model", default=str(_default_model_path()), help="Path to model.onnx or HF repo id") | |
| args = parser.parse_args(argv) | |
| model = OMRBlindNetONNX.from_pretrained(args.model, threshold=getattr(args, "threshold", 0.50)) | |
| if args.cmd == "info": | |
| print(json.dumps({"model_path": str(model.model_path), "config": model.config}, indent=2)) | |
| return 0 | |
| answer_key = _parse_key(args.key) | |
| pages = _load_pages(Path(args.input)) | |
| print(f"[OMR-BlindNet-v1] Loaded {len(pages)} page(s) from {args.input}") | |
| rows_out = [] | |
| for p_idx, bgr in enumerate(pages): | |
| img, questions = _auto_detect_grid(bgr) | |
| flat_coords = [(cx, cy, r) for _, opts in questions for _, cx, cy, r in opts] | |
| probs = model.predict_bubbles_on_sheet(img, flat_coords) | |
| correct = wrong = multi = blank = 0 | |
| cursor = 0 | |
| page_answers = {} | |
| for qlbl, opts in questions: | |
| marked = [] | |
| for opt, _, _, _ in opts: | |
| if float(probs[cursor]) >= model.threshold: | |
| marked.append(opt) | |
| cursor += 1 | |
| page_answers[qlbl] = marked | |
| exp = answer_key.get(qlbl) | |
| if exp: | |
| if len(marked) == 0: | |
| blank += 1 | |
| elif len(marked) > 1: | |
| multi += 1 # Double/multi answer NOT allowed -> counted as WRONG | |
| elif marked[0] == exp: | |
| correct += 1 | |
| else: | |
| wrong += 1 | |
| marked_summary = {q: "+".join(v) for q, v in page_answers.items() if v} | |
| if answer_key: | |
| print(f"Page {p_idx + 1}: Score={correct}/{len(answer_key)} | Correct={correct} Wrong={wrong} Multi(Wrong)={multi} Blank={blank}") | |
| else: | |
| print(f"Page {p_idx + 1}: Detected {len(marked_summary)} answered / {len(questions)} MCQs -> {marked_summary}") | |
| rows_out.append({"page": p_idx + 1, "correct": correct, "wrong": wrong, "multi_wrong": multi, "blank": blank, "answers": json.dumps(marked_summary)}) | |
| if args.out: | |
| with open(args.out, "w", newline="", encoding="utf-8") as f: | |
| w = csv.DictWriter(f, fieldnames=["page", "correct", "wrong", "multi_wrong", "blank", "answers"]) | |
| w.writeheader() | |
| w.writerows(rows_out) | |
| print(f"Saved results to {args.out}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |