ahmed-masry commited on
Commit
4f1faee
1 Parent(s): 4ae7b97

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import DonutProcessor, VisionEncoderDecoderModel
3
+ import requests
4
+ from PIL import Image
5
+ import torch, os, re
6
+
7
+ torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/74801584018932.png', 'chart_example_1.png')
8
+ torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/multi_col_1229.png', 'chart_example_2.png')
9
+
10
+
11
+ model_name = "ahmed-masry/unichart-base-960"
12
+ model = VisionEncoderDecoderModel.from_pretrained(model_name, use_auth_token=os.environ['temp_access_token'])
13
+ processor = DonutProcessor.from_pretrained(model_name, use_auth_token=os.environ['temp_access_token'])
14
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
15
+ model.to(device)
16
+
17
+
18
+ def predict(image, input_prompt):
19
+ input_prompt += " <s_answer>"
20
+ decoder_input_ids = processor.tokenizer(input_prompt, add_special_tokens=False, return_tensors="pt").input_ids
21
+ pixel_values = processor(image, return_tensors="pt").pixel_values
22
+
23
+ outputs = model.generate(
24
+ pixel_values.to(device),
25
+ decoder_input_ids=decoder_input_ids.to(device),
26
+ max_length=model.decoder.config.max_position_embeddings,
27
+ early_stopping=True,
28
+ pad_token_id=processor.tokenizer.pad_token_id,
29
+ eos_token_id=processor.tokenizer.eos_token_id,
30
+ use_cache=True,
31
+ num_beams=4,
32
+ bad_words_ids=[[processor.tokenizer.unk_token_id]],
33
+ return_dict_in_generate=True,
34
+ )
35
+ sequence = processor.batch_decode(outputs.sequences)[0]
36
+ sequence = sequence.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
37
+ sequence = re.sub(r"<.*?>", "", sequence, count=2).strip()
38
+ return sequence
39
+
40
+
41
+ image = gr.inputs.Image(type="pil", label="Chart Image")
42
+ input_prompt = gr.inputs.Textbox(label="Input Prompt")
43
+ model_output = gr.outputs.Textbox(label="Model Output")
44
+ examples = [["chart_example_1.png", "<summarize_chart>"],
45
+ ["chart_example_2.png", "<extract_data_table>"]]
46
+
47
+ title = "Interactive Gradio Demo for UniChart-base-960 model"
48
+ interface = gr.Interface(fn=predict,
49
+ inputs=[image, input_prompt],
50
+ outputs=model_output,
51
+ examples=examples,
52
+ title=title,
53
+ theme='gradio/soft',
54
+ enable_queue=True)
55
+
56
+ interface.launch()