from __future__ import annotations from dataclasses import dataclass, field from datetime import datetime, timezone from pathlib import Path from queue import Queue from threading import Lock, Thread from time import perf_counter from typing import Any, Callable from uuid import UUID from ocr_server.ocr import OCRService from ocr_server.schemas import OCRDocument, OCRLocation, OCRTextBox, TaskStatus @dataclass class OCRTask: file_id: UUID image_path: Path status: TaskStatus = "queued" progress: int = 0 result: OCRDocument | None = None error: str | None = None ocr_started_at: datetime | None = None ocr_finished_at: datetime | None = None ocr_elapsed_ms: float | None = None _lock: Lock = field(default_factory=Lock, repr=False) class OCRTaskQueue: """In-memory FIFO queue with one independent OCR service per worker.""" def __init__( self, ocr_factory: Callable[[], OCRService], worker_count: int = 1, ) -> None: self.worker_count = worker_count self._tasks: dict[UUID, OCRTask] = {} self._tasks_lock = Lock() self._queue: Queue[OCRTask | None] = Queue() self._ocr_services = [ocr_factory() for _ in range(worker_count)] self._workers = [ Thread( target=self._worker_loop, args=(index,), name=f"ocr-worker-{index + 1}", daemon=True, ) for index in range(worker_count) ] for worker in self._workers: worker.start() def submit(self, file_id: UUID, image_path: Path) -> OCRTask: task = OCRTask(file_id=file_id, image_path=image_path) with self._tasks_lock: self._tasks[file_id] = task self._queue.put(task) return task def get(self, file_id: UUID) -> OCRTask | None: with self._tasks_lock: return self._tasks.get(file_id) def queue_position(self, file_id: UUID) -> int | None: task = self.get(file_id) if task is None or task.status != "queued": return None with self._queue.mutex: queued = list(self._queue.queue) try: return next(index for index, item in enumerate(queued, 1) if item is task) except StopIteration: return None def snapshot( self, file_id: UUID ) -> tuple[ TaskStatus, int, int | None, OCRDocument | None, str | None, datetime | None, datetime | None, float | None, ] | None: task = self.get(file_id) if task is None: return None with task._lock: return ( task.status, task.progress, self.queue_position(file_id), task.result, task.error, task.ocr_started_at, task.ocr_finished_at, task.ocr_elapsed_ms, ) def _worker_loop(self, worker_index: int) -> None: ocr = self._ocr_services[worker_index] while True: task = self._queue.get() try: if task is None: return self._run(task, ocr) finally: self._queue.task_done() def _run(self, task: OCRTask, ocr: OCRService) -> None: started_at = datetime.now(timezone.utc) started_clock = perf_counter() with task._lock: task.status = "processing" task.progress = 10 task.ocr_started_at = started_at try: with task._lock: task.progress = 20 recognized = ocr.recognize(task.image_path) with task._lock: task.progress = 80 task.result = self.build_document(recognized) task.progress = 100 task.status = "completed" except Exception as exc: with task._lock: task.status = "failed" task.progress = 100 task.error = str(exc) finally: with task._lock: task.ocr_finished_at = datetime.now(timezone.utc) task.ocr_elapsed_ms = round((perf_counter() - started_clock) * 1000, 2) @classmethod def build_document(cls, recognized: list[dict[str, Any]]) -> OCRDocument: """Build the compact polygon object and line/paragraph numbering.""" segments = [item for item in recognized if item.get("text")] if not segments: return OCRDocument(text="", polygon={}) ordered = sorted(segments, key=cls._segment_sort_key) line_groups: list[list[dict[str, Any]]] = [] for segment in ordered: matching_line = cls._find_line(segment, line_groups) if matching_line is None: line_groups.append([segment]) else: matching_line.append(segment) for line in line_groups: line.sort(key=cls._segment_sort_key) line_groups.sort(key=cls._line_sort_key) paragraph_groups: list[list[list[dict[str, Any]]]] = [] for line in line_groups: line_record = { "segments": line, "polygon": cls._combined_polygon( [item.get("polygon", []) for item in line] ), "text": cls._join_text(line), } if not paragraph_groups or not cls._same_paragraph( paragraph_groups[-1][-1], line_record ): paragraph_groups.append([line_record]) else: paragraph_groups[-1].append(line_record) polygon: dict[str, OCRTextBox] = {} paragraph_texts: list[str] = [] line_number = 0 for paragraph_number, paragraph in enumerate(paragraph_groups, 1): paragraph_texts.append("\n".join(line["text"] for line in paragraph)) for line in paragraph: line_number += 1 for segment in line["segments"]: bounds = cls._bounds(segment.get("polygon", [])) if bounds is None: continue polygon[f"text{len(polygon) + 1}"] = OCRTextBox( text=str(segment.get("text", "")), confidence=float(segment.get("confidence", 0.0)), Location=OCRLocation( xtop=bounds[0], ytop=bounds[1], xbottom=bounds[2], ybottom=bounds[3], ), line=line_number, paragraphs=paragraph_number, ) return OCRDocument(text="\n\n".join(paragraph_texts), polygon=polygon) @classmethod def filter_document(cls, document: OCRDocument, min_confidence: float) -> OCRDocument: # The compact response is intentionally rebuilt from its own polygon map. selected = [ { "text": item.text, "confidence": item.confidence, "polygon": [ [item.Location.xtop, item.Location.ytop], [item.Location.xbottom, item.Location.ytop], [item.Location.xbottom, item.Location.ybottom], [item.Location.xtop, item.Location.ybottom], ], } for item in document.polygon.values() if item.confidence >= min_confidence ] return cls.build_document(selected) @classmethod def _find_line( cls, segment: dict[str, Any], line_groups: list[list[dict[str, Any]]], ) -> list[dict[str, Any]] | None: segment_bounds = cls._bounds(segment.get("polygon", [])) if segment_bounds is None: return None _, top, _, bottom = segment_bounds segment_height = max(bottom - top, 1.0) best: tuple[float, list[dict[str, Any]]] | None = None for line in line_groups: line_bounds = cls._combined_bounds([item.get("polygon", []) for item in line]) if line_bounds is None: continue _, line_top, _, line_bottom = line_bounds line_height = max(line_bottom - line_top, 1.0) overlap = min(bottom, line_bottom) - max(top, line_top) center_distance = abs((top + bottom) / 2 - (line_top + line_bottom) / 2) if overlap >= 0.25 * min(segment_height, line_height) or center_distance <= 0.45 * max(segment_height, line_height): if best is None or center_distance < best[0]: best = (center_distance, line) return best[1] if best else None @classmethod def _same_paragraph(cls, previous: dict[str, Any], current: dict[str, Any]) -> bool: previous_bounds = cls._bounds(previous["polygon"]) current_bounds = cls._bounds(current["polygon"]) if previous_bounds is None or current_bounds is None: return True previous_left, previous_top, previous_right, previous_bottom = previous_bounds current_left, current_top, current_right, _ = current_bounds previous_height = max(previous_bottom - previous_top, 1.0) vertical_gap = current_top - previous_bottom horizontal_overlap = min(previous_right, current_right) - max(previous_left, current_left) return vertical_gap <= 2.0 * previous_height and ( horizontal_overlap >= 0 or abs(current_left - previous_left) <= 2.0 * previous_height ) @staticmethod def _join_text(segments: list[dict[str, Any]]) -> str: text = "" for segment in segments: value = str(segment.get("text", "")) if text and text[-1].isascii() and text[-1].isalnum() and value[:1].isascii() and value[:1].isalnum(): text += " " text += value return text @staticmethod def _segment_sort_key(segment: dict[str, Any]) -> tuple[float, float]: bounds = OCRTaskQueue._bounds(segment.get("polygon", [])) return (bounds[1], bounds[0]) if bounds else (0.0, 0.0) @classmethod def _line_sort_key(cls, line: list[dict[str, Any]]) -> tuple[float, float]: bounds = cls._combined_bounds([item.get("polygon", []) for item in line]) return (bounds[1], bounds[0]) if bounds else (0.0, 0.0) @staticmethod def _bounds(polygon: list[list[float]]) -> tuple[float, float, float, float] | None: if not polygon: return None try: xs = [float(point[0]) for point in polygon] ys = [float(point[1]) for point in polygon] except (IndexError, TypeError, ValueError): return None return min(xs), min(ys), max(xs), max(ys) @classmethod def _combined_bounds( cls, polygons: list[list[list[float]]] ) -> tuple[float, float, float, float] | None: bounds = [cls._bounds(polygon) for polygon in polygons] valid = [item for item in bounds if item is not None] if not valid: return None return ( min(item[0] for item in valid), min(item[1] for item in valid), max(item[2] for item in valid), max(item[3] for item in valid), ) @classmethod def _combined_polygon(cls, polygons: list[list[list[float]]]) -> list[list[float]]: bounds = cls._combined_bounds(polygons) if bounds is None: return [] left, top, right, bottom = bounds return [[left, top], [right, top], [right, bottom], [left, bottom]]