nickgambirasi commited on
Commit
bade1d0
1 Parent(s): 4c471fe

create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import gradio
3
+ import torch
4
+
5
+ from PIL import Image
6
+ from transformers import DonutProcessor, VisionEncoderDecoderModel
7
+
8
+ processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
9
+ model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-cord-v2")
10
+
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+
13
+ model.to(device)
14
+
15
+ def process_document(image):
16
+
17
+ # prepare encoder inputs
18
+ pixel_values = processor(image, return_tensors="pt").pixel_values
19
+
20
+ # prepare decoder inputs
21
+ task_prompt = "<s_cord-v2>"
22
+ decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids
23
+
24
+ # generate answer
25
+ outputs = model.generate(
26
+ pixel_values.to(device),
27
+ decoder_input_ids=decoder_input_ids.to(device),
28
+ max_length=model.decoder.config.max_position_embeddings,
29
+ early_stopping=True,
30
+ pad_token_id=processor.tokenizer.pad_token_id,
31
+ eos_token_id=processor.tokenizer.eos_token_id,
32
+ use_cache=True,
33
+ num_beams=1,
34
+ bad_words_ids=[[processor.tokenizer.unk_token_id]],
35
+ return_dict_in_generate=True,
36
+ )
37
+
38
+ # postprocess
39
+ sequence = processor.batch_decode(outputs.sequences)[0]
40
+ sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
41
+ sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
42
+
43
+ return processor.token2json(sequence)
44
+
45
+ demo = gradio.Interface(
46
+ fn=process_document,
47
+ inputs="image",
48
+ outputs="json",
49
+ title="Document Parsing Demo",
50
+ description=None,
51
+ article=None,
52
+ enable_queue=True,
53
+ examples=None,
54
+ cache_examples=False)
55
+
56
+ demo.launch()