abhibisht89 commited on
Commit
83eb281
1 Parent(s): ac1fbd9

Create new file

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from transformers import DonutProcessor, VisionEncoderDecoderModel
3
+ import torch
4
+
5
+ processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa")
6
+ model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa")
7
+ device = "cuda" if torch.cuda.is_available() else "cpu"
8
+ model.to(device)
9
+
10
+
11
+ def doc_process(image,question):
12
+ # prepare decoder inputs
13
+ task_prompt = "<s_docvqa><s_question>{user_input}</s_question><s_answer>"
14
+ prompt = task_prompt.replace("{user_input}", question)
15
+ decoder_input_ids = processor.tokenizer(prompt, add_special_tokens=False, return_tensors="pt").input_ids
16
+
17
+ pixel_values = processor(image, return_tensors="pt").pixel_values
18
+
19
+
20
+ outputs = model.generate(
21
+ pixel_values.to(device),
22
+ decoder_input_ids=decoder_input_ids.to(device),
23
+ max_length=model.decoder.config.max_position_embeddings,
24
+ early_stopping=True,
25
+ pad_token_id=processor.tokenizer.pad_token_id,
26
+ eos_token_id=processor.tokenizer.eos_token_id,
27
+ use_cache=True,
28
+ num_beams=1,
29
+ bad_words_ids=[[processor.tokenizer.unk_token_id]],
30
+ return_dict_in_generate=True,
31
+ )
32
+
33
+ sequence = processor.batch_decode(outputs.sequences)[0]
34
+ sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
35
+ sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
36
+ #print(processor.token2json(sequence))
37
+ return processor.token2json(sequence)
38
+
39
+ description = "Gradio Demo for Donut, inspired by Nielsr demo"
40
+
41
+ article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2111.15664' target='_blank'>Donut: OCR-free Document Understanding Transformer</a> | <a href='https://github.com/clovaai/donut' target='_blank'>Github Repo</a></p>"
42
+
43
+ demo = gr.Interface(
44
+ fn=process_document,
45
+ inputs=["image", "text"],
46
+ outputs="json",
47
+ title="Demo: Donut 🍩 for DocVQA",
48
+ description=description,
49
+ article=article,
50
+ enable_queue=True,
51
+ examples=[["example_1.png", "What is date of birth?"], ["example_1.jpeg", "What's the Sex?"]],
52
+ cache_examples=False)
53
+
54
+ demo.launch()