>  기사  >  Java  >  Spring Boot, Google Cloud Vertex AI 및 Gemini 모델을 사용한 이미지 기반 상품 검색

Spring Boot, Google Cloud Vertex AI 및 Gemini 모델을 사용한 이미지 기반 상품 검색

WBOY
WBOY원래의
2024-08-14 10:35:301057검색

소개

온라인 쇼핑을 하다가 마음에 드는 제품을 발견했지만 이름은 모른다고 상상해 보세요. 사진을 업로드하고 앱에서 사진을 찾아준다면 정말 멋지지 않을까요?

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

이 기사에서는 Spring Boot와 Google Cloud Vertex AI를 사용한 이미지 기반 제품 검색 기능을 정확하게 구축하는 방법을 보여 드리겠습니다.

기능 개요

이 기능을 사용하면 사용자가 이미지를 업로드하고 이에 맞는 제품 목록을 받을 수 있어 검색 환경이 더욱 직관적이고 시각적으로 향상됩니다.

이미지 기반 상품 검색 기능은 Google Cloud Vertex AI를 활용하여 이미지를 처리하고 관련 키워드를 추출합니다. 그런 다음 이러한 키워드는 데이터베이스에서 일치하는 제품을 검색하는 데 사용됩니다.

기술 스택

  • 자바 21
  • 스프링부트 3.2.5
  • 포스트그레SQL
  • 버텍스 AI
  • ReactJS

이 기능을 설정하는 과정을 단계별로 살펴보겠습니다.

단계별 구현

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

1. Google 콘솔에서 새 프로젝트 만들기

먼저 이를 위해 Google 콘솔에서 새 프로젝트를 만들어야 합니다.

이미 계정이 있는 경우 https://console.cloud.google.com으로 이동하여 새 계정을 만들어야 합니다. 계정이 있는 경우 해당 계정에 로그인하세요.

은행 계좌를 추가하면 Google Cloud에서 무료 평가판을 제공합니다.

계정을 만들거나 기존 계정에 로그인한 후 새 프로젝트를 만들 수 있습니다.

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

2. Vertex AI 서비스 활성화

검색창에서 Vertex AI를 찾아 모든 권장 API를 활성화해야 합니다.

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

Vertex AI는 ML 모델의 개발, 배포, 관리를 단순화하도록 설계된 Google Cloud의 완전 관리형 머신러닝(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. 스프링 부트 애플리케이션과 통합

자동차에 관한 전자상거래 애플리케이션을 구축했습니다. 그래서 이미지로 자동차를 찾아보고 싶어요.

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는 마크다운 형식으로 응답하기 때문에 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 인증 로그인
  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 애플리케이션을 다시 시작할 때 다시 로그인할 필요가 없습니다.

결론

따라서 내 프로젝트 E-Commerce를 기반으로 위의 구현을 수행하면 프로젝트 및 프레임워크와 일치하도록 수정할 수 있습니다. 스프링 부트(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으로 문의하세요.