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

介绍

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

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

在本文中,我们将向您展示如何构建这一功能:使用 Spring Boot 和 Google Cloud Vertex AI 的基于图像的产品搜索功能。

功能概述

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

基于图像的产品搜索功能利用 Google Cloud Vertex AI 处理图像并提取相关关键字。然后使用这些关键字在数据库中搜索匹配的产品。

技术栈

  • Java 21
  • Spring 启动 3.2.5
  • PostgreSQL
  • 顶点人工智能
  • ReactJS

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

逐步实施

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

1. 在Google Console上创建一个新项目

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

我们需要访问 https://console.cloud.google.com 并创建一个新帐户(如果您已有帐户)。如果您有,请登录该帐户。

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

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

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

2. 启用顶点AI服务

在搜索栏上,我们需要找到 Vertex AI 并启用所有推荐的 API。

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

Vertex AI 是 Google Cloud 完全托管的机器学习 (ML) 平台,旨在简化 ML 模型的开发、部署和管理。它允许您通过提供 AutoML、自定义模型训练、超参数调整和模型监控等工具和服务来大规模构建、训练和部署 ML 模型

Gemini 1.5 Flash 是 Google Gemini 系列模型的一部分,专为 ML 应用程序中的高效和高性能推理而设计。 Gemini 模型是 Google 开发的一系列高级 AI 模型,常用于自然语言处理 (NLP)、视觉任务和其他 AI 驱动的应用

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

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

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

Vertex AI Studio 在提示库提供了很多示例提示。我们使用示例图像文本到JSON来提取与产品图像相关的关键字。

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

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

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

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

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

4. 与 Spring Boot 应用程序集成

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

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

首先,在 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”
  • 位置:“设置项目时您的位置”
  • PROJECT_ID:“您的项目 ID”

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

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 字符串。

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

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```

", "");
    }
}


</string></product></product></string></productresponse>

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


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;
    }
}



</productresponse>

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 登录
  3. 输入,您将看到允许登录的窗口

gcloud auth login


Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model

注意:登录后,凭据将保存在 Google Maven 包中,重启 Spring Boot 应用程序时无需再次登录。

结论

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

具体实现可以在我的仓库中查看:

后端:https://github.com/duongminhhieu/YasMiniShop
前端:https://github.com/duongminhhieu/YasMini-Frontend

学习愉快!!!

以上是使用 Spring Boot、Google Cloud Vertex AI 和 Gemini 模型进行基于图像的产品搜索的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?JVM如何促进Java的'写作一次,在任何地方运行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通过字节码解释、平台无关的API和动态类加载实现Java的WORA特性:1.字节码被解释为机器码,确保跨平台运行;2.标准API抽象操作系统差异;3.类在运行时动态加载,保证一致性。

Java的较新版本如何解决平台特定问题?Java的较新版本如何解决平台特定问题?May 02, 2025 am 12:18 AM

Java的最新版本通过JVM优化、标准库改进和第三方库支持有效解决平台特定问题。1)JVM优化,如Java11的ZGC提升了垃圾回收性能。2)标准库改进,如Java9的模块系统减少平台相关问题。3)第三方库提供平台优化版本,如OpenCV。

说明JVM执行的字节码验证的过程。说明JVM执行的字节码验证的过程。May 02, 2025 am 12:18 AM

JVM的字节码验证过程包括四个关键步骤:1)检查类文件格式是否符合规范,2)验证字节码指令的有效性和正确性,3)进行数据流分析确保类型安全,4)平衡验证的彻底性与性能。通过这些步骤,JVM确保只有安全、正确的字节码被执行,从而保护程序的完整性和安全性。

平台独立性如何简化Java应用程序的部署?平台独立性如何简化Java应用程序的部署?May 02, 2025 am 12:15 AM

Java'splatFormIndepentEncealLowsApplicationStorunonAnyOperatingsystemwithajvm.1)singleCodeBase:writeandeandcompileonceforallplatforms.2)easileupdates:updatebybytecodeforsimultaneDeployment.3)testOnOneOnePlatForforuluniverSalpeforuluniverSaliver.4444.4444

Java的平台独立性如何随着时间的流逝而发展?Java的平台独立性如何随着时间的流逝而发展?May 02, 2025 am 12:12 AM

Java的平台独立性通过JVM、JIT编译、标准化、泛型、lambda表达式和ProjectPanama等技术不断增强。自1990年代以来,Java从基本的JVM演进到高性能的现代JVM,确保了代码在不同平台的一致性和高效性。

在Java应用程序中缓解平台特定问题的策略是什么?在Java应用程序中缓解平台特定问题的策略是什么?May 01, 2025 am 12:20 AM

Java如何缓解平台特定的问题?Java通过JVM和标准库来实现平台无关性。1)使用字节码和JVM抽象操作系统差异;2)标准库提供跨平台API,如Paths类处理文件路径,Charset类处理字符编码;3)实际项目中使用配置文件和多平台测试来优化和调试。

Java的平台独立性与微服务体系结构之间有什么关系?Java的平台独立性与微服务体系结构之间有什么关系?May 01, 2025 am 12:16 AM

java'splatformentenceenhancesenhancesmicroservicesharchitecture byferingDeploymentFlexible,一致性,可伸缩性和便携性。1)DeploymentFlexibilityAllowsibilityAllowsOllowsOllowSorlowsOllowsOllowsOllowSeStorunonAnyPlatformwithajvM.2)penterencyCrossServAccAcrossServAcrossServiCessImplifififiesDeevelopmentandeDe

GRAALVM与Java的平台独立目标有何关系?GRAALVM与Java的平台独立目标有何关系?May 01, 2025 am 12:14 AM

GraalVM通过三种方式增强了Java的平台独立性:1.跨语言互操作,允许Java与其他语言无缝互操作;2.独立的运行时环境,通过GraalVMNativeImage将Java程序编译成本地可执行文件;3.性能优化,Graal编译器生成高效的机器码,提升Java程序的性能和一致性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器