nielsr HF staff commited on
Commit
3ef519b
1 Parent(s): 3e560c6

Create new file

Browse files
Files changed (1) hide show
  1. app.py +41 -0
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)