matcha_chartqa / app.py
fl399's picture
Update app.py
a6237eb
raw history blame
No virus
2.22 kB
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")
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)