' # 添加一个包裹所有内容的div,设置文本颜色为黑色
for message_item in messages:
role = message_item['role']
content = message_item['content']
# 根据角色设置样式
if role == "user" or role == "human":
html_output += f'
User:'
elif role == "assistant":
html_output += f'
Assistant:'
else:
html_output += f'
{role.capitalize()}:'
# 处理内容
for content_item in content:
content_type = content_item['type']
if content_type == "text":
# 将Markdown文本转换为HTML
md_text = content_item['text']
html_text = markdown.markdown(md_text, extensions=['fenced_code', 'codehilite'])
# html_text = markdown.markdown(md_text)
# html_text = md_text
html_output += f'
{html_text}
'
elif content_type == "image_url":
content_value = content_item['image_url']['url']
# 如果是base64图片
if content_value.startswith("data:"):
html_output += f'

'
else:
html_output += f'

'
html_output += '
'
html_output += '
' # 关闭最外层div
return html_output
def pyvision_chat(model_name, client_type, api_key, base_url, question, image):
print("done!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
# 初始化组件
# client = AzureOpenAI(
# api_key=os.getenv("AZURE_OPENAI_API_KEY"), # 从环境变量读取
# api_version="2025-04-01-preview", # 使用最新API版本
# azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT") # 终结点URL
# )
if client_type == "Azure":
client = AzureOpenAI(
api_key=api_key, # 从环境变量读取
api_version="2025-04-01-preview", # 使用最新API版本
azure_endpoint=base_url # 终结点URL
)
else:
client = OpenAI(api_key=api_key, base_url=base_url)
executor = PythonExecutor()
prompt_template = json.load(open("./prompt_template_vis.json", "r", encoding="utf-8"))
prompt_type = 'vistool_with_img_info_v2'
data = {
"question": question,
"image": image,
}
# 评估单个数据点
messages = evaluate_single_data(model_name, data, client, executor, prompt_template, prompt_type)
html_output = process_message(messages)
# 将消息转换为JSON字符串,用于下载
json_str = json.dumps(messages, ensure_ascii=False, indent=4)
sharegpt_data_item = process_message_to_sharegpt_format(messages)
return html_output, sharegpt_data_item['images'], sharegpt_data_item['conversations']
# Gradio界面
def create_demo():
with gr.Blocks(title="PyVision's Online Demo", css="div.prose * {color: black !important;}") as demo:
gr.Markdown("# PyVision's Online Demo")
gr.Markdown("Upload an image and ask a question to get a response via PyVision's dynamic tooling ability.")
gr.Markdown("[Project Page](https://agent-x.space/pyvision/), [Research Paper](https://arxiv.org/abs/2507.07998), [Inference Code](https://github.com/agents-x-project/PyVision)")
with gr.Row():
with gr.Column(scale=1):
model_name = gr.Dropdown(
label="Model Selection",
choices=["gpt-4.1"],
value="gpt-4.1"
)
client_type = gr.Dropdown(label="Client Type Selection", choices=["Azure", "OpenAI"], value="Azure")
api_key = gr.Textbox(label="API Key (optional)", type="password", value=os.getenv("AZURE_OPENAI_API_KEY"))
base_url = gr.Textbox(label="Base URL (optional)", value=os.getenv("AZURE_OPENAI_ENDPOINT"))
image_input = gr.Image(label="Upload Image", type="pil")
question = gr.Textbox(label="Question", placeholder="Ask a question about the image...")
submit_btn = gr.Button("Submit")
with gr.Row():
output = gr.HTML(label="Response")
# with gr.Row():
# with gr.Column(scale=1):
# extracted_images = gr.Gallery(label="Extracted Images")
# with gr.Column(scale=1):
# extracted_json = gr.JSON(label="Extracted JSON")
# # 添加导出按钮
# with gr.Row():
# export_btn = gr.Button("Export to ZIP")
# download_file = gr.File(label="Download ZIP")
# 存储当前结果的状态变量
current_images = gr.State([])
current_json = gr.State(None)
# # 处理提交
# def handle_submit(model, client_type, key, url, q, img):
# html, images, json_data = pyvision_chat(model, client_type, key, url, q, img)
# return html, images, json_data, images, json_data
# submit_btn.click(
# fn=handle_submit,
# inputs=[model_name, client_type, api_key, base_url, question, image_input],
# outputs=[output, extracted_images, extracted_json, current_images, current_json]
# )
# 处理提交
def handle_submit(model, client_type, key, url, q, img):
html, images, json_data = pyvision_chat(model, client_type, key, url, q, img)
return html, images, json_data
submit_btn.click(
fn=handle_submit,
inputs=[model_name, client_type, api_key, base_url, question, image_input],
outputs=[output, current_images, current_json]
)
# # 处理导出
# def handle_export(images, conversations):
# if not images or conversations is None:
# return None
# zip_path = export_to_zip(images, conversations)
# return zip_path
# export_btn.click(
# fn=handle_export,
# inputs=[current_images, current_json],
# outputs=[download_file]
# )
# 示例部分
examples = [
# [
# "./examples/1.png",
# "From the information on that advertising board, what is the type of this shop?\nA. The shop is a yoga studio.\nB. The shop is a cafe.\nC. The shop is a seven-eleven.\nD. The shop is a milk tea shop.",
# ],
[
"./examples/2.png",
"What is the diagnosis for the abnormality seen in this image?\nA. Pulmonary embolism.\nB. Tuberculosis.\nC. COVID-19 infection.\nD. Influenza.",
],
[
"./examples/3.png",
"What is the color of the liquid contained in the glass on the table?\nA. The color of the liquid contained in the glass on the table is green.\nB. The color of the liquid contained in the glass on the table is transparent.\nC. The color of the liquid contained in the glass on the table is white.\nD. The color of the liquid contained in the glass on the table is orange.",
],
[
"./examples/4.png",
"Is the dog on the left or right side of the bicycle?\nA. The dog is on the right side of the bicycle.\nB. The dog is on the left side of the bicycle.",
],
[
"./examples/5.png",
"Is the kid with black shirt on the left or right side of the kid with blue shirt?\nA. The kid with black shirt is on the left side of the kid with blue shirt.\nB. The kid with black shirt is on the right side of the kid with blue shirt.",
],
[
"./examples/6.png",
"What can be observed in this image?\nA. Nerve entrapment.\nB. Musculoskeletal abnormality.\nC. Arteriovenous anomaly.\nD. Renal cyst.",
],
[
"./examples/7.png",
"What is the specific stage of cancer depicted in the image? A)Stage Ib, B)Stage IIIb, C)Stage IIc, D)Stage IIIa",
],
[
"./examples/8.png",
"A gymnast jotted down the number of cartwheels she did each day. What is the mode of the numbers?",
],
[
"./examples/9.png",
"Does Virginia have the highest value in the USA ?",
],
[
"./examples/10.png",
"AB is the diameter of ⊙O, PA is tangent to ⊙O at point A, and PO intersects ⊙O at point C; connect BC, if ∠P = 40.0, then ∠B is equal to ()",
],
[
"./examples/11.png",
"How many single-color paths go from C to A?",
],
[
"./examples/12.png",
"There is a numerical converter, the principle of which is shown in the following diagram: When the input x=16, the output y equals.",
],
[
"./examples/13.png",
"As shown in Figure 1, it is a right-angled triangular paper piece, $$ \angle A=30^{ \circ }$$, $$BC=\quantity{4}{cm}$$, it is folded so that point $$C$$ lands on point $$C'$$ on the hypotenuse, with the fold line being $$BD$$, as shown in Figure 2. Then, Figure 2 is folded along $$DE$$, so that point $$A$$ lands on point $$A'$$ on the extension of $$DC'$$, as shown in Figure 3. The length of the fold line $$DE$$ is ___.",
],
[
"./examples/14.png",
"As shown in the figure, in the 'Pascal's Triangle', the numbers above the diagonal line $$AB$$, indicated by the arrows, form a zigzag sequence: $$1$$, $$2$$, $$3$$, $$3$$, $$6$$, $$4$$, $$10$$, $$\cdots$$, let the sum of the first $$n$$ terms of this sequence be $$S_{n}$$, then $$S_{16}=$$ ___.",
],
[
"./examples/15.png",
"What do satellite 1, 2, 3 separately monitor in ?\nA. Earth's energy balance, Earth's water cycle, Earth's surface\nB. Earth's water cycle, Earth's energy balance, Earth's surface\nC. Earth's surface, Earth's water cycle, Earth's energy balance\nD. Earth's surface, Earth's energy balance, Earth's water cycle",
],
[
"./examples/16.png",
"This is a background image. Based on it, design a poster, rendering some text on it, including title, subtitle, and some slogan, making it a aesthetic and hormanized poster.",
],
[
"./examples/17.png",
"Fill the exact green shape shown in the question grid. Choose the only option set whose pieces perfectly tile the shape without gaps or overlap.",
],
[
"./examples/18.png",
"Consider a string of \(L=2.00 \mathrm{~m}\) attached to an adjustable-frequency string vibrator as shown in the figure. The waves produced by the vibrator travel down the string and are reflected by the fixed boundary condition at the pulley. The string, which has a linear mass density of \(\mu=0.006 \mathrm{~kg} / \mathrm{m}\), is passed over a frictionless pulley of a negligible mass, and the tension is provided by a 2.00-kg hanging mass.\n(a) What is the velocity of the waves on the string?\n(b) Draw a sketch of the first three normal modes of the standing waves that can be produced on the string and label each with the wavelength.\n(c) List the frequencies that the string vibrator must be tuned to in order to produce the first three normal modes of the standing waves.",
],
[
"./examples/19.png",
"The adventure starts at the green square. By following travel leftward 1 step, where do you conclude?",
],
]
gr.Examples(
examples,
[image_input, question],
label="Click any example to try it out!"
)
gr.Markdown("""
### Tips
1. We have set the API in this space, but if you want try run this demo on more data, please duplicate this space and set your own API.
2. It may take 2~5 min.
""")
return demo
# 创建并启动应用
if __name__ == "__main__":
demo = create_demo()
demo.launch()