Download main.py from SunDoge/manga-ocr-encoder-decoder: direct link, hf CLI and curl.
- Browser
- Download file 2.16 kB
-
https://huggingface.co/SunDoge/manga-ocr-encoder-decoder/resolve/main/main.py
- Command line
-
hf download hf://SunDoge/manga-ocr-encoder-decoder/main.py
-
curl -L -o main.py https://huggingface.co/SunDoge/manga-ocr-encoder-decoder/resolve/main/main.py
2.16 kB
| import requests | |
| import cv2 | |
| from loguru import logger | |
| import numpy as np | |
| import onnxruntime as ort | |
| from pathlib import Path | |
| def main(): | |
| vocab_txt = Path("vocab.txt").read_text() | |
| vocab = [x.strip() for x in vocab_txt.split()] | |
| image_path = Path("assets/04.jpg") | |
| if image_path.exists(): | |
| logger.info("read image from: {}", image_path) | |
| img = cv2.imread(str(image_path)) | |
| else: | |
| resp = requests.get( | |
| "https://raw.githubusercontent.com/kha-white/manga-ocr/refs/heads/master/assets/examples/04.jpg" | |
| ) | |
| img = cv2.imdecode( | |
| np.frombuffer(resp.content, dtype=np.uint8), cv2.IMREAD_COLOR | |
| ) | |
| logger.info("download image to: {}", image_path) | |
| image_path.parent.mkdir(parents=True, exist_ok=True) | |
| with image_path.open("wb") as f: | |
| f.write(resp.content) | |
| logger.info("image shape: {}", img.shape) | |
| img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_LINEAR) | |
| img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) | |
| img = img.transpose((2, 0, 1)).astype(np.float32) / 255.0 | |
| img = (img - 0.5) / 0.5 | |
| encoder_session = ort.InferenceSession("output/encoder_model.onnx") | |
| decoder_session = ort.InferenceSession("output/decoder_model.onnx") | |
| # Save encoder hidden states for reuse. | |
| outputs = encoder_session.run(None, {"pixel_values": img[None]}) | |
| encoder_hidden_states = outputs[0] | |
| input_ids = [2] | |
| # Use greedy search for example, should be beam search. | |
| for _ in range(300): | |
| input_ids_tensor = np.array(input_ids) | |
| outputs = decoder_session.run( | |
| None, | |
| { | |
| "input_ids": input_ids_tensor[None], | |
| "encoder_hidden_states": encoder_hidden_states, # Reuse encoder hidden states. | |
| }, | |
| ) | |
| logits = outputs[0] | |
| index = np.argmax(logits[:, -1], axis=-1) | |
| if index == 3: | |
| break | |
| input_ids.append(index.item()) | |
| logger.debug("text: {}", "".join([vocab[i] for i in input_ids])) | |
| logger.info("final text: {}", "".join([vocab[i] for i in input_ids])) | |
| if __name__ == "__main__": | |
| main() | |