gwkrsrch commited on
Commit
4ace749
1 Parent(s): 60d698c

initial commit

Browse files
Files changed (2) hide show
  1. app.py +69 -0
  2. requirements.txt +2 -0
app.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Donut
3
+ Copyright (c) 2022-present NAVER Corp.
4
+ MIT License
5
+
6
+ https://github.com/clovaai/donut
7
+ """
8
+ import argparse
9
+
10
+ import gradio as gr
11
+ import torch
12
+ from PIL import Image
13
+
14
+ from donut import DonutModel
15
+
16
+
17
+ def demo_process_vqa(input_img, question):
18
+ global pretrained_model, task_prompt, task_name
19
+ input_img = Image.fromarray(input_img)
20
+ user_prompt = task_prompt.replace("{user_input}", question)
21
+ output = pretrained_model.inference(input_img, prompt=user_prompt)["predictions"][0]
22
+ return output
23
+
24
+
25
+ def demo_process(input_img):
26
+ global pretrained_model, task_prompt, task_name
27
+ input_img = Image.fromarray(input_img)
28
+ output = pretrained_model.inference(image=input_img, prompt=task_prompt)["predictions"][0]
29
+ return output
30
+
31
+
32
+ if __name__ == "__main__":
33
+ parser = argparse.ArgumentParser()
34
+ parser.add_argument("--task", type=str, default="cord-v2")
35
+ parser.add_argument("--pretrained_path", type=str, default="naver-clova-ix/donut-base-finetuned-cord-v2")
36
+ parser.add_argument("--port", type=int, default=None)
37
+ parser.add_argument("--url", type=str, default=None)
38
+ parser.add_argument("--sample_img_path", type=str)
39
+ args, left_argv = parser.parse_known_args()
40
+
41
+ task_name = args.task
42
+ if "docvqa" == task_name:
43
+ task_prompt = "<s_docvqa><s_question>{user_input}</s_question><s_answer>"
44
+ else: # rvlcdip, cord, ...
45
+ task_prompt = f"<s_{task_name}>"
46
+
47
+ example_sample = []
48
+ if args.sample_img_path:
49
+ example_sample.append(args.sample_img_path)
50
+
51
+ pretrained_model = DonutModel.from_pretrained(args.pretrained_path)
52
+
53
+ if torch.cuda.is_available():
54
+ pretrained_model.half()
55
+ device = torch.device("cuda")
56
+ pretrained_model.to(device)
57
+ else:
58
+ pretrained_model.encoder.to(torch.bfloat16)
59
+
60
+ pretrained_model.eval()
61
+
62
+ demo = gr.Interface(
63
+ fn=demo_process_vqa if task_name == "docvqa" else demo_process,
64
+ inputs=["image", "text"] if task_name == "docvqa" else "image",
65
+ outputs="json",
66
+ title=f"Donut 🍩 demonstration for `{task_name}` task",
67
+ examples=[example_sample] if example_sample else None,
68
+ )
69
+ demo.launch(server_name=args.url, server_port=args.port)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ donut-python
2
+ gradio