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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Kurdish Handwritten Line Recognition - Training Script
|
| 3 |
+
DenseNet121-Transformer Architecture with Constrained Synthetic Line Generation
|
| 4 |
+
|
| 5 |
+
Usage:
|
| 6 |
+
python train.py --data_dir ./data/DASTNUS --vocab_path ./vocab.json
|
| 7 |
+
python train.py --data_dir ./data/DASTNUS --vocab_path ./vocab.json --use_synthetic --use_writer_mixing
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
import glob
|
| 12 |
+
import time
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
import random
|
| 17 |
+
import re
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image, ImageFilter
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
import torch.optim as optim
|
| 25 |
+
import torch.utils.data as data
|
| 26 |
+
from torch.utils.data import ConcatDataset
|
| 27 |
+
import torchvision.transforms as transforms
|
| 28 |
+
import torchvision.models as models
|
| 29 |
+
from torchvision.transforms import InterpolationMode
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# ===============================
|
| 33 |
+
# Argument Parser
|
| 34 |
+
# ===============================
|
| 35 |
+
|
| 36 |
+
def parse_args():
|
| 37 |
+
parser = argparse.ArgumentParser(description="Kurdish Handwritten Line Recognition Training")
|
| 38 |
+
|
| 39 |
+
# Data paths
|
| 40 |
+
parser.add_argument("--data_dir", type=str, required=True,
|
| 41 |
+
help="Root directory of DASTNUS dataset")
|
| 42 |
+
parser.add_argument("--vocab_path", type=str, required=True,
|
| 43 |
+
help="Path to vocabulary JSON file (vocab.json)")
|
| 44 |
+
parser.add_argument("--synthetic_dir", type=str, default=None,
|
| 45 |
+
help="Directory containing synthetic handwritten lines")
|
| 46 |
+
parser.add_argument("--fixed_lines_dir", type=str, default=None,
|
| 47 |
+
help="Directory containing fixed-content handwritten lines")
|
| 48 |
+
|
| 49 |
+
# Data options
|
| 50 |
+
parser.add_argument("--use_synthetic", action="store_true",
|
| 51 |
+
help="Include synthetic handwritten lines in training")
|
| 52 |
+
parser.add_argument("--use_writer_mixing", action="store_true",
|
| 53 |
+
help="Include fixed-content lines from random writers")
|
| 54 |
+
parser.add_argument("--num_writers", type=int, default=50,
|
| 55 |
+
help="Number of writers to randomly select for mixing")
|
| 56 |
+
|
| 57 |
+
# Image dimensions
|
| 58 |
+
parser.add_argument("--img_height", type=int, default=96)
|
| 59 |
+
parser.add_argument("--img_width", type=int, default=1235)
|
| 60 |
+
|
| 61 |
+
# Training hyperparameters
|
| 62 |
+
parser.add_argument("--batch_size", type=int, default=64)
|
| 63 |
+
parser.add_argument("--num_epochs", type=int, default=80)
|
| 64 |
+
parser.add_argument("--learning_rate", type=float, default=5e-4)
|
| 65 |
+
parser.add_argument("--grad_clip", type=float, default=5.0)
|
| 66 |
+
parser.add_argument("--weight_decay", type=float, default=1e-4)
|
| 67 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 68 |
+
|
| 69 |
+
# Model parameters
|
| 70 |
+
parser.add_argument("--hidden_size", type=int, default=256)
|
| 71 |
+
parser.add_argument("--encoder_layers", type=int, default=3)
|
| 72 |
+
parser.add_argument("--decoder_layers", type=int, default=3)
|
| 73 |
+
parser.add_argument("--num_heads", type=int, default=8)
|
| 74 |
+
parser.add_argument("--dropout", type=float, default=0.4)
|
| 75 |
+
parser.add_argument("--ff_dim", type=int, default=1024)
|
| 76 |
+
|
| 77 |
+
# Early stopping
|
| 78 |
+
parser.add_argument("--patience", type=int, default=10)
|
| 79 |
+
|
| 80 |
+
# Augmentation
|
| 81 |
+
parser.add_argument("--no_aug", action="store_true",
|
| 82 |
+
help="Disable adaptive augmentation")
|
| 83 |
+
|
| 84 |
+
# Output
|
| 85 |
+
parser.add_argument("--output_dir", type=str, default="./output",
|
| 86 |
+
help="Directory to save models and logs")
|
| 87 |
+
|
| 88 |
+
return parser.parse_args()
|
| 89 |
+
|
| 90 |
+
# ===============================
|
| 91 |
+
# Vocabulary Loader
|
| 92 |
+
# ===============================
|
| 93 |
+
|
| 94 |
+
def load_vocabulary(vocab_path):
|
| 95 |
+
"""Load vocabulary from JSON file"""
|
| 96 |
+
with open(vocab_path, "r", encoding="utf-8") as f:
|
| 97 |
+
vocab_data = json.load(f)
|
| 98 |
+
|
| 99 |
+
if "vocab_list" in vocab_data:
|
| 100 |
+
char_list = vocab_data["vocab_list"]
|
| 101 |
+
elif "char_to_idx" in vocab_data:
|
| 102 |
+
char_to_idx = vocab_data["char_to_idx"]
|
| 103 |
+
char_list = [None] * len(char_to_idx)
|
| 104 |
+
for char, idx in char_to_idx.items():
|
| 105 |
+
char_list[idx] = char
|
| 106 |
+
else:
|
| 107 |
+
raise ValueError("Vocabulary JSON must contain 'vocab_list' or 'char_to_idx'")
|
| 108 |
+
|
| 109 |
+
char_to_idx = {char: idx for idx, char in enumerate(char_list)}
|
| 110 |
+
idx_to_char = {idx: char for idx, char in enumerate(char_list)}
|
| 111 |
+
|
| 112 |
+
PAD_token = 0
|
| 113 |
+
SOS_token = 1
|
| 114 |
+
EOS_token = 2
|
| 115 |
+
|
| 116 |
+
return char_list, char_to_idx, idx_to_char, PAD_token, SOS_token, EOS_token
|
| 117 |
+
|
| 118 |
+
# ===============================
|
| 119 |
+
# Helper Functions
|
| 120 |
+
# ===============================
|
| 121 |
+
|
| 122 |
+
def tensor_to_text(tensor, idx_to_char, PAD_token, SOS_token, EOS_token):
|
| 123 |
+
"""Convert a tensor of character indices to readable text"""
|
| 124 |
+
if isinstance(tensor, torch.Tensor):
|
| 125 |
+
tensor = tensor.cpu().tolist()
|
| 126 |
+
text = ""
|
| 127 |
+
for idx in tensor:
|
| 128 |
+
if idx == PAD_token or idx == SOS_token:
|
| 129 |
+
continue
|
| 130 |
+
if idx == EOS_token:
|
| 131 |
+
break
|
| 132 |
+
if idx in idx_to_char:
|
| 133 |
+
text += idx_to_char[idx]
|
| 134 |
+
return text
|
| 135 |
+
|
| 136 |
+
def extract_writer_id(filename):
|
| 137 |
+
"""Extract writer ID from filename (e.g., DNDK00002_2_1.tif -> 2)"""
|
| 138 |
+
basename = os.path.basename(filename)
|
| 139 |
+
match = re.match(r"DNDK(\d+)", basename)
|
| 140 |
+
if match:
|
| 141 |
+
return int(match.group(1))
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
def get_unique_writers(directory):
|
| 145 |
+
"""Get all unique writer IDs from a directory"""
|
| 146 |
+
image_files = glob.glob(os.path.join(directory, "*.tif"))
|
| 147 |
+
writer_ids = set()
|
| 148 |
+
for f in image_files:
|
| 149 |
+
wid = extract_writer_id(f)
|
| 150 |
+
if wid is not None:
|
| 151 |
+
writer_ids.add(wid)
|
| 152 |
+
return sorted(list(writer_ids))
|
| 153 |
+
|
| 154 |
+
def filter_files_by_writers(directory, selected_writers):
|
| 155 |
+
"""Filter image files to only include those from selected writers"""
|
| 156 |
+
all_files = glob.glob(os.path.join(directory, "*.tif"))
|
| 157 |
+
return [f for f in all_files if extract_writer_id(f) in selected_writers]
|
| 158 |
+
|
| 159 |
+
# ===============================
|
| 160 |
+
# Dataset Class
|
| 161 |
+
# ===============================
|
| 162 |
+
|
| 163 |
+
# Global variables for adaptive augmentation
|
| 164 |
+
current_epoch = 0
|
| 165 |
+
num_epochs_global = 80
|
| 166 |
+
overfitting_detected = False
|
| 167 |
+
validation_loss_history = []
|
| 168 |
+
training_loss_history = []
|
| 169 |
+
|
| 170 |
+
class KurdishLineDataset(data.Dataset):
|
| 171 |
+
def __init__(self, root_dir=None, transform=None, max_samples=None,
|
| 172 |
+
dataset_name="", image_files=None, img_height=96, img_width=1235,
|
| 173 |
+
char_to_idx=None, SOS_token=1, EOS_token=2):
|
| 174 |
+
self.transform = transform
|
| 175 |
+
self.dataset_name = dataset_name
|
| 176 |
+
self.img_height = img_height
|
| 177 |
+
self.img_width = img_width
|
| 178 |
+
self.char_to_idx = char_to_idx
|
| 179 |
+
self.SOS_token = SOS_token
|
| 180 |
+
self.EOS_token = EOS_token
|
| 181 |
+
|
| 182 |
+
if image_files is not None:
|
| 183 |
+
self.image_files = image_files
|
| 184 |
+
else:
|
| 185 |
+
self.image_files = glob.glob(os.path.join(root_dir, "*.tif"))
|
| 186 |
+
|
| 187 |
+
if max_samples and max_samples < len(self.image_files):
|
| 188 |
+
self.image_files = self.image_files[:max_samples]
|
| 189 |
+
|
| 190 |
+
print(f"Loaded {len(self.image_files)} images for {dataset_name}")
|
| 191 |
+
|
| 192 |
+
def __len__(self):
|
| 193 |
+
return len(self.image_files)
|
| 194 |
+
|
| 195 |
+
def __getitem__(self, idx):
|
| 196 |
+
img_path = self.image_files[idx]
|
| 197 |
+
label_path = os.path.splitext(img_path)[0] + ".txt"
|
| 198 |
+
|
| 199 |
+
image = Image.open(img_path).convert("RGB")
|
| 200 |
+
orig_width, orig_height = image.size
|
| 201 |
+
aspect_ratio = orig_width / orig_height
|
| 202 |
+
|
| 203 |
+
new_height = self.img_height
|
| 204 |
+
new_width = min(int(new_height * aspect_ratio), self.img_width)
|
| 205 |
+
image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 206 |
+
|
| 207 |
+
target_img = Image.new("RGB", (self.img_width, self.img_height), color=(255, 255, 255))
|
| 208 |
+
target_img.paste(image, (0, 0))
|
| 209 |
+
|
| 210 |
+
if self.transform:
|
| 211 |
+
target_img = self.transform(target_img)
|
| 212 |
+
|
| 213 |
+
try:
|
| 214 |
+
with open(label_path, "r", encoding="utf-8") as f:
|
| 215 |
+
text = f.readline().strip()
|
| 216 |
+
except UnicodeDecodeError:
|
| 217 |
+
with open(label_path, "r", encoding="utf-8-sig") as f:
|
| 218 |
+
text = f.readline().strip()
|
| 219 |
+
|
| 220 |
+
indices = ([self.SOS_token] +
|
| 221 |
+
[self.char_to_idx.get(char, self.char_to_idx.get(" ", 0)) for char in text] +
|
| 222 |
+
[self.EOS_token])
|
| 223 |
+
|
| 224 |
+
target = torch.LongTensor(indices)
|
| 225 |
+
target_length = len(indices)
|
| 226 |
+
|
| 227 |
+
return target_img, target, target_length, text
|
| 228 |
+
|
| 229 |
+
def collate_fn(batch):
|
| 230 |
+
"""Custom collate function for padding sequences"""
|
| 231 |
+
batch.sort(key=lambda x: x[2], reverse=True)
|
| 232 |
+
images, targets, lengths, original_texts = zip(*batch)
|
| 233 |
+
|
| 234 |
+
images = torch.stack(images, 0)
|
| 235 |
+
max_length = max(lengths)
|
| 236 |
+
|
| 237 |
+
padded_targets = torch.zeros(len(targets), max_length).long()
|
| 238 |
+
for i, target in enumerate(targets):
|
| 239 |
+
padded_targets[i, :lengths[i]] = target[:lengths[i]]
|
| 240 |
+
|
| 241 |
+
lengths = torch.LongTensor(lengths)
|
| 242 |
+
return images, padded_targets, lengths, original_texts
|
| 243 |
+
|
| 244 |
+
# ===============================
|
| 245 |
+
# Adaptive Augmentation
|
| 246 |
+
# ===============================
|
| 247 |
+
|
| 248 |
+
class AdaptiveStrokeWidthJitter:
|
| 249 |
+
def __init__(self, base_p=0.2, max_p=0.6, base_kernel=3, max_kernel=5):
|
| 250 |
+
self.base_p, self.max_p = base_p, max_p
|
| 251 |
+
self.base_kernel, self.max_kernel = base_kernel, max_kernel
|
| 252 |
+
|
| 253 |
+
def __call__(self, img):
|
| 254 |
+
progress = min(current_epoch / num_epochs_global, 1.0)
|
| 255 |
+
factor = 1.5 if overfitting_detected else 1.0
|
| 256 |
+
p = min(self.base_p + (self.max_p - self.base_p) * progress * factor, self.max_p)
|
| 257 |
+
kernel = self.base_kernel + int(2 * progress)
|
| 258 |
+
if kernel % 2 == 0:
|
| 259 |
+
kernel += 1
|
| 260 |
+
kernel = min(kernel, self.max_kernel)
|
| 261 |
+
if random.random() < p:
|
| 262 |
+
if random.random() < 0.5:
|
| 263 |
+
return img.filter(ImageFilter.MinFilter(kernel))
|
| 264 |
+
return img.filter(ImageFilter.MaxFilter(kernel))
|
| 265 |
+
return img
|
| 266 |
+
|
| 267 |
+
class AdaptiveGaussianNoise:
|
| 268 |
+
def __init__(self, base_std=(0.0, 0.01), max_std=(0.0, 0.03), base_p=0.3, max_p=0.7):
|
| 269 |
+
self.base_std, self.max_std = base_std, max_std
|
| 270 |
+
self.base_p, self.max_p = base_p, max_p
|
| 271 |
+
|
| 272 |
+
def __call__(self, tensor):
|
| 273 |
+
progress = min(current_epoch / num_epochs_global, 1.0)
|
| 274 |
+
factor = 1.5 if overfitting_detected else 1.0
|
| 275 |
+
p = min(self.base_p + (self.max_p - self.base_p) * progress * factor, self.max_p)
|
| 276 |
+
std_high = min(self.base_std[1] + (self.max_std[1] - self.base_std[1]) * progress * factor,
|
| 277 |
+
self.max_std[1])
|
| 278 |
+
if torch.rand(1).item() < p:
|
| 279 |
+
noise = torch.randn_like(tensor) * random.uniform(self.base_std[0], std_high)
|
| 280 |
+
tensor = torch.clamp(tensor + noise, 0.0, 1.0)
|
| 281 |
+
return tensor
|
| 282 |
+
|
| 283 |
+
def build_adaptive_train_transform():
|
| 284 |
+
class AdaptiveTransform:
|
| 285 |
+
def __call__(self, img):
|
| 286 |
+
progress = min(current_epoch / num_epochs_global, 1.0)
|
| 287 |
+
factor = 1.3 if overfitting_detected else 1.0
|
| 288 |
+
|
| 289 |
+
if random.random() < min(0.6 + 0.35 * progress * factor, 0.95):
|
| 290 |
+
b = min(0.1 + 0.2 * progress * factor, 0.3)
|
| 291 |
+
img = transforms.ColorJitter(brightness=b, contrast=b)(img)
|
| 292 |
+
|
| 293 |
+
if random.random() < min(0.7 + 0.25 * progress * factor, 0.95):
|
| 294 |
+
deg = min(1 + 4 * progress * factor, 5)
|
| 295 |
+
shear = min(3 + 7 * progress * factor, 10)
|
| 296 |
+
img = transforms.RandomAffine(
|
| 297 |
+
degrees=deg,
|
| 298 |
+
translate=(min(0.01 + 0.02 * progress, 0.03),
|
| 299 |
+
min(0.03 + 0.05 * progress, 0.08)),
|
| 300 |
+
scale=(max(1 - 0.02 - 0.08 * progress, 0.90),
|
| 301 |
+
min(1 + 0.02 + 0.08 * progress, 1.10)),
|
| 302 |
+
shear=(-shear, shear),
|
| 303 |
+
interpolation=InterpolationMode.BILINEAR, fill=255)(img)
|
| 304 |
+
|
| 305 |
+
if random.random() < min(0.1 + 0.4 * progress * factor, 0.5):
|
| 306 |
+
dist = min(0.02 + 0.06 * progress * factor, 0.08)
|
| 307 |
+
img = transforms.RandomPerspective(
|
| 308 |
+
distortion_scale=dist, p=1.0,
|
| 309 |
+
interpolation=InterpolationMode.BILINEAR, fill=255)(img)
|
| 310 |
+
|
| 311 |
+
if random.random() < min(0.15 + 0.2 * progress, 0.35):
|
| 312 |
+
img = transforms.GaussianBlur(
|
| 313 |
+
kernel_size=3, sigma=(0.1, min(0.5 + 0.5 * progress, 1.0)))(img)
|
| 314 |
+
|
| 315 |
+
img = AdaptiveStrokeWidthJitter()(img)
|
| 316 |
+
img = transforms.ToTensor()(img)
|
| 317 |
+
img = AdaptiveGaussianNoise()(img)
|
| 318 |
+
|
| 319 |
+
if random.random() < min(0.1 + 0.3 * progress * factor, 0.4):
|
| 320 |
+
img = transforms.RandomErasing(
|
| 321 |
+
p=1.0, scale=(0.01, min(0.01 + 0.04 * progress, 0.05)),
|
| 322 |
+
ratio=(0.3, 3.3), value="random")(img)
|
| 323 |
+
|
| 324 |
+
img = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))(img)
|
| 325 |
+
return img
|
| 326 |
+
|
| 327 |
+
return AdaptiveTransform()
|
| 328 |
+
|
| 329 |
+
def build_eval_transform():
|
| 330 |
+
return transforms.Compose([
|
| 331 |
+
transforms.ToTensor(),
|
| 332 |
+
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
|
| 333 |
+
])
|
| 334 |
+
|
| 335 |
+
# ===============================
|
| 336 |
+
# Model Architecture
|
| 337 |
+
# ===============================
|
| 338 |
+
|
| 339 |
+
class PositionalEncoding(nn.Module):
|
| 340 |
+
def __init__(self, d_model, max_len=5000):
|
| 341 |
+
super().__init__()
|
| 342 |
+
pe = torch.zeros(max_len, d_model)
|
| 343 |
+
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
|
| 344 |
+
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
| 345 |
+
pe[:, 0::2] = torch.sin(position * div_term)
|
| 346 |
+
pe[:, 1::2] = torch.cos(position * div_term)
|
| 347 |
+
pe = pe.unsqueeze(0).transpose(0, 1)
|
| 348 |
+
self.register_buffer("pe", pe)
|
| 349 |
+
|
| 350 |
+
def forward(self, x):
|
| 351 |
+
return x + self.pe[:x.size(0), :]
|
| 352 |
+
|
| 353 |
+
class DenseNetFeatureExtractor(nn.Module):
|
| 354 |
+
def __init__(self, output_dim=256):
|
| 355 |
+
super().__init__()
|
| 356 |
+
densenet = models.densenet121(weights=models.DenseNet121_Weights.DEFAULT)
|
| 357 |
+
self.features = nn.Sequential(*list(densenet.children())[:-1])
|
| 358 |
+
self.adapt = nn.Conv2d(1024, output_dim, kernel_size=1)
|
| 359 |
+
|
| 360 |
+
def forward(self, x):
|
| 361 |
+
x = self.features(x)
|
| 362 |
+
x = self.adapt(x)
|
| 363 |
+
x = nn.functional.adaptive_avg_pool2d(x, (1, None))
|
| 364 |
+
x = x.squeeze(2)
|
| 365 |
+
return x.permute(0, 2, 1)
|
| 366 |
+
|
| 367 |
+
class TransformerOCRModel(nn.Module):
|
| 368 |
+
def __init__(self, vocab_size, hidden_size=256, nhead=8,
|
| 369 |
+
num_encoder_layers=3, num_decoder_layers=3,
|
| 370 |
+
dim_feedforward=1024, dropout=0.4,
|
| 371 |
+
PAD_token=0, SOS_token=1, EOS_token=2, max_seq_len=150):
|
| 372 |
+
super().__init__()
|
| 373 |
+
self.feature_extractor = DenseNetFeatureExtractor(output_dim=hidden_size)
|
| 374 |
+
self.pos_encoder = PositionalEncoding(hidden_size)
|
| 375 |
+
self.transformer = nn.Transformer(
|
| 376 |
+
d_model=hidden_size, nhead=nhead,
|
| 377 |
+
num_encoder_layers=num_encoder_layers,
|
| 378 |
+
num_decoder_layers=num_decoder_layers,
|
| 379 |
+
dim_feedforward=dim_feedforward,
|
| 380 |
+
dropout=dropout, batch_first=True)
|
| 381 |
+
self.token_embedding = nn.Embedding(vocab_size, hidden_size)
|
| 382 |
+
self.output_projection = nn.Linear(hidden_size, vocab_size)
|
| 383 |
+
self.hidden_size = hidden_size
|
| 384 |
+
self.vocab_size = vocab_size
|
| 385 |
+
self.PAD_token = PAD_token
|
| 386 |
+
self.SOS_token = SOS_token
|
| 387 |
+
self.EOS_token = EOS_token
|
| 388 |
+
self.max_seq_len = max_seq_len
|
| 389 |
+
self._init_parameters()
|
| 390 |
+
|
| 391 |
+
def _init_parameters(self):
|
| 392 |
+
nn.init.xavier_uniform_(self.token_embedding.weight)
|
| 393 |
+
nn.init.xavier_uniform_(self.output_projection.weight)
|
| 394 |
+
|
| 395 |
+
def _generate_square_subsequent_mask(self, sz):
|
| 396 |
+
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
|
| 397 |
+
return mask.float().masked_fill(mask == 0, float("-inf")).masked_fill(mask == 1, 0.0)
|
| 398 |
+
|
| 399 |
+
def _apply_pos_encoding(self, x):
|
| 400 |
+
x = x.permute(1, 0, 2)
|
| 401 |
+
x = self.pos_encoder(x)
|
| 402 |
+
return x.permute(1, 0, 2)
|
| 403 |
+
|
| 404 |
+
def forward(self, src, tgt):
|
| 405 |
+
memory = self._apply_pos_encoding(self.feature_extractor(src))
|
| 406 |
+
tgt_input = tgt[:, :-1]
|
| 407 |
+
tgt_embedded = self._apply_pos_encoding(self.token_embedding(tgt_input))
|
| 408 |
+
tgt_mask = self._generate_square_subsequent_mask(tgt_embedded.size(1)).to(src.device)
|
| 409 |
+
output = self.transformer(
|
| 410 |
+
src=memory, tgt=tgt_embedded, tgt_mask=tgt_mask,
|
| 411 |
+
src_is_causal=False, tgt_is_causal=True)
|
| 412 |
+
return self.output_projection(output)
|
| 413 |
+
|
| 414 |
+
def generate(self, img):
|
| 415 |
+
"""Generate text from a single image"""
|
| 416 |
+
was_training = self.training
|
| 417 |
+
self.eval()
|
| 418 |
+
with torch.no_grad():
|
| 419 |
+
if img.dim() == 3:
|
| 420 |
+
img = img.unsqueeze(0)
|
| 421 |
+
memory = self._apply_pos_encoding(self.feature_extractor(img))
|
| 422 |
+
ys = torch.ones(1, 1).fill_(self.SOS_token).long().to(img.device)
|
| 423 |
+
|
| 424 |
+
for _ in range(self.max_seq_len - 1):
|
| 425 |
+
tgt_embedded = self._apply_pos_encoding(self.token_embedding(ys))
|
| 426 |
+
tgt_mask = self._generate_square_subsequent_mask(ys.size(1)).to(img.device)
|
| 427 |
+
out = self.transformer(src=memory, tgt=tgt_embedded, tgt_mask=tgt_mask)
|
| 428 |
+
out = self.output_projection(out)
|
| 429 |
+
next_word = out[0, -1].argmax().item()
|
| 430 |
+
ys = torch.cat([ys, torch.ones(1, 1).long().fill_(next_word).to(img.device)], dim=1)
|
| 431 |
+
if next_word == self.EOS_token:
|
| 432 |
+
break
|
| 433 |
+
|
| 434 |
+
if was_training:
|
| 435 |
+
self.train(True)
|
| 436 |
+
return ys[0]
|
| 437 |
+
|
| 438 |
+
def generate_batch(self, imgs):
|
| 439 |
+
"""Generate text from a batch of images"""
|
| 440 |
+
self.eval()
|
| 441 |
+
batch_size = imgs.size(0)
|
| 442 |
+
with torch.no_grad():
|
| 443 |
+
memory = self._apply_pos_encoding(self.feature_extractor(imgs))
|
| 444 |
+
ys = torch.ones(batch_size, 1).fill_(self.SOS_token).long().to(imgs.device)
|
| 445 |
+
finished = torch.zeros(batch_size, dtype=torch.bool, device=imgs.device)
|
| 446 |
+
|
| 447 |
+
for _ in range(self.max_seq_len - 1):
|
| 448 |
+
tgt_embedded = self._apply_pos_encoding(self.token_embedding(ys))
|
| 449 |
+
tgt_mask = self._generate_square_subsequent_mask(ys.size(1)).to(imgs.device)
|
| 450 |
+
out = self.transformer(src=memory, tgt=tgt_embedded, tgt_mask=tgt_mask)
|
| 451 |
+
out = self.output_projection(out)
|
| 452 |
+
next_tokens = out[:, -1].argmax(dim=-1)
|
| 453 |
+
next_tokens[finished] = self.PAD_token
|
| 454 |
+
ys = torch.cat([ys, next_tokens.unsqueeze(1)], dim=1)
|
| 455 |
+
finished = finished | (next_tokens == self.EOS_token)
|
| 456 |
+
if finished.all():
|
| 457 |
+
break
|
| 458 |
+
return ys
|
| 459 |
+
|
| 460 |
+
# ===============================
|
| 461 |
+
# Metrics
|
| 462 |
+
# ===============================
|
| 463 |
+
|
| 464 |
+
def levenshtein_distance(s1, s2):
|
| 465 |
+
if len(s1) < len(s2):
|
| 466 |
+
return levenshtein_distance(s2, s1)
|
| 467 |
+
if len(s2) == 0:
|
| 468 |
+
return len(s1)
|
| 469 |
+
prev = range(len(s2) + 1)
|
| 470 |
+
for c1 in s1:
|
| 471 |
+
curr = [prev[0] + 1]
|
| 472 |
+
for j, c2 in enumerate(s2):
|
| 473 |
+
curr.append(min(prev[j + 1] + 1, curr[j] + 1, prev[j] + (c1 != c2)))
|
| 474 |
+
prev = curr
|
| 475 |
+
return prev[-1]
|
| 476 |
+
|
| 477 |
+
def calculate_cer(preds, targets):
|
| 478 |
+
total_dist, total_chars = 0, 0
|
| 479 |
+
for p, t in zip(preds, targets):
|
| 480 |
+
total_dist += levenshtein_distance(p, t)
|
| 481 |
+
total_chars += len(t)
|
| 482 |
+
return total_dist / max(1, total_chars)
|
| 483 |
+
|
| 484 |
+
def calculate_wer(preds, targets):
|
| 485 |
+
total_dist, total_words = 0, 0
|
| 486 |
+
for p, t in zip(preds, targets):
|
| 487 |
+
total_dist += levenshtein_distance(p.split(), t.split())
|
| 488 |
+
total_words += len(t.split())
|
| 489 |
+
return total_dist / max(1, total_words)
|
| 490 |
+
|
| 491 |
+
def evaluate_cer(model, dataloader, device, idx_to_char, PAD_token, SOS_token, EOS_token):
|
| 492 |
+
model.eval()
|
| 493 |
+
all_preds, all_targets = [], []
|
| 494 |
+
with torch.no_grad():
|
| 495 |
+
for images, _, _, texts in tqdm(dataloader, desc="Evaluating"):
|
| 496 |
+
images = images.to(device)
|
| 497 |
+
batch_output = model.generate_batch(images)
|
| 498 |
+
for seq in batch_output:
|
| 499 |
+
all_preds.append(tensor_to_text(seq, idx_to_char, PAD_token, SOS_token, EOS_token))
|
| 500 |
+
all_targets.extend(texts)
|
| 501 |
+
cer = calculate_cer(all_preds, all_targets)
|
| 502 |
+
return cer, all_preds, all_targets
|
| 503 |
+
|
| 504 |
+
# ===============================
|
| 505 |
+
# Early Stopping
|
| 506 |
+
# ===============================
|
| 507 |
+
|
| 508 |
+
class EarlyStopping:
|
| 509 |
+
def __init__(self, patience=10):
|
| 510 |
+
self.patience = patience
|
| 511 |
+
self.counter = 0
|
| 512 |
+
self.best_cer = float("inf")
|
| 513 |
+
self.early_stop = False
|
| 514 |
+
|
| 515 |
+
def __call__(self, val_cer, model, epoch, path):
|
| 516 |
+
if val_cer < self.best_cer:
|
| 517 |
+
self.best_cer = val_cer
|
| 518 |
+
self.counter = 0
|
| 519 |
+
torch.save({
|
| 520 |
+
"epoch": epoch,
|
| 521 |
+
"model_state_dict": model.state_dict(),
|
| 522 |
+
"val_cer": val_cer
|
| 523 |
+
}, path)
|
| 524 |
+
print(f"Model saved (Val CER: {val_cer:.4f})")
|
| 525 |
+
else:
|
| 526 |
+
self.counter += 1
|
| 527 |
+
print(f"Early stopping: {self.counter}/{self.patience}")
|
| 528 |
+
if self.counter >= self.patience:
|
| 529 |
+
self.early_stop = True
|
| 530 |
+
print("Early stopping triggered.")
|
| 531 |
+
|
| 532 |
+
# ===============================
|
| 533 |
+
# Training Loop
|
| 534 |
+
# ===============================
|
| 535 |
+
|
| 536 |
+
def train_epoch(model, dataloader, optimizer, criterion, device, scheduler, PAD_token):
|
| 537 |
+
model.train()
|
| 538 |
+
epoch_loss = 0
|
| 539 |
+
for images, targets, _, _ in tqdm(dataloader, desc="Training"):
|
| 540 |
+
images, targets = images.to(device), targets.to(device)
|
| 541 |
+
optimizer.zero_grad()
|
| 542 |
+
outputs = model(images, targets)
|
| 543 |
+
outputs = outputs.reshape(-1, outputs.shape[-1])
|
| 544 |
+
targets_flat = targets[:, 1:].reshape(-1)
|
| 545 |
+
loss = criterion(outputs, targets_flat)
|
| 546 |
+
loss.backward()
|
| 547 |
+
torch.nn.utils.clip_grad_norm_(model.parameters(), args.grad_clip)
|
| 548 |
+
optimizer.step()
|
| 549 |
+
scheduler.step()
|
| 550 |
+
epoch_loss += loss.item()
|
| 551 |
+
return epoch_loss / len(dataloader)
|
| 552 |
+
|
| 553 |
+
def evaluate_model(model, dataloader, criterion, device, PAD_token):
|
| 554 |
+
model.eval()
|
| 555 |
+
epoch_loss = 0
|
| 556 |
+
with torch.no_grad():
|
| 557 |
+
for images, targets, _, _ in dataloader:
|
| 558 |
+
images, targets = images.to(device), targets.to(device)
|
| 559 |
+
outputs = model(images, targets)
|
| 560 |
+
outputs = outputs.reshape(-1, outputs.shape[-1])
|
| 561 |
+
targets_flat = targets[:, 1:].reshape(-1)
|
| 562 |
+
loss = criterion(outputs, targets_flat)
|
| 563 |
+
epoch_loss += loss.item()
|
| 564 |
+
return epoch_loss / len(dataloader)
|
| 565 |
+
|
| 566 |
+
# ===============================
|
| 567 |
+
# Main
|
| 568 |
+
# ===============================
|
| 569 |
+
|
| 570 |
+
def main():
|
| 571 |
+
global current_epoch, num_epochs_global, overfitting_detected
|
| 572 |
+
global validation_loss_history, training_loss_history, args
|
| 573 |
+
|
| 574 |
+
args = parse_args()
|
| 575 |
+
|
| 576 |
+
# Set seeds
|
| 577 |
+
torch.manual_seed(args.seed)
|
| 578 |
+
random.seed(args.seed)
|
| 579 |
+
np.random.seed(args.seed)
|
| 580 |
+
num_epochs_global = args.num_epochs
|
| 581 |
+
|
| 582 |
+
# Device
|
| 583 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 584 |
+
print(f"Using device: {device}")
|
| 585 |
+
|
| 586 |
+
# Output directory
|
| 587 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 588 |
+
|
| 589 |
+
# Load vocabulary
|
| 590 |
+
char_list, char_to_idx, idx_to_char, PAD_token, SOS_token, EOS_token = \
|
| 591 |
+
load_vocabulary(args.vocab_path)
|
| 592 |
+
vocab_size = len(char_list)
|
| 593 |
+
print(f"Vocabulary size: {vocab_size}")
|
| 594 |
+
|
| 595 |
+
# Transforms
|
| 596 |
+
train_transform = build_eval_transform() if args.no_aug else build_adaptive_train_transform()
|
| 597 |
+
eval_transform = build_eval_transform()
|
| 598 |
+
|
| 599 |
+
# Dataset common kwargs
|
| 600 |
+
ds_kwargs = dict(img_height=args.img_height, img_width=args.img_width,
|
| 601 |
+
char_to_idx=char_to_idx, SOS_token=SOS_token, EOS_token=EOS_token)
|
| 602 |
+
|
| 603 |
+
# Build datasets
|
| 604 |
+
real_train_dir = os.path.join(args.data_dir, "Training")
|
| 605 |
+
real_val_dir = os.path.join(args.data_dir, "Validation")
|
| 606 |
+
real_test_dir = os.path.join(args.data_dir, "Testing")
|
| 607 |
+
|
| 608 |
+
train_datasets = [
|
| 609 |
+
KurdishLineDataset(real_train_dir, transform=train_transform,
|
| 610 |
+
dataset_name="Real Training", **ds_kwargs)
|
| 611 |
+
]
|
| 612 |
+
|
| 613 |
+
if args.use_synthetic and args.synthetic_dir:
|
| 614 |
+
syn_dir = os.path.join(args.synthetic_dir, "Training")
|
| 615 |
+
train_datasets.append(
|
| 616 |
+
KurdishLineDataset(syn_dir, transform=train_transform,
|
| 617 |
+
dataset_name="Synthetic Training", **ds_kwargs))
|
| 618 |
+
|
| 619 |
+
if args.use_writer_mixing and args.fixed_lines_dir:
|
| 620 |
+
fix_dir = os.path.join(args.fixed_lines_dir, "Training")
|
| 621 |
+
all_writers = get_unique_writers(fix_dir)
|
| 622 |
+
selected = random.sample(all_writers, min(args.num_writers, len(all_writers)))
|
| 623 |
+
selected_files = filter_files_by_writers(fix_dir, set(selected))
|
| 624 |
+
train_datasets.append(
|
| 625 |
+
KurdishLineDataset(image_files=selected_files, transform=train_transform,
|
| 626 |
+
dataset_name=f"Fixed {len(selected)} Writers", **ds_kwargs))
|
| 627 |
+
|
| 628 |
+
train_dataset = ConcatDataset(train_datasets) if len(train_datasets) > 1 else train_datasets[0]
|
| 629 |
+
val_dataset = KurdishLineDataset(real_val_dir, transform=eval_transform,
|
| 630 |
+
dataset_name="Validation", **ds_kwargs)
|
| 631 |
+
test_dataset = KurdishLineDataset(real_test_dir, transform=eval_transform,
|
| 632 |
+
dataset_name="Testing", **ds_kwargs)
|
| 633 |
+
|
| 634 |
+
print(f"\nTraining: {len(train_dataset)} | Validation: {len(val_dataset)} | Testing: {len(test_dataset)}")
|
| 635 |
+
|
| 636 |
+
# Data loaders
|
| 637 |
+
loader_kwargs = dict(num_workers=0, pin_memory=True, collate_fn=collate_fn)
|
| 638 |
+
train_loader = data.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True, **loader_kwargs)
|
| 639 |
+
val_loader = data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, **loader_kwargs)
|
| 640 |
+
test_loader = data.DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, **loader_kwargs)
|
| 641 |
+
|
| 642 |
+
# Model
|
| 643 |
+
model = TransformerOCRModel(
|
| 644 |
+
vocab_size=vocab_size, hidden_size=args.hidden_size,
|
| 645 |
+
nhead=args.num_heads, num_encoder_layers=args.encoder_layers,
|
| 646 |
+
num_decoder_layers=args.decoder_layers, dim_feedforward=args.ff_dim,
|
| 647 |
+
dropout=args.dropout, PAD_token=PAD_token, SOS_token=SOS_token,
|
| 648 |
+
EOS_token=EOS_token).to(device)
|
| 649 |
+
|
| 650 |
+
total_params = sum(p.numel() for p in model.parameters())
|
| 651 |
+
print(f"Model parameters: {total_params:,}")
|
| 652 |
+
|
| 653 |
+
# Optimizer and schedulers
|
| 654 |
+
optimizer = optim.AdamW(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
|
| 655 |
+
onecycle = optim.lr_scheduler.OneCycleLR(
|
| 656 |
+
optimizer, max_lr=args.learning_rate,
|
| 657 |
+
steps_per_epoch=len(train_loader), epochs=args.num_epochs, pct_start=0.1)
|
| 658 |
+
plateau = optim.lr_scheduler.ReduceLROnPlateau(
|
| 659 |
+
optimizer, mode="min", factor=0.5, patience=2, min_lr=1e-6)
|
| 660 |
+
|
| 661 |
+
criterion = nn.CrossEntropyLoss(ignore_index=PAD_token)
|
| 662 |
+
early_stopping = EarlyStopping(patience=args.patience)
|
| 663 |
+
best_model_path = os.path.join(args.output_dir, "best_model.pth")
|
| 664 |
+
|
| 665 |
+
# Training
|
| 666 |
+
print(f"\nStarting training for {args.num_epochs} epochs...")
|
| 667 |
+
best_val_cer = float("inf")
|
| 668 |
+
|
| 669 |
+
for epoch in range(args.num_epochs):
|
| 670 |
+
current_epoch = epoch
|
| 671 |
+
start = time.time()
|
| 672 |
+
|
| 673 |
+
train_loss = train_epoch(model, train_loader, optimizer, criterion, device, onecycle, PAD_token)
|
| 674 |
+
val_loss = evaluate_model(model, val_loader, criterion, device, PAD_token)
|
| 675 |
+
val_cer, _, _ = evaluate_cer(model, val_loader, device, idx_to_char,
|
| 676 |
+
PAD_token, SOS_token, EOS_token)
|
| 677 |
+
|
| 678 |
+
# Overfitting detection
|
| 679 |
+
training_loss_history.append(train_loss)
|
| 680 |
+
validation_loss_history.append(val_loss)
|
| 681 |
+
if len(training_loss_history) >= 3:
|
| 682 |
+
overfitting_detected = (np.mean(validation_loss_history[-3:]) >
|
| 683 |
+
np.mean(training_loss_history[-3:]) * 1.2)
|
| 684 |
+
|
| 685 |
+
plateau.step(val_cer)
|
| 686 |
+
mins, secs = divmod(time.time() - start, 60)
|
| 687 |
+
|
| 688 |
+
print(f"\nEpoch {epoch + 1}/{args.num_epochs} ({mins:.0f}m {secs:.0f}s)")
|
| 689 |
+
print(f" Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f} | Val CER: {val_cer:.4f}")
|
| 690 |
+
|
| 691 |
+
if val_cer < best_val_cer:
|
| 692 |
+
best_val_cer = val_cer
|
| 693 |
+
|
| 694 |
+
early_stopping(val_cer, model, epoch, best_model_path)
|
| 695 |
+
if early_stopping.early_stop:
|
| 696 |
+
break
|
| 697 |
+
|
| 698 |
+
# Final evaluation
|
| 699 |
+
print(f"\nBest validation CER: {best_val_cer:.4f}")
|
| 700 |
+
print("Loading best model for test evaluation...")
|
| 701 |
+
checkpoint = torch.load(best_model_path)
|
| 702 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 703 |
+
|
| 704 |
+
test_cer, test_preds, test_targets = evaluate_cer(
|
| 705 |
+
model, test_loader, device, idx_to_char, PAD_token, SOS_token, EOS_token)
|
| 706 |
+
test_wer = calculate_wer(test_preds, test_targets)
|
| 707 |
+
|
| 708 |
+
print(f"\nTest CER: {test_cer:.4f}")
|
| 709 |
+
print(f"Test WER: {test_wer:.4f}")
|
| 710 |
+
print(f"Test CRR: {(1 - test_cer) * 100:.2f}%")
|
| 711 |
+
|
| 712 |
+
for i in range(min(5, len(test_preds))):
|
| 713 |
+
print(f"\nSample {i + 1}:")
|
| 714 |
+
print(f" Predicted: {test_preds[i]}")
|
| 715 |
+
print(f" Actual: {test_targets[i]}")
|
| 716 |
+
|
| 717 |
+
if __name__ == "__main__":
|
| 718 |
+
main()
|