Create new file
Browse files
app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
3 |
+
import requests
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-str")
|
7 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-str")
|
8 |
+
|
9 |
+
# load image examples
|
10 |
+
urls = ['https://i.postimg.cc/ZKwLg2Gw/367-14.png']
|
11 |
+
for idx, url in enumerate(urls):
|
12 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
13 |
+
image.save(f"image_{idx}.png")
|
14 |
+
|
15 |
+
def process_image(image):
|
16 |
+
# prepare image
|
17 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
18 |
+
|
19 |
+
# generate (no beam search)
|
20 |
+
generated_ids = model.generate(pixel_values)
|
21 |
+
|
22 |
+
# decode
|
23 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
24 |
+
|
25 |
+
return generated_text
|
26 |
+
|
27 |
+
title = "Interactive demo: Scene Text Recognition with TrOCR"
|
28 |
+
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 for scene text recognition. 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."
|
29 |
+
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2109.10282'>TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models</a> | <a href='https://github.com/microsoft/unilm/tree/master/trocr'>Github Repo</a></p>"
|
30 |
+
examples =[["image_0.png"]]
|
31 |
+
|
32 |
+
#css = """.output_image, .input_image {height: 600px !important}"""
|
33 |
+
|
34 |
+
iface = gr.Interface(fn=process_image,
|
35 |
+
inputs=gr.inputs.Image(type="pil"),
|
36 |
+
outputs=gr.outputs.Textbox(),
|
37 |
+
title=title,
|
38 |
+
description=description,
|
39 |
+
article=article,
|
40 |
+
examples=examples)
|
41 |
+
iface.launch(debug=True)
|