Run this model with HF Jobs
Run Wall3/Yara_Captcha_Solver on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Wall3/Yara_Captcha_Solver. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Wall3/Yara_Captcha_Solver on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Wall3/Yara_Captcha_Solver with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Keras
How to use Wall3/Yara_Captcha_Solver with Keras:
# !pip install -U keras tensorflow huggingface_hub # Keras needs TensorFlow installed to read "hf://" paths, so the tensorflow backend is selected here; # "jax" and "torch" also work for computation once TensorFlow is installed. import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras model = keras.saving.load_model("hf://Wall3/Yara_Captcha_Solver") - Notebooks
- Google Colab
- Kaggle
Upload 5 files
Browse filesFiles changed (6)
- .gitattributes+1
- README.md+237
- dataset.pyAdded+339
- model.pyAdded+290
- preview_all_types.pngAdded
- weekend_best.weights.h5Added+3
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textpreview_all_types.png filter=lfs diff=lfs merge=lfs -text
123---license: mit---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240---license: mitlanguage:- entags:- captcha- ocr- crnn- ctc- image-to-text- tensorflow- kerastask_categories:- image-to-textdatasets:- ayoubkirouane/captcha- ThangaTharun/captchaimages- yuxi5/text-captcha-data-clean- AvinashRicky/CaptchaOCR-500K- cybertruck32489/captcha_90k- yusuf802/captcha_dataset- lumasik/captcha-25k---# π CRNN-CTC Captcha Solver### Convolutional Recurrent Neural Network Β· Real-Data Fine-Tuned[](https://opensource.org/licenses/MIT)[](https://www.python.org/)[](https://www.tensorflow.org/)Alphanumeric CAPTCHA recognition using a deep **CRNN + CTC** architecture trained on**275,000 real-world labeled CAPTCHAs** from 7 HuggingFace datasets, then refined over afull weekend of augmented training on an NVIDIA A100. Achieves **90.08% whole-CAPTCHAsequence accuracy** on the held-out real test set.---## π Model Details| Property | Value ||---|---|| **Task** | Alphanumeric CAPTCHA Recognition (OCR) || **Architecture** | CRNN β 6-block CNN + 2Γ Bidirectional LSTM + Dense || **Input** | RGB image `(64 Γ 200 Γ 3)`, float32 `[0, 1]` || **Output** | Character sequence, length 1β8 || **Vocabulary** | `0-9`, `a-z`, `A-Z` β 62 characters + CTC blank || **Loss** | Connectionist Temporal Classification (CTC) || **Parameters** | 10,049,535 (~38.3 MB) || **Framework** | TensorFlow 2.21 / Keras 3 || **Training hardware** | NVIDIA A100 80 GB |---## π Performance### Overall (held-out real test set, n = 5,502)| Metric | Score ||---|---|| **Sequence accuracy** (whole CAPTCHA correct) | **90.08 %** || **Character accuracy** | **96.14 %** || CTC loss | 1.10 |### Per-dataset breakdown| Dataset | n (test) | Char acc | Seq acc ||---|---|---|---|| cybertruck32489/captcha_90k | 1,224 | 99.9 % | **99.7 %** || ayoubkirouane/captcha | 192 | 99.9 % | **99.5 %** || yuxi5/text-captcha-data-clean | 1,171 | 93.6 % | 90.9 % || AvinashRicky/CaptchaOCR-500K | 1,215 | 97.8 % | 88.7 % || lumasik/captcha-25k | 502 | 96.0 % | 86.5 % || yusuf802/captcha_dataset | 1,196 | 92.5 % | 80.8 % || ThangaTharun/captchaimages | 2 | 100.0 % | 100.0 % |**Total params: 10,049,535 β Model size: 38.3 MB**---## π¦ Training Datasets| Dataset | Label field | Images used | Notes ||---|---|---|---|| [ayoubkirouane/captcha](https://huggingface.co/datasets/ayoubkirouane/captcha) | `solution` | 10,000 | clean, parquet || [ThangaTharun/captchaimages](https://huggingface.co/datasets/ThangaTharun/captchaimages) | `output` | 100 | small, noisy || [yuxi5/text-captcha-data-clean](https://huggingface.co/datasets/yuxi5/text-captcha-data-clean) | `label` | 60,000 | capped at 60k || [AvinashRicky/CaptchaOCR-500K](https://huggingface.co/datasets/AvinashRicky/CaptchaOCR-500K) | `text` | 60,000 | capped at 60k || [cybertruck32489/captcha_90k](https://huggingface.co/datasets/cybertruck32489/captcha_90k) | `solve` | 60,000 | capped at 60k || [yusuf802/captcha_dataset](https://huggingface.co/datasets/yusuf802/captcha_dataset) | `label` | 60,000 | capped at 60k || [lumasik/captcha-25k](https://huggingface.co/datasets/lumasik/captcha-25k) | `label` | 25,000 | all images used || **Synthetic (17 generator types)** | generated | mixed in at 30% | custom Python generators |**Total real images preprocessed:** 275,100 β 264,096 train / 5,502 val / 5,502 testAll images were resized to **64 Γ 200** with aspect-preserving letterboxing (pad withmedian border color).---## βοΈ Training Details### Two-stage process**Stage 1 β Synthetic pre-training**Training from scratch on 17 procedural CAPTCHA types (custom Python generators) coveringdifferent fonts, noise levels, distortions, and color palettes.**Stage 2 β Real-data fine-tuning + augmented weekend run**- Initialized from the synthetic checkpoint.- Fine-tuned on 264k real images for 40 epochs (LR 1e-3 β 1e-5 cosine).- Extended with a full weekend run (386 epochs, ~60h on A100) combining:- **30% synthetic** mixed into each batch for robustness.- **GPU augmentation:** `RandomRotation(Β±2Β°)`, `RandomTranslation`, `RandomZoom(6%)`, `RandomContrast(25%)`, brightness jitter Β±0.08, Gaussian noise Ο=0.03.- **Weak-source oversampling:** datasets below 90% test seq were oversampled up to Γ2 proportionally.### Hyperparameters| Parameter | Value ||---|---|| Optimizer | Adam || Peak LR | 5 Γ 10β»β΄ || Min LR | 1 Γ 10β»βΆ || LR schedule | Warmup + Cosine Decay || Batch size | 128 || Dropout | 0.25 || Gradient clip norm | 5.0 || Max sequence length | 8 characters |---## π Usage### Install dependencies```bashpip install tensorflow pillow numpy```### Predict from an image```pythonimport numpy as npfrom PIL import Imageimport tensorflow as tf# ββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββCHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"IDX_TO_CHAR = {i: c for i, c in enumerate(CHARS)}BLANK_IDX = 62IMG_H, IMG_W = 64, 200def preprocess(pil_img: Image.Image) -> np.ndarray:"""Aspect-preserving resize to 64Γ200, pad with median border color."""img = pil_img.convert("RGB")w, h = img.sizenew_w = int(round(w * IMG_H / h))img = img.resize((new_w, IMG_H), Image.LANCZOS)if new_w >= IMG_W:img = img.resize((IMG_W, IMG_H), Image.LANCZOS)return np.array(img, dtype=np.float32) / 255.0canvas = np.array(img, dtype=np.float32)border_color = np.median(np.concatenate([canvas[0], canvas[-1],canvas[:, 0], canvas[:, -1]], axis=0), axis=0)pad_l = (IMG_W - new_w) // 2result = np.full((IMG_H, IMG_W, 3), border_color, dtype=np.float32)result[:, pad_l:pad_l + new_w] = canvasreturn result / 255.0def decode_ctc(logits: np.ndarray) -> str:"""Greedy CTC decode β collapse repeats, remove blanks."""indices = np.argmax(logits, axis=-1) # (T,)chars, prev = [], -1for idx in indices:if idx != prev and idx != BLANK_IDX:chars.append(IDX_TO_CHAR.get(int(idx), ""))prev = idxreturn "".join(chars)# ββ load model βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Clone the repo or download the weights file, then:from model import build_crnn_model # from this repositorymodel = build_crnn_model()model.load_weights("weekend_best.weights.h5")# ββ run inference βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββimg = Image.open("captcha.png")tensor = preprocess(img)[np.newaxis] # (1, 64, 200, 3)logits = model(tensor, training=False).numpy() # (1, 50, 63)print("Prediction:", decode_ctc(logits[0]))```### Batch inference```pythonimages = [preprocess(Image.open(p)) for p in image_paths]batch = np.stack(images) # (N, 64, 200, 3)logits = model(batch, training=False).numpy() # (N, 50, 63)preds = [decode_ctc(l) for l in logits]```---## πΌοΈ PreprocessingInput images go through **aspect-preserving letterboxing**:1. Resize height to 64 px, keeping aspect ratio.2. If the resulting width β₯ 200 px, squeeze to 200 px.3. Otherwise, pad left and right with the **median border color** of the image to reach 200 px.4. Normalize to `float32 [0, 1]`.This ensures the character shapes are never stretched, which is critical fordistinguishing similar characters (e.g. `O` / `0`, `l` / `1`).---## βοΈ LicenseThis model is released under the **MIT License**. You are free to use, copy, modify,and distribute it for any purpose, including commercial use, with attribution.---## π CitationIf you use this model in your work, please cite:```CRNN-CTC Captcha Solver (2026)Trained on 275k real-world CAPTCHAs from 7 HuggingFace datasets.Architecture: 6-block CNN + 2Γ BiLSTM + CTC, 10M parameters, 38 MB.Sequence accuracy: 90.08% on held-out real test set.License: MIT```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339"""dataset.py~~~~~~~~~~Infinite on-the-fly TensorFlow dataset pipeline for CAPTCHA training.No images are ever saved to disk β every sample is generated fresh each epoch.
Image size: 200 Γ 64 px (width Γ height) Why 200 wide? CTC needs time_steps >= 2 * max_label_len - 1. After 2Γ stride-2 pooling on the width axis: 200 / 4 = 50 time steps. For a 7-char label that's 50 vs the minimum 13 β comfortable margin. 128px would give only 32 steps (still valid but tight for longer labels).
Character set: 62 chars (digits + lowercase + uppercase) Indices 0-61 β '0'-'9', 'a'-'z', 'A'-'Z' Index 62 β CTC blank token
Usage: from dataset import make_dataset, make_combined_dataset, CHARS, NUM_CLASSES
# One dataset per type (17 separate, fully on-the-fly) ds_type1 = make_dataset(captcha_type=1, batch_size=32) for images, labels, label_lengths in ds_type1.take(10): ... # images: (B, 64, 200, 3) float32 labels: (B, pad) int32
# All 17 types mixed together ds_all = make_combined_dataset(batch_size=32)
# Keras model.fit() helper (returns dict y) ds_keras = make_dataset(1, batch_size=32, keras_format=True) model.fit(ds_keras, steps_per_epoch=500, epochs=50)"""
from __future__ import annotations
import numpy as npimport tensorflow as tffrom PIL import Image as PILImage
from captcha_generators import generate, generate_random, TYPES
# ββ Character set βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"CHAR_TO_IDX = {c: i for i, c in enumerate(CHARS)}IDX_TO_CHAR = {i: c for i, c in enumerate(CHARS)}BLANK_IDX = len(CHARS) # 62NUM_CLASSES = len(CHARS) + 1 # 63 (62 chars + 1 blank)MAX_LABEL_LEN = 8 # max chars any generator produces
# ββ Image dimensions ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
IMG_W = 200 # width β determines CTC time steps after CNNIMG_H = 64 # heightIMG_C = 3 # RGB channels
# ββ Encoding helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def encode_label(text: str) -> np.ndarray: """ Map each character in *text* to its integer index. Unknown characters are silently skipped. Returns a 1-D int32 numpy array. """ return np.array([CHAR_TO_IDX[c] for c in text if c in CHAR_TO_IDX], dtype=np.int32)
def decode_label(indices) -> str: """ Map a sequence of integer indices back to a string. CTC blank tokens (index 62) and padding (-1) are stripped. """ return "".join( IDX_TO_CHAR[int(i)] for i in indices if int(i) not in (-1, BLANK_IDX) )
def preprocess_image(pil_img) -> np.ndarray: """ Resize a PIL image to (IMG_H, IMG_W) **preserving aspect ratio** and pad the remaining width with the estimated background colour. Returns a float32 array in [0, 1] of shape (IMG_H, IMG_W, IMG_C).
Real CAPTCHAs vary widely in aspect ratio (100Γ40 β¦ 280Γ54). Stretching them all to a fixed box distorts the glyphs; instead we scale to the target height, fit the width, and pad so characters keep their natural shape. """ pil_img = pil_img.convert("RGB") w, h = pil_img.size
# Scale so height == IMG_H, keep aspect ratio new_w = max(1, int(round(w * (IMG_H / h)))) pil_img = pil_img.resize((new_w, IMG_H), PILImage.LANCZOS) arr = np.array(pil_img, dtype=np.float32) / 255.0 # (IMG_H, new_w, 3)
if new_w == IMG_W: return arr if new_w > IMG_W: # Too wide after height-scaling: squeeze width to fit (rare) pil_img = pil_img.resize((IMG_W, IMG_H), PILImage.LANCZOS) return np.array(pil_img, dtype=np.float32) / 255.0
# Pad width to IMG_W, centered, using the median border colour as background border = np.concatenate([arr[0, :, :], arr[-1, :, :], arr[:, 0, :], arr[:, -1, :]], axis=0) bg = np.median(border, axis=0) # (3,) canvas = np.ones((IMG_H, IMG_W, IMG_C), dtype=np.float32) * bg left = (IMG_W - new_w) // 2 canvas[:, left:left + new_w, :] = arr return canvas
# ββ Core Python generators ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _single_type_generator(captcha_type: int): """ Infinite Python generator for one CAPTCHA type. Yields (image_array, label_indices, label_length) tuples. """ while True: pil_img, label = generate(captcha_type) image = preprocess_image(pil_img) indices = encode_label(label) yield image, indices, np.int32(len(indices))
def _combined_generator(): """ Infinite Python generator that cycles through all 17 types randomly. Yields (image_array, label_indices, label_length, type_id) tuples. """ import random while True: pil_img, label, t = generate_random() image = preprocess_image(pil_img) indices = encode_label(label) yield image, indices, np.int32(len(indices)), np.int32(t)
# ββ tf.data.Dataset factories βββββββββββββββββββββββββββββββββββββββββββββββββ
def make_dataset( captcha_type: int, batch_size: int = 32, shuffle_buffer: int = 256, prefetch: int = tf.data.AUTOTUNE, keras_format: bool = False,) -> tf.data.Dataset: """ Build an infinite on-the-fly tf.data.Dataset for a single CAPTCHA type.
Args: captcha_type: Integer 1-17. batch_size: Samples per batch. shuffle_buffer: Size of the shuffle buffer (0 = no shuffle). prefetch: Number of batches to prefetch (AUTOTUNE recommended). keras_format: If True, each batch is (images, y_dict) where y_dict = {'labels': ..., 'label_lengths': ...}. Use this with model.fit().
Returns: Batched tf.data.Dataset. Each batch (keras_format=False): images : (B, 64, 200, 3) float32 labels : (B, pad_len) int32 (padded with -1) label_lengths : (B,) int32 """ if captcha_type not in TYPES: raise ValueError(f"captcha_type must be 1-17, got {captcha_type!r}")
output_sig = ( tf.TensorSpec(shape=(IMG_H, IMG_W, IMG_C), dtype=tf.float32), tf.TensorSpec(shape=(None,), dtype=tf.int32), tf.TensorSpec(shape=(), dtype=tf.int32), )
ds = tf.data.Dataset.from_generator( lambda: _single_type_generator(captcha_type), output_signature=output_sig, )
if shuffle_buffer > 0: ds = ds.shuffle(buffer_size=shuffle_buffer, reshuffle_each_iteration=True)
ds = ds.padded_batch( batch_size, padded_shapes=((IMG_H, IMG_W, IMG_C), (None,), ()), padding_values=( tf.constant(0.0, tf.float32), tf.constant(-1, tf.int32), # -1 = padding sentinel for labels tf.constant(0, tf.int32), ), drop_remainder=False, )
if keras_format: ds = ds.map( lambda imgs, lbl, llen: ( imgs, {"labels": lbl, "label_lengths": llen}, ), num_parallel_calls=tf.data.AUTOTUNE, )
return ds.prefetch(prefetch)
def make_combined_dataset( batch_size: int = 32, shuffle_buffer: int = 256, prefetch: int = tf.data.AUTOTUNE, include_type_id: bool = False, keras_format: bool = False,) -> tf.data.Dataset: """ Build an infinite dataset that mixes all 17 CAPTCHA types randomly.
Args: include_type_id: If True, each batch includes the captcha_type integer (useful for multi-task learning or analysis). keras_format: Same as make_dataset().
Returns: Batched tf.data.Dataset. Each batch (include_type_id=False, keras_format=False): images : (B, 64, 200, 3) float32 labels : (B, pad_len) int32 label_lengths : (B,) int32 """ output_sig = ( tf.TensorSpec(shape=(IMG_H, IMG_W, IMG_C), dtype=tf.float32), tf.TensorSpec(shape=(None,), dtype=tf.int32), tf.TensorSpec(shape=(), dtype=tf.int32), tf.TensorSpec(shape=(), dtype=tf.int32), # type_id )
ds = tf.data.Dataset.from_generator( _combined_generator, output_signature=output_sig, )
if shuffle_buffer > 0: ds = ds.shuffle(buffer_size=shuffle_buffer, reshuffle_each_iteration=True)
if include_type_id: ds = ds.padded_batch( batch_size, padded_shapes=((IMG_H, IMG_W, IMG_C), (None,), (), ()), padding_values=( tf.constant(0.0, tf.float32), tf.constant(-1, tf.int32), tf.constant(0, tf.int32), tf.constant(0, tf.int32), ), drop_remainder=False, ) else: # Drop the type_id column for simplicity ds = ds.map(lambda img, lbl, llen, _t: (img, lbl, llen), num_parallel_calls=tf.data.AUTOTUNE) ds = ds.padded_batch( batch_size, padded_shapes=((IMG_H, IMG_W, IMG_C), (None,), ()), padding_values=( tf.constant(0.0, tf.float32), tf.constant(-1, tf.int32), tf.constant(0, tf.int32), ), drop_remainder=False, )
if keras_format: ds = ds.map( lambda imgs, lbl, llen: ( imgs, {"labels": lbl, "label_lengths": llen}, ), num_parallel_calls=tf.data.AUTOTUNE, )
return ds.prefetch(prefetch)
def make_all_datasets( batch_size: int = 32, shuffle_buffer: int = 256, keras_format: bool = False,) -> dict[int, tf.data.Dataset]: """ Convenience function β returns a dict of 17 separate tf.data.Datasets, one per CAPTCHA type.
Returns: {1: ds_type1, 2: ds_type2, ..., 17: ds_type17} """ return { t: make_dataset(t, batch_size=batch_size, shuffle_buffer=shuffle_buffer, keras_format=keras_format) for t in TYPES }
# ββ Quick sanity check ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def verify_pipeline(captcha_type: int = 1, n_batches: int = 3, batch_size: int = 4) -> None: """ Print shape and label info for a few batches. Use to confirm the pipeline is working before kicking off a full training run.
Example: from dataset import verify_pipeline verify_pipeline(captcha_type=3) """ print(f"\nββ Verifying pipeline for type {captcha_type} ββ") print(f" IMG_W={IMG_W} IMG_H={IMG_H} NUM_CLASSES={NUM_CLASSES} BLANK={BLANK_IDX}\n")
ds = make_dataset(captcha_type, batch_size=batch_size, shuffle_buffer=16) for batch_idx, (images, labels, lengths) in enumerate(ds.take(n_batches)): print(f" Batch {batch_idx + 1}:") print(f" images shape : {images.shape} dtype={images.dtype}" f" min={images.numpy().min():.3f} max={images.numpy().max():.3f}") print(f" labels shape : {labels.shape} dtype={labels.dtype}") print(f" label_lengths : {lengths.numpy().tolist()}") for i in range(len(lengths)): raw = labels[i].numpy() length = int(lengths[i]) text = decode_label(raw[:length]) print(f" sample {i}: encoded={raw[:length].tolist()} decoded='{text}'") print()
if __name__ == "__main__": for t in TYPES: verify_pipeline(captcha_type=t, n_batches=1, batch_size=2)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""model.py~~~~~~~~CRNN (Convolutional Recurrent Neural Network) for CAPTCHA text recognition.
Architecture β Shi et al. 2016, "An End-to-End Trainable Neural Networkfor Image-based Sequence Recognition" (modernised with BatchNorm + Dropout):
Input (B, H=64, W=200, C=3) ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ CNN 6 conv blocks β (B, 1, 50, 512) Reshape squeeze height β (B, T=50, 512) BiLSTMΓ2 bidirectional context β (B, T=50, 512) Dense per-step projection β (B, T=50, 63) β logits ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ CTC loss (training) tf.nn.ctc_loss CTC decode(inference) greedy or beam search
Why CRNN + CTC? β’ CNN β learns local visual features (stroke curves, serifs, noise patterns) β’ Width axis maps naturally to the time axis CTC needs β’ BiLSTM β captures left β right context across characters β’ CTC β no need to pre-segment characters; handles variable-length text
CNN width reduction detail: Blocks 1-2: MaxPool(2Γ2) β width halved twice: 200 β 100 β 50 Blocks 3-6: MaxPool(2Γ1) β width unchanged at 50, height halved to 1 After CNN: T = 50 time steps (β₯ 2Γmax_label_len β 1 = 15, safe margin)"""
from __future__ import annotations
import kerasimport tensorflow as tfimport numpy as np
from dataset import NUM_CLASSES, BLANK_IDX, IMG_H, IMG_W, IMG_C, decode_label
# ββ CNN building block ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _conv_block( x: keras.KerasTensor, filters: int, pool: tuple[int, int], double_conv: bool = False, name: str = "",) -> keras.KerasTensor: """Conv β BN β ReLU (optionally repeated) β MaxPool.""" x = keras.layers.Conv2D( filters, (3, 3), padding="same", use_bias=False, name=f"{name}_conv1" )(x) x = keras.layers.BatchNormalization(name=f"{name}_bn1")(x) x = keras.layers.Activation("relu", name=f"{name}_relu1")(x)
if double_conv: x = keras.layers.Conv2D( filters, (3, 3), padding="same", use_bias=False, name=f"{name}_conv2" )(x) x = keras.layers.BatchNormalization(name=f"{name}_bn2")(x) x = keras.layers.Activation("relu", name=f"{name}_relu2")(x)
x = keras.layers.MaxPooling2D(pool_size=pool, strides=pool, name=f"{name}_pool")(x) return x
# ββ Model builder βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def build_crnn_model( img_h: int = IMG_H, img_w: int = IMG_W, img_c: int = IMG_C, num_classes: int = NUM_CLASSES, rnn_units: int = 256, num_rnn_layers: int = 2, rnn_type: str = "lstm", # 'lstm' or 'gru' dropout: float = 0.25,) -> keras.Model: """ Build and return the CRNN model.
Args: img_h, img_w, img_c : Input image dimensions (height, width, channels). num_classes : Total classes including CTC blank (63). rnn_units : Hidden units per direction in each BiRNN layer. num_rnn_layers : Number of stacked BiRNN layers (1 or 2). rnn_type : 'lstm' (default, slightly better) or 'gru' (faster). dropout : Dropout rate applied after each RNN layer.
Returns: keras.Model inputs=(B, H, W, C) outputs=(B, T, num_classes) The output is RAW LOGITS β no softmax, no activation. Pass directly to ctc_loss() during training. Pass through tf.nn.softmax then ctc_decode() during inference. """ inputs = keras.Input(shape=(img_h, img_w, img_c), name="image")
# ββ CNN backbone βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ # Block 1: H 64β32, W 200β100, channels 3β64 x = _conv_block(inputs, 64, pool=(2, 2), name="block1") # Block 2: H 32β16, W 100β50, channels 64β128 x = _conv_block(x, 128, pool=(2, 2), name="block2") # Block 3: H 16β8, W 50 (unchanged), double conv, channels 128β256 x = _conv_block(x, 256, pool=(2, 1), double_conv=True, name="block3") # Block 4: H 8β4, W 50 (unchanged), channels 256β512 x = _conv_block(x, 512, pool=(2, 1), name="block4") # Block 5: H 4β2, W 50 (unchanged), channels 512β512 x = _conv_block(x, 512, pool=(2, 1), name="block5") # Block 6: H 2β1, W 50 (unchanged), channels 512β512 x = _conv_block(x, 512, pool=(2, 1), name="block6") # x shape: (B, 1, 50, 512)
# ββ Height squeeze β sequence ββββββββββββββββββββββββββββββββββββββββββββββ # Remove the height=1 axis β (B, 50, 512) x = keras.layers.Lambda(lambda t: tf.squeeze(t, axis=1), name="squeeze")(x)
# ββ Bidirectional RNN ββββββββββββββββββββββββββββββββββββββββββββββββββββββ RNNCell = keras.layers.LSTM if rnn_type.lower() == "lstm" else keras.layers.GRU
for i in range(num_rnn_layers): return_seq = True # always True β we need per-timestep output x = keras.layers.Bidirectional( RNNCell(rnn_units, return_sequences=return_seq, dropout=dropout, name=f"rnn{i + 1}"), merge_mode="concat", name=f"birnn{i + 1}", )(x) # x shape: (B, 50, rnn_units*2)
# ββ Output projection ββββββββββββββββββββββββββββββββββββββββββββββββββββββ # Raw logits β shape (B, T=50, num_classes=63) # DO NOT apply softmax here; tf.nn.ctc_loss expects unnormalised log-probs. logits = keras.layers.Dense(num_classes, name="logits")(x)
model = keras.Model(inputs=inputs, outputs=logits, name="CRNN_CTC") return model
# ββ CTC loss ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def ctc_loss( logits: tf.Tensor, labels: tf.Tensor, label_lengths: tf.Tensor, logit_lengths: tf.Tensor | None = None,) -> tf.Tensor: """ Compute mean CTC loss over a batch.
Args: logits : (B, T, C) raw logits from the model. labels : (B, pad_len) int32 padded label indices (-1 = padding). label_lengths : (B,) int32 true length of each label sequence. logit_lengths : (B,) int32 length of each logit sequence. Defaults to T (full width) for every sample.
Returns: Scalar tensor β mean CTC loss over the batch. """ batch_size = tf.shape(logits)[0] time_steps = tf.shape(logits)[1]
if logit_lengths is None: logit_lengths = tf.fill([batch_size], time_steps)
# tf.nn.ctc_loss expects labels without padding tokens. # We pass the dense padded tensor + label_lengths; TF handles the masking. loss = tf.nn.ctc_loss( labels=tf.cast(labels, tf.int32), logits=logits, label_length=tf.cast(label_lengths, tf.int32), logit_length=tf.cast(logit_lengths, tf.int32), logits_time_major=False, # logits is (B, T, C) blank_index=BLANK_IDX, # 62 = last class ) return tf.reduce_mean(loss)
# ββ CTC decode ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def ctc_decode( logits: tf.Tensor, logit_lengths: tf.Tensor | None = None, method: str = "greedy", beam_width: int = 5,) -> list[str]: """ Decode model logits into text strings.
Args: logits : (B, T, C) raw logits (no softmax needed β applied here). logit_lengths : (B,) int32. Defaults to T for all samples. method : 'greedy' (fast) or 'beam' (slightly more accurate). beam_width : Beam width when method='beam'.
Returns: List of decoded text strings, length = B. """ batch_size = tf.shape(logits)[0] time_steps = tf.shape(logits)[1]
if logit_lengths is None: logit_lengths = tf.fill([batch_size], time_steps)
# Apply softmax and convert to log-probs for the CTC decoder log_probs = tf.nn.log_softmax(logits, axis=-1)
# TF CTC decoders expect (T, B, C) β time-major log_probs_tm = tf.transpose(log_probs, perm=[1, 0, 2])
seq_len = tf.cast(logit_lengths, tf.int32)
if method == "beam": decoded, _ = tf.nn.ctc_beam_search_decoder( log_probs_tm, sequence_length=seq_len, beam_width=beam_width, top_paths=1, ) sparse = decoded[0] else: decoded, _ = tf.nn.ctc_greedy_decoder( log_probs_tm, sequence_length=seq_len, merge_repeated=True, ) sparse = decoded[0]
# Convert SparseTensor to dense padded with -1 dense = tf.sparse.to_dense(sparse, default_value=-1).numpy()
return [decode_label(row) for row in dense]
# ββ Accuracy metrics ββββββββββββββοΏ½οΏ½οΏ½βββββββββββββββββββββββββββββββββββββββββββ
def character_accuracy(preds: list[str], targets: list[str]) -> float: """ Character-level accuracy: fraction of correctly predicted characters across all samples (aligned by position, length-padded). """ total = correct = 0 for pred, tgt in zip(preds, targets): for p, t in zip(pred.ljust(len(tgt)), tgt): total += 1 if p == t: correct += 1 return correct / total if total else 0.0
def sequence_accuracy(preds: list[str], targets: list[str]) -> float: """ Sequence-level accuracy: fraction of samples where the entire predicted string exactly matches the ground truth. """ if not preds: return 0.0 return sum(p == t for p, t in zip(preds, targets)) / len(preds)
# ββ Summary βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def model_summary(model: keras.Model) -> None: """Print a clean model summary with parameter count.""" model.summary(line_length=80) total = model.count_params() trainable = sum( int(tf.reduce_prod(v.shape)) for v in model.trainable_variables ) print(f"\n Total params : {total:,}") print(f" Trainable params : {trainable:,}") print(f" Input shape : {model.input_shape}") print(f" Output shape : {model.output_shape} (B, T, num_classes)") print(f" T (time steps) : {model.output_shape[1]}") print(f" num_classes : {model.output_shape[2]} " f"(chars 0-{NUM_CLASSES-2} + blank={BLANK_IDX})\n")
# ββ Quick build test ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if __name__ == "__main__": print("Building CRNN model...") m = build_crnn_model() model_summary(m)
# Forward pass smoke test dummy = tf.zeros((2, IMG_H, IMG_W, IMG_C)) out = m(dummy, training=False) print(f"Smoke test β input {dummy.shape} β output {out.shape}") assert out.shape == (2, 50, NUM_CLASSES), f"Unexpected output shape: {out.shape}" print("All checks passed.")123version https://git-lfs.github.com/spec/v1oid sha256:fcc00334e74b4b1ae5ad2b3bc0b29283056149e743cae8f7d528cc60e9d31f34size 40301680.gitattributes+1
README.md+237
dataset.pyAdded+339
model.pyAdded+290
preview_all_types.pngAdded

Large File Pointer Details
- SHA256: 2c2c231ee6eea1ca89b9a7d5fbcb3b5840357d627e310841c831805e07e43887
- Pointer size: 131 Bytes
- Size of remote file: 141 kB
weekend_best.weights.h5Added+3