掘金 人工智能 07月11日 01:11
基于【ERNIE-4.5-VL-28B-A3B】模型的图片内容分析系统
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

该项目是一个基于Gradio和百度AI Studio的图像内容分析工具,它通过调用ERNIE-4.5-VL-28B-A3B大模型接口,实现对用户上传图片的描述或分析。用户可以上传本地图片并输入自定义提示词,系统将通过流式响应实时展示分析结果。该工具还提供了示例图片和提示词,方便用户快速测试。项目依赖于Gradio、OpenAI库,并需要配置大型语言模型API接口。

🖼️ 该项目核心功能是图像内容分析,用户可以上传本地图片并输入自定义提示词,系统将调用ERNIE-4.5-VL-28B-A3B大模型接口进行分析。

⌨️ 用户通过文本输入框输入提示词,系统结合图片内容进行分析,并以流式响应的方式实时展示分析结果。

⚙️ 项目依赖Gradio和OpenAI库,需要配置大型语言模型API接口,包括获取API密钥和设置Base URL。

💡 代码中使用base64编码图片,便于在网络请求中传递图像数据,核心函数analyze_image调用大模型并处理流式返回结果。

🚀 项目创建了Gradio界面,提供输入输出、标题、描述和示例数据,用户可以上传图片并输入提示词,体验图片分析功能。

1. 项目功能

该项目是一个基于 Gradio 和百度 AI Studio 的图像内容分析工具。它通过调用大模型接口(ERNIE-4.5-VL-28B-A3B),接收用户上传的图片和提示词(prompt),并返回对图片内容的描述或分析结果。

主要功能:

2. 依赖安装

在运行该项目之前,请确保已安装以下依赖库

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 图像分析主函数

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()`.

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Gradio 图像分析 ERNIE-4.5-VL-28B-A3B AI
相关文章