File size: 2,160 Bytes
8908073 e97e76a 8908073 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | 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()
|