165 lines
8.1 KiB
Python
165 lines
8.1 KiB
Python
import re
|
|
from typing import List
|
|
from datetime import datetime
|
|
from collections import OrderedDict
|
|
from translatepy import Translator # 번역 라이브러리 예시
|
|
|
|
class TitleGenerator:
|
|
def __init__(self, forbidden_word_manager, naver_parser, kipris_api, gpt_client):
|
|
self.forbidden_word_manager = forbidden_word_manager
|
|
self.naver_parser = naver_parser
|
|
self.kipris_api = kipris_api
|
|
self.gpt_client = gpt_client
|
|
self.translator = Translator() # 번역 라이브러리 초기화
|
|
|
|
def translate_product_name(self, original_name: str) -> str:
|
|
"""텍스트를 한국어로 번역하는 메서드"""
|
|
try:
|
|
result = self.translator.translate(original_name, "ko")
|
|
return result.result if result else original_name
|
|
except Exception as e:
|
|
print(f"번역 중 오류 발생: {e}")
|
|
return original_name
|
|
|
|
def is_word_forbidden(self, word: str) -> bool:
|
|
"""금지어 매니저를 통해 단어가 금지어인지 확인"""
|
|
return self.forbidden_word_manager.is_word_forbidden(word)
|
|
|
|
def search_trademark(self, word: str) -> dict:
|
|
"""키프리스 API로 단어를 검색하는 메서드"""
|
|
return self.kipris_api.search_trademark(word)
|
|
|
|
def is_valid_word(self, word: str) -> bool:
|
|
"""숫자로만 이루어진 단어 또는 영어와 숫자로만 이루어진 단어를 검증하는 함수."""
|
|
return not (word.isdigit() or re.fullmatch(r'[A-Za-z0-9]+', word))
|
|
|
|
def extract_special_words(self, original_name: str) -> list:
|
|
"""원본 상품명에서 숫자로만 이루어진 단어와 영어와 숫자로만 이루어진 단어를 추출하는 함수."""
|
|
return [word for word in original_name.split() if word.isdigit() or re.fullmatch(r'[A-Za-z0-9]+', word)]
|
|
|
|
def filter_invalid_words(self, words: list) -> list:
|
|
"""영어만 이루어진 단어와 영어와 숫자로 이루어진 단어를 제외하는 함수."""
|
|
return [word for word in words if not re.fullmatch(r'[A-Za-z0-9]+', word)]
|
|
|
|
def process_top_titles(self, top_titles: list) -> list:
|
|
"""top_titles에서 유효하지 않은 단어(영어만 이루어진 단어와 영어와 숫자로 이루어진 단어)를 제외하는 함수."""
|
|
filtered_titles = []
|
|
for title in top_titles:
|
|
filtered_words = self.filter_invalid_words(title.split())
|
|
filtered_titles.append(' '.join(filtered_words))
|
|
return filtered_titles
|
|
|
|
def generate_product_title(self, original_name: str, keyword_name: str) -> str:
|
|
"""상품명을 생성하는 메서드"""
|
|
# 1. 원본 상품명 번역 및 관련성 판단
|
|
translated_name = self.translate_product_name(original_name)
|
|
print(f'translated_name : {translated_name}')
|
|
is_related = self.gpt_client.is_related_product(translated_name, keyword_name)
|
|
|
|
if not is_related:
|
|
return "관련성이 없습니다."
|
|
|
|
# 2. 키워드 상품명으로 검색 및 단어 리스트 생성
|
|
search_result = self.naver_parser.search_and_parse(keyword_name.split()[:4])
|
|
print(f'naver_parser search_result : {search_result}')
|
|
|
|
# top_titles = search_result["top_products"]
|
|
top_titles = [item['title'] for item in search_result["top_products"]]
|
|
print(f'top_titles : {top_titles}')
|
|
|
|
top_titles = self.process_top_titles(top_titles)
|
|
|
|
keyword_title = list(set(
|
|
word for title in [keyword_name] + top_titles # top_titles는 이미 문자열 리스트
|
|
for word in title.split()
|
|
))
|
|
print(f'keyword_title : {keyword_title}')
|
|
|
|
# 3. 숫자나 영어와 숫자로만 이루어진 단어 필터링
|
|
keyword_title = [word for word in keyword_title if self.is_valid_word(word)]
|
|
print(f'keyword_title after filtering invalid words : {keyword_title}')
|
|
|
|
# 4. 금지어 필터링
|
|
keyword_title = [word for word in keyword_title if not self.is_word_forbidden(word)]
|
|
print(f'keyword_title after forbidden filter : {keyword_title}')
|
|
|
|
# 4. 고유명사 추출 및 Kipris 검색 후 금지어 등록
|
|
kipris_word = self.gpt_client.extract_proper_nouns(keyword_title)
|
|
print(f'kipris_word : {kipris_word}')
|
|
|
|
# 고유명사 추출 결과가 keyword_title의 단어와 겹치는지 확인
|
|
if not any(word in kipris_word for word in keyword_title):
|
|
print("No proper nouns found in the keyword_title. Skipping Kipris search.")
|
|
final_keywords = keyword_title # 고유명사가 없으면 keyword_title 그대로 사용
|
|
else:
|
|
final_keywords = []
|
|
for word in kipris_word:
|
|
result_list = self.search_trademark(word)
|
|
print(f'kipris_word for search_trademark result: {result_list}')
|
|
|
|
is_registered = False
|
|
for result in result_list:
|
|
if result.get("application_status") in ["등록", "공개"]:
|
|
is_registered = True
|
|
self.forbidden_word_manager.register_word(
|
|
word=word,
|
|
has_trademark=True,
|
|
category_code=result.get("category_code", ""),
|
|
category_description=result.get("category_description", ""),
|
|
registrant=result.get("registrant", ""),
|
|
registration_date=result.get("registration_date", "")
|
|
)
|
|
print(f'registered forbidden word: {word}')
|
|
|
|
if not is_registered:
|
|
final_keywords.append(word)
|
|
print(f'added to final_keywords: {word}')
|
|
|
|
# 5. 최종 keyword_title에서 kipris_word 제거
|
|
keyword_title = [word for word in keyword_title if word in final_keywords]
|
|
print(f'final keyword_title after Kipris search: {keyword_title}')
|
|
|
|
# 6. 최종 단어 리스트에서 '숫자 또는 영어와 숫자로만 이루어진 단어' 제외
|
|
keyword_title = [word for word in keyword_title if word in final_keywords]
|
|
print(f'final keyword_title after Kipris search: {keyword_title}')
|
|
|
|
# 7. 원본 상품명에서 숫자 또는 영어와 숫자로만 이루어진 단어 추출 및 포함
|
|
special_words = self.extract_special_words(original_name)
|
|
print(f'special_words from original_name: {special_words}')
|
|
keyword_title.extend(special_words)
|
|
|
|
# 8. 중복 제거 후 최종 리스트 생성
|
|
keyword_title = list(set(keyword_title))
|
|
print(f'final keyword_title including special words: {keyword_title}')
|
|
|
|
# 9. 최종 상품명 생성
|
|
product_title = self.gpt_client.generate_product_name(words=keyword_title, original_name=original_name, top_titles=top_titles)
|
|
print(f'final product_title: {product_title}')
|
|
|
|
return product_title
|
|
|
|
|
|
from gpt_client import GPTClient
|
|
from mongoDBManager import MongoDBManager
|
|
from forbiddenWD_Manager import ForbiddenWordManager
|
|
from naver_parser import NaverParser
|
|
from kiprisAPI import Kipris_API
|
|
|
|
if __name__ == "__main__":
|
|
# 객체 생성
|
|
db_manager = MongoDBManager(db_url='mongodb://root:1234@cckb9998.synology.me:27017/')
|
|
forbidden_manager = ForbiddenWordManager(db_manager)
|
|
naver_parser = NaverParser()
|
|
kipris_api = Kipris_API(apikey='X9Tz3JqC/JcCwxnNewA6qdloIN6QFIitVBgS1a2KVDYk1AmddaDTvzr6+t3dyLZV3gh2TPXdNhxsRQwaKP673Q==')
|
|
gpt_client = GPTClient(api_key="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")
|
|
|
|
# TitleGenerator 객체 생성
|
|
title_generator = TitleGenerator(forbidden_manager, naver_parser, kipris_api, gpt_client)
|
|
|
|
# 상품명 생성
|
|
product_title = title_generator.generate_product_title("10升15升压力桶W-77加长杆喷枪水包水砂多彩油漆乳胶漆涂料喷漆枪", "페인트후끼")
|
|
print("생성된 상품명:", product_title)
|
|
|
|
# DB 연결 종료
|
|
db_manager.close_connection()
|