104 lines
5.0 KiB
Python
104 lines
5.0 KiB
Python
import os
|
|
import json
|
|
import sys
|
|
import logging
|
|
import asyncio
|
|
|
|
from vertexai.generative_models import GenerativeModel
|
|
|
|
class VertexAITranslator:
|
|
def __init__(self, logger):
|
|
"""
|
|
VertexAITranslator 클래스 초기화 메서드.
|
|
|
|
:param logger: 로깅을 위한 로거 객체.
|
|
"""
|
|
self.logger = logger
|
|
key_path = self.get_key_path('leensoo1nt.json')
|
|
|
|
# GOOGLE_APPLICATION_CREDENTIALS 환경 변수 설정
|
|
self.logger.debug(f"GOOGLE_APPLICATION_CREDENTIALS 환경 변수를 설정: {key_path}")
|
|
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = key_path
|
|
|
|
# GenerativeModel 객체 초기화
|
|
self.logger.debug("Vertex AI 모델 초기화 중...")
|
|
self.model = GenerativeModel("gemini-1.5-flash-001")
|
|
|
|
def get_key_path(self, key_path):
|
|
# cx_Freeze로 패키징된 경우 실행 파일 경로로 설정
|
|
if getattr(sys, 'frozen', False):
|
|
return os.path.join(os.path.dirname(sys.executable), key_path)
|
|
else:
|
|
# 일반 Python 실행 환경일 경우
|
|
return os.path.join(os.path.dirname(__file__), key_path)
|
|
|
|
async def generate_optimized_product_name(self, original_name, naver_name):
|
|
"""
|
|
원본 상품명과 네이버 상품명을 비교하여, 매칭이 성공적인 경우 새 상품명을 생성하는 메서드.
|
|
|
|
:param original_name: 원본 상품명 (str 형태).
|
|
:param naver_name: 네이버 상품명 (str 형태).
|
|
:return: 매칭 여부와 새로운 상품명 (매칭 시: "Match: 생성된 상품명", 매칭 실패 시: "Mismatch").
|
|
"""
|
|
self.logger.debug(f"상품 매칭 여부 확인 및 새로운 상품명 생성 중: 원본명({original_name}) - 네이버명({naver_name})")
|
|
|
|
# 프롬프트 생성
|
|
prompt_template = (
|
|
"You are tasked with determining if a product on the Taobao platform matches the existing product name "
|
|
"as it appears in the Korean market. Review the names provided and determine if the Taobao product and "
|
|
"the Naver product share enough similarity in purpose, function, and type to be sold under a common name.\n\n"
|
|
"If they are similar:\n"
|
|
"1. Begin the new Korean product name using the first 3-4 words from the Naver product name to keep consistency in main product categories.\n"
|
|
"2. For the rest of the product name, incorporate specific details and features directly from the Taobao product name that highlight its unique options or characteristics.\n"
|
|
"3. Provide a concise, clear, and market-appropriate Korean product name that reflects both the familiarity of the Naver product's introductory words and the specific features of the Taobao product.\n\n"
|
|
"If they are not similar, respond with 'Mismatch.'\n\n"
|
|
"Original Taobao Product Name: {original_name}\n"
|
|
"Existing Naver Product Name: {naver_name}\n\n"
|
|
"Response:\n"
|
|
"- 'Match': [Generated Korean Product Name]\n"
|
|
"- 'Mismatch'"
|
|
)
|
|
|
|
prompt = prompt_template.format(original_name=original_name, naver_name=naver_name)
|
|
self.logger.debug(f"생성된 프롬프트: {prompt}")
|
|
|
|
# Vertex AI 모델에 프롬프트 전달하여 응답 받기
|
|
self.logger.debug("Vertex AI 모델에 프롬프트를 전달하여 응답을 기다리는 중...")
|
|
response = self.model.generate_content(prompt)
|
|
self.logger.debug(f"모델 응답: {response.text.strip()}")
|
|
|
|
# 응답 처리
|
|
result = response.text.strip()
|
|
if result.startswith("Match:"):
|
|
# 'Match:' 이후의 상품명만 추출
|
|
product_name = result.split("Match:")[1].strip().splitlines()[0]
|
|
self.logger.debug(f"상품이 매칭되어 새로운 상품명을 생성했습니다: {product_name}")
|
|
return f"Match: {product_name}"
|
|
elif result == "Mismatch":
|
|
self.logger.debug("상품이 매칭되지 않아 처리를 중지합니다.")
|
|
return "Mismatch"
|
|
else:
|
|
self.logger.error("예상치 못한 응답을 수신했습니다. 응답 텍스트: " + result)
|
|
raise ValueError("예상치 못한 응답 형식으로 인해 상품명 생성 불가.")
|
|
|
|
|
|
# 사용 예시:
|
|
# 로그 설정
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# VertexAITranslator 클래스 초기화 및 사용 예시
|
|
async def main():
|
|
translator = VertexAITranslator(logger)
|
|
|
|
# 원본 상품명과 네이버 상품명 설정
|
|
original_name = "石墨烯宽条电热膜家用电暖炕速热瑜伽馆地暖电热板远红外安装包邮"
|
|
naver_name = "전기난방기 강화 마루 판넬 접선벨트 X1.75m 섬유 2.6m 듀얼 컨테이너 탄소 컨트롤"
|
|
|
|
# generate_optimized_product_name 메서드 호출 및 결과 출력
|
|
result = await translator.generate_optimized_product_name(original_name, naver_name)
|
|
print("결과:", result)
|
|
|
|
# 비동기 실행
|
|
asyncio.run(main())
|