Image-to-Text
Transformers
Safetensors
Khmer
khmer-ocr
feature-extraction
transformer
text-recognition
crnn
khmer-text-recognition
custom_code
Darayut commited on
Commit
3a57793
·
verified ·
1 Parent(s): 10cc428

Upload inference.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. inference.py +207 -0
inference.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from transformers import AutoModel, AutoTokenizer
4
+ from PIL import Image
5
+ from torchvision import transforms
6
+ import os
7
+ import argparse
8
+
9
+ class KhmerOCR:
10
+ def __init__(self, model_repo="Darayut/khmer-SeqSE-CRNN-Transformer", device=None):
11
+ """
12
+ Initializes the Khmer OCR model and tokenizer.
13
+ """
14
+ if device is None:
15
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
+ else:
17
+ self.device = device
18
+
19
+ print(f"⏳ Loading model from {model_repo} on {self.device}...")
20
+
21
+ # Load Model & Tokenizer with trust_remote_code=True
22
+ self.tokenizer = AutoTokenizer.from_pretrained(model_repo, trust_remote_code=True)
23
+ self.model = AutoModel.from_pretrained(model_repo, trust_remote_code=True).to(self.device)
24
+ self.model.eval()
25
+
26
+ # Build Vocab Mappings
27
+ self.vocab = self.tokenizer.get_vocab()
28
+ self.id2char = {v: k for k, v in self.vocab.items()}
29
+
30
+ # Special Tokens
31
+ self.sos_idx = self.vocab.get("<sos>", 1)
32
+ self.eos_idx = self.vocab.get("<eos>", 2)
33
+ self.pad_idx = self.vocab.get("<pad>", 0)
34
+ self.unk_idx = self.vocab.get("<unk>", 3)
35
+
36
+ # Image Transform (Matches Training)
37
+ self.transform = transforms.Compose([
38
+ transforms.Grayscale(),
39
+ transforms.ToTensor(),
40
+ transforms.Normalize(0.5, 0.5)
41
+ ])
42
+
43
+ def _chunk_image(self, img_tensor, chunk_width=100, overlap=16):
44
+ """Internal helper to split image into overlapping chunks."""
45
+ C, H, W = img_tensor.shape
46
+ chunks = []
47
+ start = 0
48
+ while start < W:
49
+ end = min(start + chunk_width, W)
50
+ chunk = img_tensor[:, :, start:end]
51
+ if chunk.shape[2] < chunk_width:
52
+ pad_size = chunk_width - chunk.shape[2]
53
+ chunk = F.pad(chunk, (0, pad_size, 0, 0), value=1.0)
54
+ chunks.append(chunk)
55
+ start += chunk_width - overlap
56
+ return chunks
57
+
58
+ def preprocess(self, image_source):
59
+ """
60
+ Preprocesses an image path or PIL Object into a batch of chunks.
61
+ """
62
+ # Load Image
63
+ if isinstance(image_source, str):
64
+ if not os.path.exists(image_source):
65
+ raise FileNotFoundError(f"Image not found at {image_source}")
66
+ image = Image.open(image_source).convert('L')
67
+ elif isinstance(image_source, Image.Image):
68
+ image = image_source.convert('L')
69
+ else:
70
+ raise ValueError("Input must be a file path or PIL Image.")
71
+
72
+ # Resize (Fixed Height: 48)
73
+ target_height = 48
74
+ aspect_ratio = image.width / image.height
75
+ new_width = int(target_height * aspect_ratio)
76
+ new_width = max(10, new_width)
77
+ image = image.resize((new_width, target_height), Image.Resampling.BILINEAR)
78
+
79
+ # Transform & Chunk
80
+ img_tensor = self.transform(image)
81
+ chunks = self._chunk_image(img_tensor, chunk_width=100, overlap=16)
82
+ chunks_tensor = torch.stack(chunks).to(self.device)
83
+ return chunks_tensor
84
+
85
+ def predict(self, image_source, method="beam", beam_width=3, max_len=256):
86
+ """
87
+ Main prediction method.
88
+ Args:
89
+ image_source: Path to image or PIL object.
90
+ method: 'greedy' or 'beam'.
91
+ beam_width: Width for beam search (default 3).
92
+ max_len: Max decoded sequence length.
93
+ """
94
+ chunks_tensor = self.preprocess(image_source)
95
+
96
+ # 1. Encode (CNN + Transformer + BiLSTM Smoothing)
97
+ with torch.no_grad():
98
+ # Wrap in list as model expects batch of images
99
+ memory = self.model([chunks_tensor])
100
+
101
+ # 2. Decode
102
+ if method == "greedy" or beam_width <= 1:
103
+ token_ids = self._greedy_decode(memory, max_len)
104
+ else:
105
+ token_ids = self._beam_search(memory, max_len, beam_width)
106
+
107
+ # 3. Convert IDs to Text (Manual mapping to avoid spacing issues)
108
+ result_text = ""
109
+ for idx in token_ids:
110
+ if idx in [self.sos_idx, self.eos_idx, self.pad_idx, self.unk_idx]:
111
+ continue
112
+ char = self.id2char.get(idx, "")
113
+ result_text += char
114
+
115
+ return result_text
116
+
117
+ def _greedy_decode(self, memory, max_len):
118
+ B, T, _ = memory.shape
119
+ memory_mask = torch.zeros((B, T), dtype=torch.bool, device=self.device)
120
+ generated = [self.sos_idx]
121
+
122
+ with torch.no_grad():
123
+ for _ in range(max_len):
124
+ tgt = torch.LongTensor([generated]).to(self.device)
125
+ logits = self.model.dec(tgt, memory, memory_mask)
126
+ next_token = torch.argmax(logits[0, -1, :]).item()
127
+ if next_token == self.eos_idx: break
128
+ generated.append(next_token)
129
+ return generated
130
+
131
+ def _beam_search(self, memory, max_len, beam_width):
132
+ B, T, D = memory.shape
133
+ memory = memory.expand(beam_width, -1, -1)
134
+ memory_mask = torch.zeros((beam_width, T), dtype=torch.bool, device=self.device)
135
+
136
+ beams = [(0.0, [self.sos_idx])]
137
+ completed_beams = []
138
+
139
+ with torch.no_grad():
140
+ for step in range(max_len):
141
+ k_curr = len(beams)
142
+ current_seqs = [b[1] for b in beams]
143
+ tgt = torch.tensor(current_seqs, dtype=torch.long, device=self.device)
144
+
145
+ step_logits = self.model.dec(tgt, memory[:k_curr], memory_mask[:k_curr])
146
+ log_probs = F.log_softmax(step_logits[:, -1, :], dim=-1)
147
+
148
+ candidates = []
149
+ for i in range(k_curr):
150
+ score_so_far, seq_so_far = beams[i]
151
+ topk_probs, topk_idx = log_probs[i].topk(beam_width)
152
+ for k in range(beam_width):
153
+ candidates.append((score_so_far + topk_probs[k].item(), seq_so_far + [topk_idx[k].item()]))
154
+
155
+ candidates.sort(key=lambda x: x[0], reverse=True)
156
+ next_beams = []
157
+ for score, seq in candidates:
158
+ if seq[-1] == self.eos_idx:
159
+ norm_score = score / (len(seq) - 1)
160
+ completed_beams.append((norm_score, seq))
161
+ else:
162
+ next_beams.append((score, seq))
163
+ if len(next_beams) == beam_width: break
164
+ beams = next_beams
165
+ if not beams: break
166
+
167
+ if completed_beams:
168
+ completed_beams.sort(key=lambda x: x[0], reverse=True)
169
+ return completed_beams[0][1]
170
+ elif beams:
171
+ return beams[0][1]
172
+ else:
173
+ return [self.sos_idx]
174
+
175
+ # ==============================================================================
176
+ # CLI USAGE
177
+ # ==============================================================================
178
+ if __name__ == "__main__":
179
+ parser = argparse.ArgumentParser(description="Khmer OCR Inference")
180
+ parser.add_argument("--image", type=str, required=True, help="Path to input image")
181
+ parser.add_argument("--method", type=str, default="beam", choices=["greedy", "beam"], help="Decoding method")
182
+ parser.add_argument("--beam_width", type=int, default=3, help="Width for beam search")
183
+ parser.add_argument("--max_len", type=int, default=256, help="Max output length")
184
+ parser.add_argument("--repo", type=str, default="Darayut/khmer-SeqSE-CRNN-Transformer", help="HF Model Repo")
185
+
186
+ args = parser.parse_args()
187
+
188
+ try:
189
+ # Initialize
190
+ ocr = KhmerOCR(model_repo=args.repo)
191
+
192
+ # Run
193
+ print(f"📷 Processing: {args.image}")
194
+ text = ocr.predict(args.image, method=args.method, beam_width=args.beam_width, max_len=args.max_len)
195
+
196
+ print("\n" + "="*30)
197
+ print(f"RESULT: {text}")
198
+ print("="*30)
199
+
200
+ # Auto-Save
201
+ out_path = os.path.splitext(args.image)[0] + ".txt"
202
+ with open(out_path, "w", encoding="utf-8") as f:
203
+ f.write(text)
204
+ print(f"💾 Saved to: {out_path}")
205
+
206
+ except Exception as e:
207
+ print(f"❌ Error: {e}")