Views
No views yet
pip install torch torchvision pillow numpy huggingface_hub1import torch
2import torch.nn as nn
3import numpy as np
4from PIL import Image
5from huggingface_hub import hf_hub_download
6
7# Download model checkpoint
8ckpt_path = hf_hub_download(repo_id="IsmatS/handwriting-recognition-iam", filename="best_model.pth")
9checkpoint = torch.load(ckpt_path, map_location="cpu")
10
11# Character mapper from checkpoint
12char_mapper = checkpoint['char_mapper']
13
14def preprocess_image(image_path, target_height=64, target_width=256):
15 img = Image.open(image_path).convert('L') # grayscale
16 img = img.resize((target_width, target_height), Image.LANCZOS)
17 img = np.array(img, dtype=np.float32) / 255.0
18 img = (img - 0.5) / 0.5 # normalize to [-1, 1]
19 return torch.FloatTensor(img).unsqueeze(0).unsqueeze(0) # (1, 1, H, W)
20
21def ctc_decode(predictions, char_mapper):
22 """Greedy CTC decoding."""
23 pred_indices = predictions.argmax(dim=2).squeeze(1).tolist()
24 decoded = []
25 prev = None
26 for idx in pred_indices:
27 if idx != prev and idx != 0: # 0 = blank token
28 decoded.append(char_mapper.idx_to_char[idx])
29 prev = idx
30 return ''.join(decoded)
31
32# Note: CRNN class must match the training definition in train_colab.ipynb
33# See train_colab.ipynb for the full model class
34# model = CRNN(num_chars=len(char_mapper.chars))
35# model.load_state_dict(checkpoint['model_state_dict'])
36# model.eval()
37#
38# img_tensor = preprocess_image("handwriting_sample.png")
39# with torch.no_grad():
40# output = model(img_tensor) # (T, 1, num_chars)
41# text = ctc_decode(output, char_mapper)
42# print("Recognized:", text)Note: The trained model weights (best_model.pth) are generated during training. Runtrain_colab.ipynbon Google Colab to produce the checkpoint, then use the code above for inference.
charts/ folderjupyter notebook analysis.ipynbtrain_colab.ipynb to Google Colabanalysis.ipynb:charts/01_sample_images.png - 10 sample handwritten textscharts/02_text_length_distribution.png - Text statisticscharts/03_image_dimensions.png - Image analysischarts/04_character_frequency.png - Character distributioncharts/05_summary_statistics.png - Summary tablebest_model.pth - Trained model weightstraining_history.png - Loss/CER/WER plotspredictions.png - Sample predictionstorch>=2.0.0
datasets>=2.14.0
pillow>=9.5.0
numpy>=1.24.0
matplotlib>=3.7.0
seaborn>=0.13.0
jupyter>=1.0.0
jiwer>=3.0.01import torch
2
3# Load checkpoint
4checkpoint = torch.load('best_model.pth')
5char_mapper = checkpoint['char_mapper']
6
7# Create model
8from train_colab import CRNN # Copy model class
9model = CRNN(num_chars=len(char_mapper.chars))
10model.load_state_dict(checkpoint['model_state_dict'])
11model.eval()
12
13# Predict
14# ... (preprocessing + inference)