# import os # os.system('pip install git+https://github.com/huggingface/transformers.git --upgrade') import gradio as gr from transformers import TrOCRProcessor, VisionEncoderDecoderModel import requests from PIL import Image processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed") model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed") model.config.eos_token_id = 2 # load image examples urls = ['https://layoutlm.blob.core.windows.net/trocr/dataset/SROIE2019Task2Crop/train/X00016469612_1.jpg', 'https://layoutlm.blob.core.windows.net/trocr/dataset/SROIE2019Task2Crop/train/X51005255805_7.jpg', 'https://layoutlm.blob.core.windows.net/trocr/dataset/SROIE2019Task2Crop/train/X51005745214_6.jpg'] for idx, url in enumerate(urls): image = Image.open(requests.get(url, stream=True).raw) image.save(f"image_{idx}.png") def process_image(image): # prepare image pixel_values = processor(image, return_tensors="pt").pixel_values # generate (no beam search) generated_ids = model.generate(pixel_values) # decode generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] return generated_text title = "Interactive demo: TrOCR" description = "Demo for Microsoft's TrOCR, an encoder-decoder model consisting of an image Transformer encoder and a text Transformer decoder for state-of-the-art optical character recognition (OCR) on single-text line images. This particular model is fine-tuned on SROIE Task 2, a dataset of annotated printed images. To use it, simply upload a (single-text line) image or use one of the example images below and click 'submit'. Results will show up in a few seconds." article = "
TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models | Github Repo
" examples =[["image_0.png"], ["image_1.png"], ["image_2.png"]] #css = """.output_image, .input_image {height: 600px !important}""" iface = gr.Interface(fn=process_image, inputs=gr.inputs.Image(type="pil"), outputs=gr.outputs.Textbox(), title=title, description=description, article=article, examples=examples) iface.launch(debug=True)