File size: 11,640 Bytes
f12abb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
"""
mini-kh-OCR Pipeline
--------------------
Combines:
  - phonsobon/mini-text-detection  (YOLO11n โ€” detects subject / reference / content)
  - phonsobon/mini-ocr             (CRNN + CTC โ€” recognises Khmer & English text)

Usage:
    from mini_kh_ocr import MiniKhOCR
    ocr = MiniKhOCR()
    result = ocr("your_image.jpg")
    print(result)
"""

import os
import torch
import torch.nn as nn
import numpy as np
from PIL import Image
from huggingface_hub import hf_hub_download
from ultralytics import YOLO


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# 1. CONSTANTS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

CLASS_NAMES = {0: "subject", 1: "reference", 2: "content"}

TOKENS = (
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789"
    "แž€แžแž‚แžƒแž„แž…แž†แž‡แžˆแž‰แžŠแž‹แžŒแžแžŽแžแžแž‘แž’แž“แž”แž•แž–แž—แž˜แž™แžšแž›แžœแžแžžแžŸแž แžกแžขแžฃแžคแžฅแžฆแžงแžฉแžชแžซแžฌแžญแžฎแžฏแžฐแžฑแžฒแžณ"
    "แžถแžทแžธแžนแžบแžปแžผแžฝแžพแžฟแŸ€แŸแŸ‚แŸƒแŸ„แŸ…แŸ†แŸ‡แŸˆแŸ‰แŸŠแŸ‹แŸŒแŸแŸŽแŸแŸแŸ‘แŸ’แŸ”แŸ•แŸ–แŸ—แŸ˜แŸ›แŸ"
    "แŸ แŸกแŸขแŸฃแŸคแŸฅแŸฆแŸงแŸจแŸฉแŸณ"
    "!@#$%^&*()-_=+[]{};:'\",.<>?/|\\ "
)
NUM_CHARS = len(TOKENS)
IDX2CHAR  = {i + 1: c for i, c in enumerate(TOKENS)}


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# 2. OCR MODEL DEFINITION  (KhmerOCR_DTWG)
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

class KhmerOCR_DTWG(nn.Module):
    def __init__(self, num_chars=NUM_CHARS, hidden_size=256):
        super().__init__()
        self.cnn = nn.Sequential(
            self._conv(1, 32),  nn.MaxPool2d(2, 2),
            self._conv(32, 64), nn.MaxPool2d(2, 2),
            self._conv(64, 128),
            self._conv(128, 128),
            nn.MaxPool2d((2, 1), (2, 1)),
            self._conv(128, 256),
            self._conv(256, 256),
            nn.MaxPool2d((4, 1), (4, 1)),
        )
        self.lstm1 = nn.LSTM(256, hidden_size, bidirectional=True, batch_first=True)
        self.fc1   = nn.Linear(hidden_size * 2, hidden_size)
        self.lstm2 = nn.LSTM(hidden_size, hidden_size, bidirectional=True, batch_first=True)
        self.fc    = nn.Linear(hidden_size * 2, num_chars + 1)

    def _conv(self, i, o):
        return nn.Sequential(
            nn.Conv2d(i, o, 3, 1, 1, bias=False),
            nn.BatchNorm2d(o),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        x = self.cnn(x)
        x = x.squeeze(2).permute(0, 2, 1)
        x, _ = self.lstm1(x)
        x = torch.relu(self.fc1(x))
        x, _ = self.lstm2(x)
        x = self.fc(x)
        return x.permute(1, 0, 2)


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# 3. HELPERS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

def _load_crop_for_ocr(pil_img: Image.Image) -> torch.Tensor:
    """Resize a PIL crop to height=32, normalise, return (1,1,32,W) tensor."""
    img = pil_img.convert("L")
    w, h = img.size
    if h == 0:
        h = 1
    new_w = max(1, int(w / h * 32))
    img = img.resize((new_w, 32))
    arr = np.array(img, dtype=np.float32) / 255.0
    return torch.tensor(arr).unsqueeze(0).unsqueeze(0)   # (1,1,32,W)


def _ctc_decode(logits: torch.Tensor) -> str:
    """Greedy CTC decode โ€” logits shape: (T, 1, C)."""
    preds = torch.argmax(logits, dim=2)[:, 0].cpu().numpy()
    prev, text = -1, []
    for p in preds:
        if p != prev and p != 0:
            text.append(IDX2CHAR.get(int(p), ""))
        prev = p
    return "".join(text)


def _sort_boxes_top_to_bottom(boxes, cls_ids, confs):
    """Sort detections by vertical position (top โ†’ bottom)."""
    order = sorted(range(len(boxes)), key=lambda i: boxes[i][1])
    return [boxes[i] for i in order], [cls_ids[i] for i in order], [confs[i] for i in order]


# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
# 4. MAIN PIPELINE CLASS
# โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

class MiniKhOCR:
    """
    End-to-end Khmer OCR pipeline.

    Parameters
    ----------
    det_conf   : float  โ€” detection confidence threshold (default 0.25)
    det_iou    : float  โ€” NMS IoU threshold (default 0.45)
    det_imgsz  : int    โ€” detection image size (default 640)
    device     : str    โ€” 'cuda' | 'cpu' | 'auto'
    """

    def __init__(
        self,
        det_conf: float = 0.25,
        det_iou:  float = 0.45,
        det_imgsz: int  = 640,
        device: str     = "auto",
    ):
        if device == "auto":
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        else:
            self.device = torch.device(device)

        print(f"[mini-kh-OCR] Device: {self.device}")

        # โ”€โ”€ detection model โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        print("[mini-kh-OCR] Loading detection model ...")
        det_path = hf_hub_download(
            repo_id="phonsobon/mini-text-detection",
            filename="khmer-text-detection-mini.pt",
        )
        self.detector  = YOLO(det_path)
        self.det_conf  = det_conf
        self.det_iou   = det_iou
        self.det_imgsz = det_imgsz

        # โ”€โ”€ recognition model โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        print("[mini-kh-OCR] Loading recognition model ...")
        ocr_path = hf_hub_download(
            repo_id="phonsobon/mini-ocr",
            filename="model.pt",
        )
        self.recogniser = KhmerOCR_DTWG(NUM_CHARS).to(self.device)
        self.recogniser.load_state_dict(
            torch.load(ocr_path, map_location=self.device)
        )
        self.recogniser.eval()

        print("[mini-kh-OCR] Ready โœ…")

    # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def _recognise(self, crop: Image.Image) -> str:
        """Run OCR on a single PIL crop."""
        tensor = _load_crop_for_ocr(crop).to(self.device)
        with torch.no_grad():
            logits = self.recogniser(tensor)
        return _ctc_decode(logits)

    # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def __call__(
        self,
        image,
        return_crops: bool = False,
        verbose: bool = False,
    ) -> dict:
        """
        Run detection + recognition on an image.

        Parameters
        ----------
        image        : str | PIL.Image  โ€” file path or PIL image
        return_crops : bool             โ€” include cropped PIL images in output
        verbose      : bool             โ€” print each detected region

        Returns
        -------
        dict with keys:
            "subject"   : list of str
            "reference" : list of str
            "content"   : list of str
            "regions"   : list of dicts with box, class, conf, text (and crop if requested)
        """
        if isinstance(image, str):
            pil_img = Image.open(image).convert("RGB")
        else:
            pil_img = image.convert("RGB")

        # โ”€โ”€ Step 1: detect โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        det_results = self.detector.predict(
            source=pil_img,
            conf=self.det_conf,
            iou=self.det_iou,
            imgsz=self.det_imgsz,
            verbose=False,
        )

        raw_boxes  = det_results[0].boxes.xyxy.cpu().numpy().astype(int).tolist()
        raw_cls    = [int(c) for c in det_results[0].boxes.cls.cpu().numpy()]
        raw_conf   = [float(c) for c in det_results[0].boxes.conf.cpu().numpy()]

        # โ”€โ”€ Step 2: sort top โ†’ bottom โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        boxes, cls_ids, confs = _sort_boxes_top_to_bottom(raw_boxes, raw_cls, raw_conf)

        # โ”€โ”€ Step 3: recognise each crop โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        result = {"subject": [], "reference": [], "content": [], "regions": []}

        for box, cls_id, conf in zip(boxes, cls_ids, confs):
            x1, y1, x2, y2 = box
            label = CLASS_NAMES.get(cls_id, "unknown")

            crop = pil_img.crop((x1, y1, x2, y2))
            text = self._recognise(crop)

            if label in result:
                result[label].append(text)

            region = {
                "class":  label,
                "conf":   round(conf, 3),
                "box":    {"x1": x1, "y1": y1, "x2": x2, "y2": y2},
                "text":   text,
            }
            if return_crops:
                region["crop"] = crop

            result["regions"].append(region)

            if verbose:
                print(f"  [{label}] ({x1},{y1})โ†’({x2},{y2})  conf={conf:.2f}  โ†’  {text!r}")

        return result

    # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    def to_document(self, result: dict) -> str:
        """
        Format result as a structured text document.

        Example output:
            [SUBJECT]
            แž—แŸ’แž“แŸ†แž–แŸแž‰ แž€แŸ’แžšแžปแž„

            [REFERENCE]
            แž›แŸแž แŸ แŸ แŸก

            [CONTENT]
            แžขแžแŸ’แžแž”แž‘แžŠแŸ†แž”แžผแž„
            แžขแžแŸ’แžแž”แž‘แž‘แžธแž–แžธแžš
        """
        lines = []
        for cls in ("subject", "reference", "content"):
            texts = result.get(cls, [])
            if texts:
                lines.append(f"[{cls.upper()}]")
                lines.extend(texts)
                lines.append("")
        return "\n".join(lines).strip()