Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.system('pip install git+https://github.com/huggingface/transformers.git --upgrade')
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
|
6 |
+
import requests
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
|
10 |
+
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
|
11 |
+
|
12 |
+
# load image examples
|
13 |
+
urls = ['https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg', 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoolxi9yWGAT5SLZShv8vVd0bz47UWRzQC19fDTeE8GmGv_Rn-PCF1pP1rrUx8kOjA4gg&usqp=CAU',
|
14 |
+
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRNYtTuSBpZPV_nkBYPMFwVVD9asZOPgHww4epu9EqWgDmXW--sE2o8og40ZfDGo87j5w&usqp=CAU']
|
15 |
+
for idx, url in enumerate(urls):
|
16 |
+
image = Image.open(requests.get(url, stream=True).raw)
|
17 |
+
image.save(f"image_{idx}.png")
|
18 |
+
|
19 |
+
def process_image(image):
|
20 |
+
# prepare image
|
21 |
+
pixel_values = processor(image, return_tensors="pt").pixel_values
|
22 |
+
|
23 |
+
# generate (no beam search)
|
24 |
+
generated_ids = model.generate(pixel_values)
|
25 |
+
|
26 |
+
# decode
|
27 |
+
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
28 |
+
|
29 |
+
return generated_text
|
30 |
+
|
31 |
+
title = "Interactive demo: TrOCR"
|
32 |
+
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 IAM, a dataset of annotated handwritten 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."
|
33 |
+
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>"
|
34 |
+
examples =[["image_5.png"], ["image_0.png"], ["image_1.png"], ["image_2.png"]]
|
35 |
+
|
36 |
+
#css = """.output_image, .input_image {height: 600px !important}"""
|
37 |
+
|
38 |
+
iface = gr.Interface(fn=process_image,
|
39 |
+
inputs=gr.inputs.Image(type="pil"),
|
40 |
+
outputs=gr.outputs.Textbox(),
|
41 |
+
title=title,
|
42 |
+
description=description,
|
43 |
+
article=article,
|
44 |
+
examples=examples)
|
45 |
+
iface.launch(debug=True)
|