File size: 4,847 Bytes
7ca0188
 
 
 
9b70bf1
7ca0188
 
384be10
 
7ca0188
 
 
 
 
 
 
 
 
9b70bf1
 
 
 
 
 
 
 
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
0084816
7ca0188
 
 
 
 
0084816
7ca0188
 
 
 
 
 
 
 
0084816
7ca0188
0084816
 
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0084816
7ca0188
 
9b70bf1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ca0188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0084816
7ca0188
 
 
 
 
 
0084816
7ca0188
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""Lazy OCR support for airport signs and information boards."""

from __future__ import annotations

import threading
from typing import Any

import numpy as np

from src.config import Settings, get_settings
from src.preprocessing.image_processor import ImageProcessor
from src.utils.timing import elapsed_ms, now_ms

try:
    import easyocr
except ImportError:  # pragma: no cover - optional dependency
    easyocr = None

try:
    import torch
except ImportError:  # pragma: no cover - optional dependency
    torch = None


_OCR_INFERENCE_LOCK = threading.Lock()


class OCRReader:
    """Extract visible text without retaining uploaded image data."""

    def __init__(
        self,
        settings: Settings | None = None,
        reader: Any | None = None,
        image_processor: ImageProcessor | None = None,
    ) -> None:
        self.settings = settings or get_settings()
        self.reader = reader
        self.image_processor = image_processor or ImageProcessor(self.settings)
        self.last_error: str | None = None

    def load(self) -> bool:
        if self.reader is not None:
            return True
        if not self.settings.ocr_enabled or easyocr is None:
            self.last_error = "OCR is disabled or its dependency is unavailable."
            return False
        languages = [
            item.strip()
            for item in self.settings.ocr_languages.split(",")
            if item.strip()
        ] or ["en"]
        try:
            self.reader = easyocr.Reader(languages, gpu=False)
            self.last_error = None
            return True
        except Exception as exc:
            self.last_error = f"{type(exc).__name__}: {exc}"
            self.reader = None
            return False

    def extract_text(self, file_path: str | None) -> dict[str, Any]:
        start = now_ms()
        prepared = self.image_processor.prepare_image(file_path)
        if not prepared["valid"]:
            return {
                "success": False,
                "text": "",
                "confidence": 0.0,
                "items": [],
                "processing_time_ms": elapsed_ms(start),
                "error": prepared["error"] or "Invalid image.",
            }
        if not self.load():
            return {
                "success": False,
                "text": "",
                "confidence": 0.0,
                "items": [],
                "processing_time_ms": elapsed_ms(start),
                "error": self.last_error or "OCR is disabled or unavailable.",
            }
        try:
            image_array = np.asarray(prepared["image"])
            if torch is None:
                raw = self.reader.readtext(image_array, detail=1, paragraph=False)
            else:
                # EasyOCR hard-codes pin_memory=True in its recognition
                # DataLoader. ZeroGPU exposes CUDA capability to PyTorch even
                # outside a GPU allocation, so pinned-memory initialization can
                # raise "No CUDA GPUs are available" for an otherwise CPU-only
                # reader. Override that one constructor argument while the
                # synchronous OCR call runs, then restore the global factory.
                with _OCR_INFERENCE_LOCK:
                    original_loader = torch.utils.data.DataLoader

                    def cpu_loader(*args: Any, **kwargs: Any) -> Any:
                        kwargs["pin_memory"] = False
                        return original_loader(*args, **kwargs)

                    torch.utils.data.DataLoader = cpu_loader
                    try:
                        raw = self.reader.readtext(
                            image_array, detail=1, paragraph=False
                        )
                    finally:
                        torch.utils.data.DataLoader = original_loader
            items = [
                {"text": str(item[1]).strip(), "confidence": float(item[2])}
                for item in raw
                if len(item) >= 3 and str(item[1]).strip()
            ]
            confidence = (
                sum(item["confidence"] for item in items) / len(items)
                if items
                else 0.0
            )
            return {
                "success": bool(items),
                "text": " ".join(item["text"] for item in items),
                "confidence": confidence,
                "items": items,
                "processing_time_ms": elapsed_ms(start),
                "error": None if items else "No useful text detected.",
            }
        except Exception as exc:
            return {
                "success": False,
                "text": "",
                "confidence": 0.0,
                "items": [],
                "processing_time_ms": elapsed_ms(start),
                "error": f"{type(exc).__name__}: {exc}",
            }