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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kurdish Handwritten Line Recognition - Inference Script
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
# Single image
|
| 6 |
+
python inference.py --image sample.tif --model_path best_model.pth --vocab_path vocab.json
|
| 7 |
+
|
| 8 |
+
# Directory of images
|
| 9 |
+
python inference.py --image_dir ./test_images --model_path best_model.pth --vocab_path vocab.json
|
| 10 |
+
|
| 11 |
+
# With safetensors format
|
| 12 |
+
python inference.py --image sample.tif --model_path model.safetensors --vocab_path vocab.json
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import glob
|
| 17 |
+
import json
|
| 18 |
+
import math
|
| 19 |
+
import argparse
|
| 20 |
+
from PIL import Image
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torchvision.transforms as transforms
|
| 25 |
+
import torchvision.models as models
|
| 26 |
+
|
| 27 |
+
# ===============================
|
| 28 |
+
# Argument Parser
|
| 29 |
+
# ===============================
|
| 30 |
+
|
| 31 |
+
def parse_args():
|
| 32 |
+
parser = argparse.ArgumentParser(description="Kurdish Handwritten Line Recognition - Inference")
|
| 33 |
+
parser.add_argument("--image", type=str, default=None, help="Path to a single image")
|
| 34 |
+
parser.add_argument("--image_dir", type=str, default=None, help="Directory of images to process")
|
| 35 |
+
parser.add_argument("--model_path", type=str, required=True, help="Path to model (.pth or .safetensors)")
|
| 36 |
+
parser.add_argument("--vocab_path", type=str, required=True, help="Path to vocab.json")
|
| 37 |
+
parser.add_argument("--img_height", type=int, default=96)
|
| 38 |
+
parser.add_argument("--img_width", type=int, default=1235)
|
| 39 |
+
parser.add_argument("--hidden_size", type=int, default=256)
|
| 40 |
+
parser.add_argument("--encoder_layers", type=int, default=3)
|
| 41 |
+
parser.add_argument("--decoder_layers", type=int, default=3)
|
| 42 |
+
parser.add_argument("--num_heads", type=int, default=8)
|
| 43 |
+
parser.add_argument("--ff_dim", type=int, default=1024)
|
| 44 |
+
parser.add_argument("--max_seq_len", type=int, default=150)
|
| 45 |
+
parser.add_argument("--device", type=str, default=None, help="Device (cuda/cpu, auto-detected if not set)")
|
| 46 |
+
return parser.parse_args()
|
| 47 |
+
|
| 48 |
+
# ===============================
|
| 49 |
+
# Vocabulary
|
| 50 |
+
# ===============================
|
| 51 |
+
|
| 52 |
+
def load_vocabulary(vocab_path):
|
| 53 |
+
with open(vocab_path, "r", encoding="utf-8") as f:
|
| 54 |
+
vocab_data = json.load(f)
|
| 55 |
+
if "vocab_list" in vocab_data:
|
| 56 |
+
char_list = vocab_data["vocab_list"]
|
| 57 |
+
elif "char_to_idx" in vocab_data:
|
| 58 |
+
char_to_idx = vocab_data["char_to_idx"]
|
| 59 |
+
char_list = [None] * len(char_to_idx)
|
| 60 |
+
for char, idx in char_to_idx.items():
|
| 61 |
+
char_list[idx] = char
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError("Vocabulary JSON must contain 'vocab_list' or 'char_to_idx'")
|
| 64 |
+
idx_to_char = {idx: char for idx, char in enumerate(char_list)}
|
| 65 |
+
return char_list, idx_to_char
|
| 66 |
+
|
| 67 |
+
# ===============================
|
| 68 |
+
# Model Architecture
|
| 69 |
+
# ===============================
|
| 70 |
+
|
| 71 |
+
class PositionalEncoding(nn.Module):
|
| 72 |
+
def __init__(self, d_model, max_len=5000):
|
| 73 |
+
super().__init__()
|
| 74 |
+
pe = torch.zeros(max_len, d_model)
|
| 75 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 76 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
| 77 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 78 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 79 |
+
pe = pe.unsqueeze(0).transpose(0, 1)
|
| 80 |
+
self.register_buffer("pe", pe)
|
| 81 |
+
|
| 82 |
+
def forward(self, x):
|
| 83 |
+
return x + self.pe[:x.size(0), :]
|
| 84 |
+
|
| 85 |
+
class DenseNetFeatureExtractor(nn.Module):
|
| 86 |
+
def __init__(self, output_dim=256):
|
| 87 |
+
super().__init__()
|
| 88 |
+
densenet = models.densenet121(weights=models.DenseNet121_Weights.DEFAULT)
|
| 89 |
+
self.features = nn.Sequential(*list(densenet.children())[:-1])
|
| 90 |
+
self.adapt = nn.Conv2d(1024, output_dim, kernel_size=1)
|
| 91 |
+
|
| 92 |
+
def forward(self, x):
|
| 93 |
+
x = self.features(x)
|
| 94 |
+
x = self.adapt(x)
|
| 95 |
+
x = nn.functional.adaptive_avg_pool2d(x, (1, None))
|
| 96 |
+
x = x.squeeze(2)
|
| 97 |
+
return x.permute(0, 2, 1)
|
| 98 |
+
|
| 99 |
+
class TransformerOCRModel(nn.Module):
|
| 100 |
+
def __init__(self, vocab_size, hidden_size=256, nhead=8,
|
| 101 |
+
num_encoder_layers=3, num_decoder_layers=3,
|
| 102 |
+
dim_feedforward=1024, dropout=0.0, max_seq_len=150):
|
| 103 |
+
super().__init__()
|
| 104 |
+
self.feature_extractor = DenseNetFeatureExtractor(output_dim=hidden_size)
|
| 105 |
+
self.pos_encoder = PositionalEncoding(hidden_size)
|
| 106 |
+
self.transformer = nn.Transformer(
|
| 107 |
+
d_model=hidden_size, nhead=nhead,
|
| 108 |
+
num_encoder_layers=num_encoder_layers,
|
| 109 |
+
num_decoder_layers=num_decoder_layers,
|
| 110 |
+
dim_feedforward=dim_feedforward,
|
| 111 |
+
dropout=dropout, batch_first=True)
|
| 112 |
+
self.token_embedding = nn.Embedding(vocab_size, hidden_size)
|
| 113 |
+
self.output_projection = nn.Linear(hidden_size, vocab_size)
|
| 114 |
+
self.max_seq_len = max_seq_len
|
| 115 |
+
self.SOS_token = 1
|
| 116 |
+
self.EOS_token = 2
|
| 117 |
+
self.PAD_token = 0
|
| 118 |
+
|
| 119 |
+
def _generate_square_subsequent_mask(self, sz):
|
| 120 |
+
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
|
| 121 |
+
return mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, 0.0)
|
| 122 |
+
|
| 123 |
+
def _apply_pos_encoding(self, x):
|
| 124 |
+
x = x.permute(1, 0, 2)
|
| 125 |
+
x = self.pos_encoder(x)
|
| 126 |
+
return x.permute(1, 0, 2)
|
| 127 |
+
|
| 128 |
+
def generate(self, img):
|
| 129 |
+
self.eval()
|
| 130 |
+
with torch.no_grad():
|
| 131 |
+
if img.dim() == 3:
|
| 132 |
+
img = img.unsqueeze(0)
|
| 133 |
+
memory = self._apply_pos_encoding(self.feature_extractor(img))
|
| 134 |
+
ys = torch.ones(1, 1).fill_(self.SOS_token).long().to(img.device)
|
| 135 |
+
|
| 136 |
+
for _ in range(self.max_seq_len - 1):
|
| 137 |
+
tgt_embedded = self._apply_pos_encoding(self.token_embedding(ys))
|
| 138 |
+
tgt_mask = self._generate_square_subsequent_mask(ys.size(1)).to(img.device)
|
| 139 |
+
out = self.transformer(src=memory, tgt=tgt_embedded, tgt_mask=tgt_mask)
|
| 140 |
+
out = self.output_projection(out)
|
| 141 |
+
next_word = out[0, -1].argmax().item()
|
| 142 |
+
ys = torch.cat([ys, torch.ones(1, 1).long().fill_(next_word).to(img.device)], dim=1)
|
| 143 |
+
if next_word == self.EOS_token:
|
| 144 |
+
break
|
| 145 |
+
return ys[0]
|
| 146 |
+
|
| 147 |
+
# ===============================
|
| 148 |
+
# Image Preprocessing
|
| 149 |
+
# ===============================
|
| 150 |
+
|
| 151 |
+
def preprocess_image(image_path, img_height, img_width):
|
| 152 |
+
image = Image.open(image_path).convert("RGB")
|
| 153 |
+
orig_w, orig_h = image.size
|
| 154 |
+
new_h = img_height
|
| 155 |
+
new_w = min(int(new_h * (orig_w / orig_h)), img_width)
|
| 156 |
+
image = image.resize((new_w, new_h), Image.Resampling.LANCZOS)
|
| 157 |
+
|
| 158 |
+
canvas = Image.new("RGB", (img_width, img_height), color=(255, 255, 255))
|
| 159 |
+
canvas.paste(image, (0, 0))
|
| 160 |
+
|
| 161 |
+
transform = transforms.Compose([
|
| 162 |
+
transforms.ToTensor(),
|
| 163 |
+
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
|
| 164 |
+
])
|
| 165 |
+
return transform(canvas)
|
| 166 |
+
|
| 167 |
+
# ===============================
|
| 168 |
+
# Decode Output
|
| 169 |
+
# ===============================
|
| 170 |
+
|
| 171 |
+
def decode_output(tensor, idx_to_char):
|
| 172 |
+
if isinstance(tensor, torch.Tensor):
|
| 173 |
+
tensor = tensor.cpu().tolist()
|
| 174 |
+
text = ""
|
| 175 |
+
for idx in tensor:
|
| 176 |
+
if idx == 0 or idx == 1: # PAD or SOS
|
| 177 |
+
continue
|
| 178 |
+
if idx == 2: # EOS
|
| 179 |
+
break
|
| 180 |
+
if idx in idx_to_char:
|
| 181 |
+
text += idx_to_char[idx]
|
| 182 |
+
return text
|
| 183 |
+
|
| 184 |
+
# ===============================
|
| 185 |
+
# Main
|
| 186 |
+
# ===============================
|
| 187 |
+
|
| 188 |
+
def main():
|
| 189 |
+
args = parse_args()
|
| 190 |
+
|
| 191 |
+
if args.image is None and args.image_dir is None:
|
| 192 |
+
print("Error: Provide --image or --image_dir")
|
| 193 |
+
return
|
| 194 |
+
|
| 195 |
+
# Device
|
| 196 |
+
if args.device:
|
| 197 |
+
device = torch.device(args.device)
|
| 198 |
+
else:
|
| 199 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 200 |
+
print(f"Device: {device}")
|
| 201 |
+
|
| 202 |
+
# Vocabulary
|
| 203 |
+
char_list, idx_to_char = load_vocabulary(args.vocab_path)
|
| 204 |
+
vocab_size = len(char_list)
|
| 205 |
+
print(f"Vocabulary: {vocab_size} tokens")
|
| 206 |
+
|
| 207 |
+
# Model
|
| 208 |
+
model = TransformerOCRModel(
|
| 209 |
+
vocab_size=vocab_size,
|
| 210 |
+
hidden_size=args.hidden_size,
|
| 211 |
+
nhead=args.num_heads,
|
| 212 |
+
num_encoder_layers=args.encoder_layers,
|
| 213 |
+
num_decoder_layers=args.decoder_layers,
|
| 214 |
+
dim_feedforward=args.ff_dim,
|
| 215 |
+
max_seq_len=args.max_seq_len
|
| 216 |
+
).to(device)
|
| 217 |
+
|
| 218 |
+
# Load weights
|
| 219 |
+
if args.model_path.endswith(".safetensors"):
|
| 220 |
+
from safetensors.torch import load_file
|
| 221 |
+
state_dict = load_file(args.model_path)
|
| 222 |
+
model.load_state_dict(state_dict, strict=True)
|
| 223 |
+
else:
|
| 224 |
+
checkpoint = torch.load(args.model_path, map_location=device)
|
| 225 |
+
if "model_state_dict" in checkpoint:
|
| 226 |
+
model.load_state_dict(checkpoint["model_state_dict"], strict=True)
|
| 227 |
+
else:
|
| 228 |
+
model.load_state_dict(checkpoint, strict=True)
|
| 229 |
+
|
| 230 |
+
model.eval()
|
| 231 |
+
print(f"Model loaded: {sum(p.numel() for p in model.parameters()):,} parameters\n")
|
| 232 |
+
|
| 233 |
+
# Collect images
|
| 234 |
+
image_paths = []
|
| 235 |
+
if args.image:
|
| 236 |
+
image_paths = [args.image]
|
| 237 |
+
elif args.image_dir:
|
| 238 |
+
for ext in ("*.tif", "*.tiff", "*.png", "*.jpg", "*.jpeg", "*.bmp"):
|
| 239 |
+
image_paths.extend(glob.glob(os.path.join(args.image_dir, ext)))
|
| 240 |
+
image_paths.sort()
|
| 241 |
+
|
| 242 |
+
if not image_paths:
|
| 243 |
+
print("No images found.")
|
| 244 |
+
return
|
| 245 |
+
|
| 246 |
+
print(f"Processing {len(image_paths)} image(s)...\n")
|
| 247 |
+
print(f"{'File':<40} {'Predicted Text'}")
|
| 248 |
+
print("-" * 80)
|
| 249 |
+
|
| 250 |
+
for img_path in image_paths:
|
| 251 |
+
tensor = preprocess_image(img_path, args.img_height, args.img_width).to(device)
|
| 252 |
+
output = model.generate(tensor)
|
| 253 |
+
text = decode_output(output, idx_to_char)
|
| 254 |
+
filename = os.path.basename(img_path)
|
| 255 |
+
print(f"{filename:<40} {text}")
|
| 256 |
+
|
| 257 |
+
print(f"\nDone. {len(image_paths)} image(s) processed.")
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
main()
|