Spaces:
Running
on
Zero
Running
on
Zero
ahmed-masry
commited on
Commit
•
5efd720
1
Parent(s):
2bcca18
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoProcessor, AutoModelForSeq2SeqLM
|
3 |
+
import requests
|
4 |
+
from PIL import Image
|
5 |
+
import torch, os, re, json
|
6 |
+
import spaces
|
7 |
+
|
8 |
+
torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/74801584018932.png', 'chart_example_1.png')
|
9 |
+
torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/multi_col_1229.png', 'chart_example_2.png')
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("ahmed-masry/ChartInstruct-FlanT5-XL", torch_dtype=torch.float16, trust_remote_code=True)
|
14 |
+
processor = AutoProcessor.from_pretrained("ahmed-masry/ChartInstruct-FlanT5-XL")
|
15 |
+
|
16 |
+
|
17 |
+
@spaces.GPU
|
18 |
+
def predict(image, input_text):
|
19 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
20 |
+
model.to(device)
|
21 |
+
|
22 |
+
input_prompt = f"<image>\n Question: {input_text} Answer: "
|
23 |
+
image = image.convert("RGB")
|
24 |
+
|
25 |
+
inputs = processor(text=input_prompt, images=image, return_tensors="pt")
|
26 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
27 |
+
|
28 |
+
# change type if pixel_values in inputs to fp16.
|
29 |
+
inputs['pixel_values'] = inputs['pixel_values'].to(torch.float16)
|
30 |
+
|
31 |
+
# Generate
|
32 |
+
generate_ids = model.generate(**inputs, num_beams=4, max_new_tokens=512)
|
33 |
+
output_text = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
34 |
+
|
35 |
+
return output_text
|
36 |
+
|
37 |
+
|
38 |
+
image = gr.components.Image(type="pil", label="Chart Image")
|
39 |
+
input_prompt = gr.components.Textbox(label="Input Prompt")
|
40 |
+
model_output = gr.components.Textbox(label="Model Output")
|
41 |
+
examples = [["chart_example_1.png", "Describe the trend of the mortality rates for the Neonatal"],
|
42 |
+
["chart_example_2.png", "What is the share of respondants who prefer Facebook Messenger in the 30-59 age group?"]]
|
43 |
+
|
44 |
+
title = "Interactive Gradio Demo for ChartInstruct-FlanT5-XL model"
|
45 |
+
interface = gr.Interface(fn=predict,
|
46 |
+
inputs=[image, input_prompt],
|
47 |
+
outputs=model_output,
|
48 |
+
examples=examples,
|
49 |
+
title=title,
|
50 |
+
theme='gradio/soft')
|
51 |
+
|
52 |
+
interface.launch()
|