Spaces:
Running on Zero
Running on Zero
Download predict.py from MarcoPerson/ssm-ocr-benchmark: direct link, hf CLI and curl.
- Browser
- Download file 6 kB
-
https://huggingface.co/spaces/MarcoPerson/ssm-ocr-benchmark/resolve/main/predict.py
- Command line
-
hf download hf://spaces/MarcoPerson/ssm-ocr-benchmark/predict.py
-
curl -L -o predict.py https://huggingface.co/spaces/MarcoPerson/ssm-ocr-benchmark/resolve/main/predict.py
6 kB
| #!/usr/bin/env python | |
| # SPDX-License-Identifier: Apache-2.0 | |
| """ | |
| Transcribe text-line images with a Mamba-CTC or Mamba-NAR checkpoint. | |
| python predict.py --model ctc --script antiqua --checkpoint checkpoints/mamba_ctc_antiqua/best.pt line1.png line2.png | |
| As a library: | |
| from predict import load_recognizer | |
| recognizer = load_recognizer("nar", "fraktur", "checkpoints/mamba_nar_fraktur/best.pt") | |
| print(recognizer.transcribe(PIL.Image.open("line.png"))) | |
| The image is prepared exactly as at evaluation time (RGB, normalised with the mean and standard deviation of the training | |
| set stored in norm_stats.json, padded to the minimum size of the config). | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| from configs._utils import load_config # noqa: E402 | |
| from core.ocr_utils import LM_ind_to_str # noqa: E402 | |
| from main import build_params, get_parser # noqa: E402 | |
| MODELS = ("ctc", "nar") | |
| SCRIPTS = ("antiqua", "fraktur") | |
| ROOT = os.path.dirname(os.path.abspath(__file__)) | |
| def enable_cpu_mode(model_params): | |
| """ | |
| The Mamba CUDA kernels (selective scan, causal conv, fused layer norm) cannot run on a CPU. Without a GPU, use | |
| their reference implementations in plain PyTorch: same weights and same results, but slower. | |
| """ | |
| from mamba_ssm.modules import mamba_simple | |
| from mamba_ssm.ops.selective_scan_interface import selective_scan_ref | |
| mamba_simple.selective_scan_fn = selective_scan_ref | |
| mamba_simple.causal_conv1d_fn = None | |
| model_params["mamba_config"]["fused_add_norm"] = False | |
| class Recognizer: | |
| def __init__(self, model, encoder, decoder, charset, mean, std, padding, device): | |
| self.model, self.encoder, self.decoder, self.charset = model, encoder, decoder, charset | |
| self.mean, self.std, self.padding, self.device = mean, std, padding, device | |
| def prepare(self, image): | |
| """PIL image -> normalised, padded tensor (1, 3, H, W) and the width of the image in feature-map columns.""" | |
| array = np.array(image.convert("RGB"), dtype=np.float64) | |
| array = (array - self.mean) / self.std | |
| height, width, channels = array.shape | |
| pad_h = max(0, self.padding["min_height"] - height) | |
| pad_w = max(0, self.padding["min_width"] - width) | |
| padded = np.zeros((height + pad_h, width + pad_w, channels)) # padding value 0, bottom and right | |
| padded[:height, :width] = array | |
| tensor = torch.from_numpy(padded).float().permute(2, 0, 1).unsqueeze(0) | |
| return tensor.to(self.device), int(np.ceil(width / 8)) | |
| def transcribe(self, image): | |
| x, valid_columns = self.prepare(image) | |
| features = self.encoder(x) # (1, C, H, W) | |
| if self.model == "ctc": | |
| scores = self.decoder(features) # (1, V + 1, W) | |
| path = scores.argmax(dim=1)[0, :valid_columns].cpu().numpy() | |
| kept = [i for k, i in enumerate(path) if k == 0 or i != path[k - 1]] # collapse repeats | |
| text = LM_ind_to_str(self.charset, kept, oov_symbol="") # the blank is skipped | |
| return re.sub("( )+", " ", text).strip(" ") | |
| # nar: one prediction per slot, cut at the first end token | |
| pooled = features.max(dim=2)[0].permute(0, 2, 1) # (1, W, C) | |
| slots = self.decoder(pooled).argmax(dim=-1)[0].cpu().numpy() | |
| return LM_ind_to_str(self.charset, slots, oov_symbol="", stop_at_end=True) | |
| def load_recognizer(model, script, checkpoint, device=None): | |
| if model not in MODELS or script not in SCRIPTS: | |
| raise ValueError(f"model must be in {MODELS} and script in {SCRIPTS}") | |
| device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu")) | |
| config_path = os.path.join(ROOT, "configs", f"mamba_{model}_{script}.py") | |
| args = get_parser().parse_args(["--config", config_path, "--mode", "eval", "--checkpoint", checkpoint, "--cpu"]) | |
| params = build_params(load_config(config_path), args) | |
| model_params = params["model_params"] | |
| charset = list(params["dataset_params"]["charset"]) | |
| model_params.update({"vocab_size": len(charset), "device": device, "use_amp": False}) | |
| if device.type == "cpu": | |
| enable_cpu_mode(model_params) | |
| saved = torch.load(checkpoint, map_location="cpu", weights_only=False) | |
| if list(saved["charset"]) != charset: | |
| raise ValueError("the character set of the checkpoint differs from the one of the config") | |
| modules = {} | |
| for name, cls in model_params["models"].items(): | |
| modules[name] = cls(model_params) | |
| modules[name].load_state_dict(saved[f"{name}_state_dict"], strict=True) | |
| modules[name].to(device).eval() | |
| if device.type == "cpu": | |
| for module in modules[name].modules(): | |
| if hasattr(module, "use_fast_path"): # Mamba layers | |
| module.use_fast_path = False | |
| with open(os.path.join(ROOT, "norm_stats.json")) as f: | |
| stats = json.load(f)[script] | |
| padding = params["dataset_params"]["config"]["padding"] | |
| return Recognizer(model, modules["encoder"], modules["decoder"], charset, np.array(stats["mean"]), np.array(stats["std"]), padding, device) | |
| def main(): | |
| from PIL import Image | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("--model", required=True, choices=MODELS) | |
| parser.add_argument("--script", required=True, choices=SCRIPTS) | |
| parser.add_argument("--checkpoint", required=True) | |
| parser.add_argument("--device", default=None, help="cuda or cpu (default: cuda when available; cpu is slower)") | |
| parser.add_argument("images", nargs="+") | |
| args = parser.parse_args() | |
| recognizer = load_recognizer(args.model, args.script, args.checkpoint, args.device) | |
| for path in args.images: | |
| print(f"{path}\t{recognizer.transcribe(Image.open(path))}") | |
| if __name__ == "__main__": | |
| main() | |