Spaces:
Sleeping
Sleeping
initial app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
|
| 3 |
+
import requests
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import torch
|
| 6 |
+
|
| 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 |
+
model = PaliGemmaForConditionalGeneration.from_pretrained("./ahmed-masry/chartgemma")
|
| 13 |
+
processor = AutoProcessor.from_pretrained("./ahmed-masry/chartgemma")
|
| 14 |
+
|
| 15 |
+
def predict(image, input_text):
|
| 16 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 17 |
+
model.to(device)
|
| 18 |
+
|
| 19 |
+
image = image.convert("RGB")
|
| 20 |
+
|
| 21 |
+
inputs = processor(text=input_text, images=image, return_tensors="pt")
|
| 22 |
+
inputs = {k: v.to(device) for k, v in inputs.items()}
|
| 23 |
+
|
| 24 |
+
prompt_length = inputs['input_ids'].shape[1]
|
| 25 |
+
|
| 26 |
+
# 生成文本
|
| 27 |
+
generate_ids = model.generate(**inputs, max_new_tokens=512)
|
| 28 |
+
output_text = processor.batch_decode(generate_ids[:, prompt_length:], skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 29 |
+
|
| 30 |
+
return output_text
|
| 31 |
+
|
| 32 |
+
examples = [
|
| 33 |
+
["chart_example_1.png", "Describe the trend of the mortality rates for children before age 5"],
|
| 34 |
+
["chart_example_2.png", "What is the share of respondents who prefer Facebook Messenger in the 30-59 age group?"]
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
title = "ChartGemma 模型的互动式 Gradio 演示"
|
| 38 |
+
|
| 39 |
+
with gr.Blocks(css="theme.css") as demo:
|
| 40 |
+
gr.Markdown(f"# {title}")
|
| 41 |
+
|
| 42 |
+
with gr.Row():
|
| 43 |
+
with gr.Column():
|
| 44 |
+
image = gr.Image(type="pil", label="图表图像")
|
| 45 |
+
input_prompt = gr.Textbox(label="输入")
|
| 46 |
+
|
| 47 |
+
with gr.Column():
|
| 48 |
+
model_output = gr.Textbox(label="输出")
|
| 49 |
+
|
| 50 |
+
gr.Examples(examples=examples, inputs=[image, input_prompt])
|
| 51 |
+
|
| 52 |
+
submit_button = gr.Button("运行")
|
| 53 |
+
submit_button.click(predict, inputs=[image, input_prompt], outputs=model_output)
|
| 54 |
+
|
| 55 |
+
demo.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
| 56 |
+
|