O2Sound_ver2_final/backend/app/services/chatgpt_service.py

167 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

from openai import OpenAI
# from app.infra.crawling.crawler_service import get_place_name_from_url
from app.shared.logger import setup_logger
from app.core.env_setting import EnvSetting
import re
logger = setup_logger(__name__)
settings = EnvSetting()
class ChatgptService:
def __init__(self):
self.model = "gpt-4o"
self.client = OpenAI(api_key=settings.OPENAI_API_KEY)
self.kt_client = OpenAI(
base_url=settings.OPENAI_MIDM_BASE_URL,
api_key=settings.OPENAI_MEDIM_API_KEY
)
self.vllm_model = settings.OPENAI_MEDIM_MODEL
def lyrics_prompt(self, name, address, category, description):
prompt = f'''
반드시 한국어로 답변해주세요.
당신은 작곡가 입니다.
작곡에 대한 영감을 얻기 위해 제가 정보를 제공할게요.
업체 이름 : {name}
업체 주소 : {address}
업체 카테고리 : {category}
업체 설명 : {description}
위의 정보를 토대로 작곡을 이어나가주세요.
다음은 노래에 대한 정보입니다.
노래의 길이 : 30초 이내입니다.
노래의 특징:
- 노래에 업체의 이름은 반드시 1번 이상 들어가야 합니다.
- 노래의 전반부는, 업체에 대한 장점과 특징을 소개하는 가사를 써주세요.
- 노래의 후반부는, 업체가 위치한 곳을 소개하는 가사를 써주세요.
답변에 [전반부], [후반부] 표시할 필요 없이, 가사만 답변해주세요.
'''
return prompt
def tags_prompt(self, name, address, category, description):
prompt = f'''
반드시 한국어로 답변해주세요.
다음은 한 업체의 정보입니다. 이 내용을 바탕으로 인스타그램 또는 블로그에서 활용할 수 있는 해시태그를 5~10개 추출해주세요. 각 해시태그는 키워드를 기반으로 간결하면서도 검색에 유리해야 하며, "#" 기호를 포함해 출력해주세요.
업체 이름: {name}
업체 주소: {address}
업체 카테고리: {category}
업체 설명: {description}
결과는 아래 형식으로 출력해주세요:
#예시1 #예시2 #예시3 ...
'''
return prompt
def generate_lyrics(self, name, address, category, description, ai_model):
prompt = self.lyrics_prompt(name, address, category, description)
# kt openai 모델 사용
if ai_model == "kt-midm":
try:
kt_midm_completion = self.kt_client.chat.completions.create(
model=self.vllm_model,
messages=[{"role": "user", "content": prompt}]
)
kt_midm_message = kt_midm_completion.choices[0].message.content
return kt_midm_message
except Exception as e:
logger.info(f"kt-midm 가사 생성 실패: {e}, ChatGPT로 대체합니다.")
# kt-midm 실패 시 ChatGPT로 폴백
completion = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
message = completion.choices[0].message.content
return message
# chatgpt 모델 사용
else:
completion = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
message = completion.choices[0].message.content
return message
def extract_tag(self, name, address, category, description):
prompt = self.tags_prompt(name, address, category, description)
try:
completion = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}]
)
result = completion.choices[0].message.content.strip()
if not result:
raise ValueError("빈 응답입니다.")
# 1. 해시태그 추출 (문자열 -> 리스트)
tags = re.findall(r"#\w+", result)
# 2. 빈 배열이면 실패로 처리
if not tags:
raise ValueError("해시태그를 찾을 수 없습니다.")
return tags
except Exception as e:
raise Exception(f"해시태그 추출 실패: {e}")
# 테스트를 위한 메인 함수
# def main():
# """generate_lyrics 함수를 테스트합니다."""
# # 테스트용 데이터
# test_name = "리사르커피 문정점"
# test_address = "서울 송파구 법원로11길 11 B동 153호"
# test_category = "카페,디저트"
# test_description = "에스프레소가 우리에게 가장 큰 가치이고 목표였다면, 이제는 에스프레소 보다 더 나은, 무한한 가치를 좇는다. 하나님을 사랑하고 나를 사랑하듯 이웃을 사랑하는 보이지 않는 가치에 집중한다."
# # ChatgptService 인스턴스 생성
# service = ChatgptService()
# print("=" * 50)
# print("가사 생성 테스트 시작")
# print("=" * 50)
# print(f"\n업체 정보:")
# print(f" - 이름: {test_name}")
# print(f" - 주소: {test_address}")
# print(f" - 카테고리: {test_category}")
# print(f" - 설명: {test_description}")
# print("\n" + "=" * 50)
# # KT-MIDM 모델로 가사 생성 (설정되어 있다면)
# try:
# print("\n[KT-MIDM 모델로 가사 생성 중...]")
# lyrics_kt = service.generate_lyrics(
# name=test_name,
# address=test_address,
# category=test_category,
# description=test_description,
# ai_model=""
# )
# print("\n생성된 가사 (KT-MIDM):")
# print("-" * 50)
# print(lyrics_kt)
# print("-" * 50)
# except Exception as e:
# print(f"\n⚠ KT-MIDM 모델 사용 불가 (설정되지 않았거나 오류 발생): {e}")
# print("\n" + "=" * 50)
# print("테스트 완료")
# print("=" * 50)
# if __name__ == "__main__":
# main()