File size: 2,265 Bytes
1cdf007
 
 
 
 
 
 
 
 
 
 
 
73faa4f
1cdf007
 
 
 
 
 
 
 
a6237eb
 
1cdf007
 
 
 
 
b8b89d1
a6237eb
73faa4f
 
1cdf007
73faa4f
 
1cdf007
a6237eb
 
1cdf007
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import gradio as gr
from transformers import Pix2StructForConditionalGeneration, Pix2StructProcessor
import requests
from PIL import Image
import torch

torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/val/png/20294671002019.png', 'chart_example.png')
torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/multi_col_1081.png', 'chart_example_2.png')
torch.hub.download_url_to_file('https://raw.githubusercontent.com/vis-nlp/ChartQA/main/ChartQA%20Dataset/test/png/18143564004789.png', 'chart_example_3.png')
torch.hub.download_url_to_file('https://sharkcoder.com/files/article/matplotlib-bar-plot.png', 'chart_example_4.png')


model_name = "google/matcha-chartqa"
model = Pix2StructForConditionalGeneration.from_pretrained(model_name)
processor = Pix2StructProcessor.from_pretrained(model_name)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

def filter_output(output):
    return output.replace("<0x0A>", "")

def chart_qa(image, question):
    inputs = processor(images=image, text=question, return_tensors="pt").to(device)
    predictions = model.generate(**inputs, max_new_tokens=512)
    return filter_output(processor.decode(predictions[0], skip_special_tokens=True))

   
image = gr.inputs.Image(type="pil", label="Chart")
question = gr.inputs.Textbox(label="Question")
answer = gr.outputs.Textbox(label="Model Output")
examples = [["chart_example.png", "Which country has the second highest death rate?"], ]
            #["chart_example_2.png"], ["chart_example_3.png"], ["chart_example_4.png"]]

title = "Interactive demo: chart QA"
description = "Gradio Demo for matcha model, fine-tuned on the ChartQA dataset. To use it, simply upload your image and click 'submit', or click one of the examples to load them."

interface = gr.Interface(fn=chart_qa, 
                         inputs=[image, question], 
                         outputs=answer, 
                         examples=examples, 
                         title=title,
                         description=description,
                         theme='gradio/soft',
                         enable_queue=True)

interface.launch(debug=True)