搜尋
首頁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:updatebybytecodeforsimultanane deployment.3)testOnOneOnePlatForforurouniverSalpeforuluniverSalpehavior formafforulululyiversalivernave.444.44.444

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

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。