nielsr HF staff commited on
Commit
297128e
1 Parent(s): 215e851

First commit

Browse files
Files changed (1) hide show
  1. app.py +43 -0
app.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.system('pip install git+https://github.com/nielsrogge/transformers.git@add_tr_ocr --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-handwritten")
10
+ model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
11
+
12
+ # load image example from the IAM database
13
+ url = 'https://fki.tic.heia-fr.ch/static/img/a01-122-02.jpg'
14
+ image = Image.open(requests.get(url, stream=True).raw)
15
+ image.save("image.png")
16
+
17
+ def process_image(image):
18
+ # prepare image
19
+ pixel_values = processor(image, return_tensors="pt").pixel_values
20
+
21
+ # generate (no beam search)
22
+ generated_ids = model.generate(pixel_values)
23
+
24
+ # decode
25
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
26
+
27
+ return generated_text
28
+
29
+ title = "Interactive demo: TrOCR"
30
+ 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 the example image below and click 'submit'. Results will show up in a few seconds."
31
+ 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>"
32
+ examples =[["image.png"]]
33
+
34
+ #css = """.output_image, .input_image {height: 600px !important}"""
35
+
36
+ iface = gr.Interface(fn=process_image,
37
+ inputs=gr.inputs.Image(type="pil"),
38
+ outputs=gr.outputs.Textbox(),
39
+ title=title,
40
+ description=description,
41
+ article=article,
42
+ examples=examples)
43
+ iface.launch(debug=True)