0

0

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

WBOY

WBOY

发布时间:2024-08-14 12:09:24

|

718人浏览过

|

来源于dev.to

转载

介绍

想象一下您在网上购物时发现了一种您喜欢的产品,但不知道它的名字。上传图片并让应用程序为您找到它,这不是很棒吗?

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

在本文中,我们将向您展示如何构建这一功能:使用 spring boot 和 google cloud vertex ai 的基于图像的产品搜索功能。

功能概述

此功能允许用户上传图像并接收与其匹配的产品列表,使搜索体验更加直观和视觉驱动。

基于图像的产品搜索功能利用 google cloud vertex ai 处理图像并提取相关关键词。然后使用这些关键字在数据库中搜索匹配的产品。

技术栈

  • java 21
  • spring 启动 3.2.5
  • postgresql
  • 顶点人工智能
  • reactjs

我们将逐步完成设置此功能的过程。

逐步实施

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

1. 在google console上创建一个新项目

首先,我们需要为此在 google console 上创建一个新项目。

如果您已经有一个帐户,我们需要转到 https://console.cloud.google.com 并创建一个新帐户。如果您有的话,请登录该帐户。

如果您添加银行帐户,google cloud 将为您提供免费试用。

创建帐户或登录现有帐户后,您可以创建新项目。

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

2. 启用顶点ai服务

在搜索栏上,我们需要找到 vertex ai 并启用所有推荐的 api。

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

vertex ai 是 google cloud 完全托管的机器学习 (ml) 平台,旨在简化 ml 模型的开发、部署和管理。它允许您通过提供 automl、自定义模型训练、超参数调整和模型监控等工具和服务来大规模构建、训练和部署 ml 模型 gemini 1.5 flash 是 google gemini 模型系列的一部分,专为 ml 应用程序中的高效、高性能推理而设计。 gemini 模型是 google 开发的一系列高级 ai 模型,常用于自然语言处理 (nlp)、视觉任务和其他 ai 驱动的应用程序

注意: 对于其他框架,您可以直接使用 gemini api,网址为 https://aistudio.google.com/app/prompts/new_chat。使用结构提示功能,因为您可以自定义输出以匹配输入,这样您将获得更好的结果。

3. 创建与您的应用程序匹配的新提示

在这一步,我们需要定制一个与您的应用相匹配的提示。

vertex ai studio 在提示图库提供了很多示例提示。我们使用示例图像文本到json来提取与产品图像相关的关键字。

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

我的应用程序是一个 carshop,所以我构建了一个这样的提示。我期望模型会用与图像相关的关键字列表来回复我。

我的提示:将名称 car 提取到列表关键字并以 json 格式输出。如果没有找到任何有关汽车的信息,请将列表输出为空。n响应示例:[“rolls”, “royce”, “wraith”]

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

Nanonets
Nanonets

基于AI的自学习OCR文档处理,自动捕获文档数据

下载

我们根据您的应用程序定制合适的提示后。现在,我们就来探讨一下如何与 spring boot application 集成。

4. 与 spring boot 应用程序集成

我构建了一个关于汽车的电子商务应用程序。所以我想通过图像找到汽车。

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

首先,在 pom.xml 文件中,您应该更新您的依赖项:

<!-- config version for dependency-->
<properties>
    <spring-cloud-gcp.version>5.1.2</spring-cloud-gcp.version>
    <google-cloud-bom.version>26.32.0</google-cloud-bom.version>
</properties>

<!-- in your dependencymanagement, please add 2 dependencies below -->
<dependencymanagement>
  <dependencies>
      <dependency>
          <groupid>com.google.cloud</groupid>
          <artifactid>spring-cloud-gcp-dependencies</artifactid>
          <version>${spring-cloud-gcp.version}</version>
          <type>pom</type>
          <scope>import</scope>
      </dependency>

      <dependency>
          <groupid>com.google.cloud</groupid>
          <artifactid>libraries-bom</artifactid>
          <version>${google-cloud-bom.version}</version>
          <type>pom</type>
          <scope>import</scope>
      </dependency>
  </dependencies>
</dependencymanagement>

<!-- in your tab dependencies, please add the dependency below -->
<dependencies>
  <dependency>
      <groupid>com.google.cloud</groupid>
      <artifactid>google-cloud-vertexai</artifactid>
  </dependency>
</dependencies>

在 pom.xml 文件中完成配置后,创建一个配置类 geminiconfig.java

  • model_name:“gemini-1.5-flash”
  • location:“设置项目时的位置”
  • project_id:“您的项目id”

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

import com.google.cloud.vertexai.vertexai;
import com.google.cloud.vertexai.generativeai.generativemodel;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;

@configuration(proxybeanmethods = false)
public class geminiconfig {

    private static final string model_name = "gemini-1.5-flash";
    private static final string location = "asia-southeast1";
    private static final string project_id = "yasmini";

    @bean
    public vertexai vertexai() {
        return new vertexai(project_id, location);
    }

    @bean
    public generativemodel getmodel(vertexai vertexai) {
        return new generativemodel(model_name, vertexai);
    }
}

其次,创建图层service、controller来实现寻车功能。创建班级服务。

因为 gemini api 响应的是 markdown 格式,所以我们需要创建一个函数来帮助转换为 json,然后我们将 json 转换为 java 中的 list 字符串。

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

import com.fasterxml.jackson.core.jsonprocessingexception;
import com.fasterxml.jackson.databind.objectmapper;
import com.google.cloud.vertexai.api.content;
import com.google.cloud.vertexai.api.generatecontentresponse;
import com.google.cloud.vertexai.api.part;
import com.google.cloud.vertexai.generativeai.*;
import com.learning.yasminishop.common.entity.product;
import com.learning.yasminishop.common.exception.appexception;
import com.learning.yasminishop.common.exception.errorcode;
import com.learning.yasminishop.product.productrepository;
import com.learning.yasminishop.product.dto.response.productresponse;
import com.learning.yasminishop.product.mapper.productmapper;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.stereotype.service;
import org.springframework.transaction.annotation.transactional;
import org.springframework.web.multipart.multipartfile;

import java.util.hashset;
import java.util.list;
import java.util.objects;
import java.util.set;

@service
@requiredargsconstructor
@slf4j
@transactional(readonly = true)
public class yasminiaiservice {

    private final generativemodel generativemodel;
    private final productrepository productrepository;

    private final productmapper productmapper;


    public list<productresponse> findcarbyimage(multipartfile file){
        try {
            var prompt = "extract the name car to a list keyword and output them in json. if you don't find any information about the car, please output the list empty.\nexample response: [\"rolls\", \"royce\", \"wraith\"]";
            var content = this.generativemodel.generatecontent(
                    contentmaker.frommultimodaldata(
                            partmaker.frommimetypeanddata(objects.requirenonnull(file.getcontenttype()), file.getbytes()),
                            prompt
                    )
            );

            string jsoncontent = responsehandler.gettext(content);
            log.info("extracted keywords from image: {}", jsoncontent);
            list<string> keywords = convertjsontolist(jsoncontent).stream()
                    .map(string::tolowercase)
                    .tolist();

            set<product> results = new hashset<>();
            for (string keyword : keywords) {
                list<product> products = productrepository.searchbykeyword(keyword);
                results.addall(products);
            }

            return results.stream()
                    .map(productmapper::toproductresponse)
                    .tolist();

        } catch (exception e) {
            log.error("error finding car by image", e);
            return list.of();
        }
    }

    private list<string> convertjsontolist(string markdown) throws jsonprocessingexception {
        objectmapper objectmapper = new objectmapper();
        string parsejson = markdown;
        if(markdown.contains("```

json")){
            parsejson = extractjsonfrommarkdown(markdown);
        }
        return objectmapper.readvalue(parsejson, list.class);
    }

    private string extractjsonfrommarkdown(string markdown) {
        return markdown.replace("

```json\n", "").replace("\n```

", "");
    }
}


我们需要创建一个控制器类来为前端做一个端点


import com.learning.yasminishop.product.dto.response.productresponse;
import lombok.requiredargsconstructor;
import lombok.extern.slf4j.slf4j;
import org.springframework.security.access.prepost.preauthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;

import java.util.list;

@restcontroller
@requestmapping("/ai")
@requiredargsconstructor
@slf4j
public class yasminiaicontroller {

    private final yasminiaiservice yasminiaiservice;


    @postmapping
    public list<productresponse> findcar(@requestparam("file") multipartfile file) {

        var response = yasminiaiservice.findcarbyimage(file);
        return response;
    }
}



5. 重要步骤:使用 google cloud cli 登录 google cloud

spring boot 应用程序无法验证您的身份,并且无法让您接受 google cloud 中的资源。

所以我们需要登录google并提供授权。

5.1 首先我们需要在您的机器上安装gcloud cli

教程链接:https://cloud.google.com/sdk/docs/install
检查上面的链接并将其安装到您的机器上

5.2 登录

  1. 在项目中打开你的终端(你必须 cd 进入项目)
  2. 类型:gcloud auth login
  3. 输入,就会看到允许登录的窗口

gcloud auth login


使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索

注意: 登录后,凭据会保存在 google maven 包中,重启 spring boot 应用程序时无需再次登录。

结论

所以上面这些都是基于我的电子商务项目实现的,你可以根据你的项目、你的框架进行修改。在其他框架中,除了 spring boot(nestjs,..),您可以使用 https://aistudio.google.com/app/prompts/new_chat。并且不需要创建新的 google cloud 帐户。

具体实现可以在我的repo查看:

后端:https://github.com/duongminhhieu/yasminishop
前端:https://github.com/duongminhhieu/yasmini-frontend

学习愉快!!!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
spring框架介绍
spring框架介绍

本专题整合了spring框架相关内容,想了解更多详细内容,请阅读专题下面的文章。

160

2025.08.06

Java Spring Security 与认证授权
Java Spring Security 与认证授权

本专题系统讲解 Java Spring Security 框架在认证与授权中的应用,涵盖用户身份验证、权限控制、JWT与OAuth2实现、跨站请求伪造(CSRF)防护、会话管理与安全漏洞防范。通过实际项目案例,帮助学习者掌握如何 使用 Spring Security 实现高安全性认证与授权机制,提升 Web 应用的安全性与用户数据保护。

88

2026.01.26

spring boot框架优点
spring boot框架优点

spring boot框架的优点有简化配置、快速开发、内嵌服务器、微服务支持、自动化测试和生态系统支持。本专题为大家提供spring boot相关的文章、下载、课程内容,供大家免费下载体验。

139

2023.09.05

spring框架有哪些
spring框架有哪些

spring框架有Spring Core、Spring MVC、Spring Data、Spring Security、Spring AOP和Spring Boot。详细介绍:1、Spring Core,通过将对象的创建和依赖关系的管理交给容器来实现,从而降低了组件之间的耦合度;2、Spring MVC,提供基于模型-视图-控制器的架构,用于开发灵活和可扩展的Web应用程序等。

408

2023.10.12

Java Spring Boot开发
Java Spring Boot开发

本专题围绕 Java 主流开发框架 Spring Boot 展开,系统讲解依赖注入、配置管理、数据访问、RESTful API、微服务架构与安全认证等核心知识,并通过电商平台、博客系统与企业管理系统等项目实战,帮助学员掌握使用 Spring Boot 快速开发高效、稳定的企业级应用。

73

2025.08.19

Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性
Java Spring Boot 4更新教程_Java Spring Boot 4有哪些新特性

Spring Boot 是一个基于 Spring 框架的 Java 开发框架,它通过 约定优于配置的原则,大幅简化了 Spring 应用的初始搭建、配置和开发过程,让开发者可以快速构建独立的、生产级别的 Spring 应用,无需繁琐的样板配置,通常集成嵌入式服务器(如 Tomcat),提供“开箱即用”的体验,是构建微服务和 Web 应用的流行工具。

150

2025.12.22

Java Spring Boot 微服务实战
Java Spring Boot 微服务实战

本专题深入讲解 Java Spring Boot 在微服务架构中的应用,内容涵盖服务注册与发现、REST API开发、配置中心、负载均衡、熔断与限流、日志与监控。通过实际项目案例(如电商订单系统),帮助开发者掌握 从单体应用迁移到高可用微服务系统的完整流程与实战能力。

271

2025.12.24

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

32

2026.02.11

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

37

2026.03.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 4.2万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.6万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 94人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号