CLIP-GmP-ViT-L-14简单调用:JavaScript前端调用Gradio API完整示例

CLIP-GmP-ViT-L-14简单调用:JavaScript前端调用Gradio API完整示例 CLIP-GmP-ViT-L-14简单调用JavaScript前端调用Gradio API完整示例1. 项目简介CLIP-GmP-ViT-L-14是一个经过几何参数化(GmP)微调的CLIP模型在ImageNet和ObjectNet数据集上达到了约90%的准确率。这个强大的视觉-语言模型可以帮助我们计算图片和文本之间的相似度在图像搜索、内容匹配等场景有广泛应用。本项目提供了一个基于Gradio的Web界面支持两种核心功能单图单文相似度计算上传一张图片和一段文本获取它们的匹配度分数批量检索一张图片匹配多个文本提示按相关性排序输出结果2. 环境准备2.1 服务端部署在开始前端调用前我们需要先确保服务端已经正确部署。以下是两种启动方式推荐方式- 使用启动脚本cd /root/CLIP-GmP-ViT-L-14 ./start.sh备选方式- 手动启动cd /root/CLIP-GmP-ViT-L-14 python3 /root/CLIP-GmP-ViT-L-14/app.py服务启动后可以通过http://localhost:7860访问Gradio界面。2.2 前端开发环境我们需要准备一个简单的HTML页面来调用API确保你有现代浏览器Chrome/Firefox/Edge等文本编辑器VSCode/Sublime等基础的JavaScript知识3. 前端调用实现3.1 基础HTML结构首先创建一个简单的HTML文件包含图片上传和文本输入区域!DOCTYPE html html head titleCLIP-GmP-ViT-L-14 API调用示例/title style body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; } .container { display: flex; flex-direction: column; gap: 20px; } .input-group { display: flex; flex-direction: column; gap: 10px; } button { padding: 10px; background: #4CAF50; color: white; border: none; cursor: pointer; } #result { margin-top: 20px; padding: 15px; background: #f5f5f5; border-radius: 5px; } /style /head body div classcontainer h1CLIP-GmP-ViT-L-14 API调用/h1 div classinput-group label forimage上传图片/label input typefile idimage acceptimage/* /div div classinput-group label fortext输入文本/label textarea idtext rows3 placeholder输入要匹配的文本描述/textarea /div button idsubmit计算相似度/button div idresult/div /div script srcapp.js/script /body /html3.2 JavaScript API调用创建一个app.js文件实现与Gradio API的交互document.getElementById(submit).addEventListener(click, async function() { const imageInput document.getElementById(image); const textInput document.getElementById(text); const resultDiv document.getElementById(result); // 验证输入 if (!imageInput.files[0] || !textInput.value.trim()) { resultDiv.innerHTML 请上传图片并输入文本; return; } resultDiv.innerHTML 处理中...; try { // 准备FormData const formData new FormData(); formData.append(image, imageInput.files[0]); formData.append(text, textInput.value); // 调用Gradio API const response await fetch(http://localhost:7860/api/predict, { method: POST, body: formData }); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data await response.json(); // 显示结果 resultDiv.innerHTML h3匹配结果/h3 p图片与文本的相似度得分: strong${data.score.toFixed(4)}/strong/p p解释: 得分范围0-1越接近1表示匹配度越高/p ; } catch (error) { resultDiv.innerHTML 发生错误: ${error.message}; console.error(API调用失败:, error); } });4. 功能扩展4.1 批量文本匹配如果需要一次匹配多个文本可以修改代码如下// 在HTML中添加多文本输入区域 // textarea idtexts rows5 placeholder每行输入一个文本描述/textarea document.getElementById(submit).addEventListener(click, async function() { const imageInput document.getElementById(image); const textsInput document.getElementById(texts); const resultDiv document.getElementById(result); if (!imageInput.files[0] || !textsInput.value.trim()) { resultDiv.innerHTML 请上传图片并输入文本; return; } resultDiv.innerHTML 处理中...; try { const formData new FormData(); formData.append(image, imageInput.files[0]); // 将多行文本转换为数组 const texts textsInput.value.split(\n).filter(t t.trim()); formData.append(texts, JSON.stringify(texts)); const response await fetch(http://localhost:7860/api/predict_batch, { method: POST, body: formData }); const data await response.json(); // 格式化结果显示 let html h3批量匹配结果/h3ol; data.results.forEach(item { html li${item.text}: strong${item.score.toFixed(4)}/strong/li; }); html /ol; resultDiv.innerHTML html; } catch (error) { resultDiv.innerHTML 发生错误: ${error.message}; console.error(API调用失败:, error); } });4.2 图片预览功能增强用户体验添加图片预览// 在HTML中添加图片预览区域 // img idpreview stylemax-width: 300px; display: none; document.getElementById(image).addEventListener(change, function(e) { const preview document.getElementById(preview); if (e.target.files[0]) { const reader new FileReader(); reader.onload function(event) { preview.src event.target.result; preview.style.display block; }; reader.readAsDataURL(e.target.files[0]); } else { preview.style.display none; } });5. 常见问题解决5.1 跨域问题如果遇到跨域错误可以在服务端添加CORS支持。修改Gradio应用的Python代码from fastapi.middleware.cors import CORSMiddleware app FastAPI() app.add_middleware( CORSMiddleware, allow_origins[*], allow_credentialsTrue, allow_methods[*], allow_headers[*], )5.2 大文件上传对于大图片文件可能需要调整Gradio的文件大小限制app gr.Interface( # ...其他参数 file_size_limit20 * 1024 * 1024 # 20MB )5.3 错误处理完善前端错误处理// 在fetch调用后添加状态检查 if (data.error) { throw new Error(data.error); }6. 总结通过本教程我们实现了使用JavaScript前端调用CLIP-GmP-ViT-L-14的Gradio API实现了单图和单文本的相似度计算功能扩展了批量文本匹配和图片预览功能解决了常见的跨域和错误处理问题这个示例展示了如何将强大的CLIP模型集成到Web应用中为图像搜索、内容匹配等场景提供了基础实现。你可以基于此进一步开发更复杂的应用如电商产品搜索社交媒体内容审核智能相册管理教育内容匹配系统获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。