1. 项目功能
该项目是一个基于 Gradio 和百度 AI Studio 的图像内容分析工具。它通过调用大模型接口(ERNIE-4.5-VL-28B-A3B),接收用户上传的图片和提示词(prompt),并返回对图片内容的描述或分析结果。
主要功能:
- 支持上传本地图片进行分析。提供文本输入框,用于输入自定义提示词。使用流式响应实时展示分析结果。内置示例图片和提示词,方便快速测试。
2. 依赖安装
在运行该项目之前,请确保已安装以下依赖库
- gradioopenai:
pip install gradio openai
此外,还需要准备一个可用的大型语言模型 API 接口,并配置好相应的访问权限和密钥信息。可以自行从aistudio上获取,或者通过代码获取,代码如下:
import os# 获取环境变量(可设置默认值)OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL")print("OPENAI_BASE_URL:", OPENAI_BASE_URL)OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")print("OPENAI_API_KEY:", OPENAI_API_KEY)
3. 代码解析
3.1 导入模块
# 导入 Gradio 库,用于创建 Web 界面import gradio as gr# 从 openai 模块导入 OpenAI 客户端类,用于调用大模型 APIfrom openai import OpenAI# 导入 os 模块,用于处理操作系统路径和环境变量等import os# 导入 base64 模块,用于对图片进行 Base64 编码以便传输import base64
/opt/conda/envs/python35-paddle120-env/lib/python3.10/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm
使用了 gradio
构建 Web 界面,openai
调用模型 API,base64
编码图片以便传输。
3.2 初始化客户端
配置 OpenAI 客户端,指定模型服务地址与 API 密钥。
client = OpenAI( api_key=OPENAI_API_KEY, base_url=OPENAI_BASE_URL)
3.3 图像编码
将图片文件转换为 Base64 编码,便于在网络请求中传递。
def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8')
3.4 图像分析主函数
- 调用ERNIE-4.5-VL-28B-A3B模型对图像进行分析核心逻辑:发送包含图片和提示词的消息给模型,获取并拼接流式返回的结果。
def analyze_image(image, prompt): if image is None: return "Please upload an image" # image_url = get_image_url(image) chat_completion = client.chat.completions.create( model="ernie-4.5-vl-28b-a3b", messages=[ { "role": "user", "content": [ { "type": "text", "text": prompt }, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image(image)}"} }, ] } ], stream=True, extra_body={ "penalty_score": 1, "enable_thinking": True }, max_completion_tokens=2000, temperature=0.2, top_p=0.8, frequency_penalty=0, presence_penalty=0 ) # Process the streaming response result = "" for chunk in chat_completion: if chunk.choices[0].delta.content is not None: result += chunk.choices[0].delta.content return result
3.5 创建 Gradio 界面
构建可视化界面,设置输入输出、标题、描述和示例数据。
# Example images and promptsexample_images = [ "https://p2.img.cctvpic.com/photoAlbum/photo/2025/07/09/PHOTDwYcYiAsM1W6RTvNQQef250709_1000x2000.png", "https://p5.img.cctvpic.com/photoAlbum/photo/2025/07/09/PHOT4gbJEL5NrXzVcuNtLvBR250709_1000x2000.png", "https://p2.img.cctvpic.com/photoAlbum/photo/2025/07/09/PHOTXfQiPIt7eWQY0p92zUVu250709_1000x2000.png"]example_prompts = [ "请问这是什么花?", "图里是什么人?在干什么?", "这张图描述的是什么?"]# Create a Gradio interface with examplesdemo = gr.Interface( fn=analyze_image, inputs=[ gr.Image(type="filepath"), gr.Textbox(label="提示词:", placeholder="请输入提示内容...") ], outputs=gr.Markdown(), title="【ERNIE-4.5-VL-28B-A3B】图片内容分析系统", description="上传一张图片,输入提示内容,我将为您分析图片中的内容。", api_name="analyze_image", flagging_mode="never", # Replace allow_flagging with flagging_mode examples=[ [example_images[0], example_prompts[0]], [example_images[1], example_prompts[1]], [example_images[2], example_prompts[2]] ])
3.6 启动应用
运行脚本后启动 Gradio 应用,默认不开启公网访问。
# Launch the Gradio appif __name__ == "__main__": demo.launch(share=False)
* Running on local URL: http://127.0.0.1:7860To create a public link, set `share=True` in `launch()`.