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

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

Aug 14, 2024 am 10:35 AM

介绍

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

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

", "");
    }
}


登录后复制

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


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 登录
  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

热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

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

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1669
14
CakePHP 教程
1428
52
Laravel 教程
1329
25
PHP教程
1273
29
C# 教程
1256
24
公司安全软件导致应用无法运行?如何排查和解决? 公司安全软件导致应用无法运行?如何排查和解决? Apr 19, 2025 pm 04:51 PM

公司安全软件导致部分应用无法正常运行的排查与解决方法许多公司为了保障内部网络安全,会部署安全软件。...

如何将姓名转换为数字以实现排序并保持群组中的一致性? 如何将姓名转换为数字以实现排序并保持群组中的一致性? Apr 19, 2025 pm 11:30 PM

将姓名转换为数字以实现排序的解决方案在许多应用场景中,用户可能需要在群组中进行排序,尤其是在一个用...

如何使用MapStruct简化系统对接中的字段映射问题? 如何使用MapStruct简化系统对接中的字段映射问题? Apr 19, 2025 pm 06:21 PM

系统对接中的字段映射处理在进行系统对接时,常常会遇到一个棘手的问题:如何将A系统的接口字段有效地映�...

IntelliJ IDEA是如何在不输出日志的情况下识别Spring Boot项目的端口号的? IntelliJ IDEA是如何在不输出日志的情况下识别Spring Boot项目的端口号的? Apr 19, 2025 pm 11:45 PM

在使用IntelliJIDEAUltimate版本启动Spring...

如何优雅地获取实体类变量名构建数据库查询条件? 如何优雅地获取实体类变量名构建数据库查询条件? Apr 19, 2025 pm 11:42 PM

在使用MyBatis-Plus或其他ORM框架进行数据库操作时,经常需要根据实体类的属性名构造查询条件。如果每次都手动...

Java对象如何安全地转换为数组? Java对象如何安全地转换为数组? Apr 19, 2025 pm 11:33 PM

Java对象与数组的转换:深入探讨强制类型转换的风险与正确方法很多Java初学者会遇到将一个对象转换成数组的�...

电商平台SKU和SPU数据库设计:如何兼顾用户自定义属性和无属性商品? 电商平台SKU和SPU数据库设计:如何兼顾用户自定义属性和无属性商品? Apr 19, 2025 pm 11:27 PM

电商平台SKU和SPU表设计详解本文将探讨电商平台中SKU和SPU的数据库设计问题,特别是如何处理用户自定义销售属...

如何利用Redis缓存方案高效实现产品排行榜列表的需求? 如何利用Redis缓存方案高效实现产品排行榜列表的需求? Apr 19, 2025 pm 11:36 PM

Redis缓存方案如何实现产品排行榜列表的需求?在开发过程中,我们常常需要处理排行榜的需求,例如展示一个�...

See all articles