Download inference.py from ArcaeaOffline/crnn-pytorch: direct link, hf CLI and curl.
- Browser
- Download file 1.66 kB
-
https://huggingface.co/ArcaeaOffline/crnn-pytorch/resolve/main/inference.py
- Command line
-
hf download hf://ArcaeaOffline/crnn-pytorch/inference.py
-
curl -L -o inference.py https://huggingface.co/ArcaeaOffline/crnn-pytorch/resolve/main/inference.py
1.66 kB
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| from PIL import Image | |
| from src.models import CRNN | |
| from src.utils.model_decoders import decode_padded_predictions, decode_predictions | |
| from src.utils.model_info import TrainingInfo | |
| training_info = TrainingInfo.from_dict( | |
| json.loads(Path("model_info.json").read_text(encoding="utf-8"))["training"] | |
| ) | |
| classes = training_info.labels | |
| def inference(image_path): | |
| # Hardcoded resize | |
| image = Image.open(image_path).convert("RGB") | |
| image = image.resize( | |
| (training_info.image_width, training_info.image_height), | |
| resample=Image.Resampling.BILINEAR, | |
| ) | |
| image = np.array(image) | |
| print(image.shape) | |
| image = np.transpose(image, (2, 0, 1)).astype(np.float32) | |
| image = image[None, ...] | |
| image = torch.from_numpy(image) | |
| if str(device) == "cuda": | |
| image = image.cuda() | |
| image = image.float() | |
| with torch.no_grad(): | |
| preds, _ = model(image) | |
| if model.use_ctc: | |
| answer = decode_predictions(preds, classes, training_info.blank_token) | |
| else: | |
| answer = decode_padded_predictions(preds, classes, training_info.pad_token) | |
| return answer | |
| if __name__ == "__main__": | |
| device = torch.device("cpu") | |
| # Setup model and load weights | |
| model = CRNN( | |
| dims=256, | |
| num_chars=len(classes) - 1, | |
| use_attention=True, | |
| use_ctc=True, | |
| grayscale=False, | |
| ) | |
| model.to(device) | |
| model.load_state_dict(torch.load("model-early_stop.pth", weights_only=True)) | |
| model.eval() | |
| filepath = "images/t1-score-09906661.png" | |
| answer = inference(filepath) | |
| print(f"text: {answer}") | |