범용 프롬프트 적용
This commit is contained in:
1 parent
8415e1c3a7
commit
04d8614919
18 files changed
+140
-85
No files matched your search
@@ -1,3 +1,5 @@
|
||||
import re
|
||||
|
||||
import gspread
|
||||
from pydantic import BaseModel
|
||||
from google.oauth2.service_account import Credentials
|
||||
@@ -6,6 +8,9 @@ from app.utils.logger import get_logger
|
||||
from app.utils.prompts.schemas import *
|
||||
from functools import lru_cache
|
||||
|
||||
# {known_field} 형태만 치환하기 위한 패턴. JSON 예시 등 리터럴 중괄호는 보존된다.
|
||||
_PLACEHOLDER_RE = re.compile(r"\{(\w+)\}")
|
||||
|
||||
logger = get_logger("prompt")
|
||||
|
||||
_SCOPES = [
|
||||
@@ -15,15 +20,33 @@ _SCOPES = [
|
||||
_sheet_cache: dict[str, tuple[str, str]] = {}
|
||||
|
||||
|
||||
def _get_spreadsheet():
|
||||
creds = Credentials.from_service_account_file(
|
||||
prompt_settings.GOOGLE_SERVICE_ACCOUNT_JSON, scopes=_SCOPES
|
||||
)
|
||||
return gspread.authorize(creds).open_by_key(prompt_settings.PROMPT_SPREADSHEET)
|
||||
|
||||
|
||||
def _preload_all_sheets(sheet_names: list[str]):
|
||||
ranges = [f"{name}!B2:B3" for name in sheet_names]
|
||||
response = _get_spreadsheet().values_batch_get(ranges)
|
||||
for value_range in response["valueRanges"]:
|
||||
range_name = value_range.get("range", "")
|
||||
name = range_name.split("!")[0].strip("'")
|
||||
if name not in sheet_names:
|
||||
continue
|
||||
values = value_range.get("values", [])
|
||||
if len(values) < 2 or not values[0] or not values[1]:
|
||||
logger.warning(f"Sheet '{name}' has missing data, skipping preload")
|
||||
continue
|
||||
_sheet_cache[name] = (values[1][0], values[0][0]) # (B3=template, B2=model)
|
||||
|
||||
|
||||
def _read_sheet_data(sheet_name: str) -> tuple[str, str]:
|
||||
if sheet_name not in _sheet_cache:
|
||||
creds = Credentials.from_service_account_file(
|
||||
prompt_settings.GOOGLE_SERVICE_ACCOUNT_JSON, scopes=_SCOPES
|
||||
)
|
||||
gc = gspread.authorize(creds)
|
||||
ws = gc.open_by_key(prompt_settings.PROMPT_SPREADSHEET).worksheet(sheet_name)
|
||||
values = ws.batch_get(["B2:B3"])[0] # [[B2], [B3]]
|
||||
_sheet_cache[sheet_name] = (values[1][0], values[0][0]) # (B3=template, B2=model)
|
||||
ws = _get_spreadsheet().worksheet(sheet_name)
|
||||
values = ws.batch_get(["B2:B3"])[0]
|
||||
_sheet_cache[sheet_name] = (values[1][0], values[0][0])
|
||||
return _sheet_cache[sheet_name]
|
||||
|
||||
|
||||
@@ -41,43 +64,43 @@ class Prompt():
|
||||
self.prompt_output_class = prompt_output_class
|
||||
self.prompt_template, self.prompt_model = _read_sheet_data(sheet_name)
|
||||
|
||||
def _reload_prompt(self):
|
||||
_sheet_cache.pop(self.sheet_name, None)
|
||||
self.prompt_template, self.prompt_model = _read_sheet_data(self.sheet_name)
|
||||
|
||||
def build_prompt(self, input_data:dict, silent:bool = False) -> str:
|
||||
verified_input = self.prompt_input_class(**input_data)
|
||||
build_template = self.prompt_template
|
||||
build_template = build_template.format(**verified_input.model_dump())
|
||||
values = verified_input.model_dump()
|
||||
# 알려진 {필드}만 치환하고, 프롬프트 내 JSON 예시 등 리터럴 중괄호는 그대로 둔다.
|
||||
# (str.format은 모든 {..}를 필드로 해석해 리터럴 중괄호에서 깨지므로 사용하지 않음)
|
||||
build_template = _PLACEHOLDER_RE.sub(
|
||||
lambda m: str(values[m.group(1)]) if m.group(1) in values else m.group(0),
|
||||
self.prompt_template,
|
||||
)
|
||||
if not silent:
|
||||
logger.debug(f"build_template: {build_template}")
|
||||
logger.debug(f"input_data: {input_data}")
|
||||
return build_template
|
||||
|
||||
# 업종 분기는 각 프롬프트 내부에서 {industry} 변수로 처리하므로 시트는 타입별 1개로 통합.
|
||||
_preload_all_sheets([
|
||||
"marketing",
|
||||
"lyric",
|
||||
"subtitle",
|
||||
"yt_upload",
|
||||
"image_tag",
|
||||
])
|
||||
|
||||
|
||||
# 업종 분기는 프롬프트 내부 {industry} 변수로 처리하므로 타입별 단일 프롬프트만 둔다.
|
||||
marketing_prompt = Prompt(
|
||||
sheet_name="marketing",
|
||||
prompt_input_class=MarketingPromptInput,
|
||||
prompt_output_class=MarketingPromptOutput,
|
||||
)
|
||||
|
||||
restaurant_marketing_prompt = Prompt(
|
||||
sheet_name="m_restaurant",
|
||||
prompt_input_class=MarketingPromptInput,
|
||||
prompt_output_class=MarketingPromptOutput,
|
||||
)
|
||||
|
||||
lyric_prompt = Prompt(
|
||||
sheet_name="lyric",
|
||||
prompt_input_class=LyricPromptInput,
|
||||
prompt_output_class=LyricPromptOutput,
|
||||
)
|
||||
|
||||
restaurant_lyric_prompt = Prompt(
|
||||
sheet_name="l_restaurant",
|
||||
prompt_input_class=LyricPromptInput,
|
||||
prompt_output_class=LyricPromptOutput,
|
||||
)
|
||||
|
||||
yt_upload_prompt = Prompt(
|
||||
sheet_name="yt_upload",
|
||||
prompt_input_class=YTUploadPromptInput,
|
||||
@@ -91,18 +114,10 @@ image_autotag_prompt = Prompt(
|
||||
)
|
||||
|
||||
@lru_cache()
|
||||
def create_dynamic_subtitle_prompt(length: int) -> Prompt:
|
||||
def create_dynamic_subtitle_prompt(length: int, industry: str = "") -> Prompt:
|
||||
# industry 인자는 캐시 구분/하위 호환용. 시트는 단일 'subtitle'로 통합됨.
|
||||
return Prompt(
|
||||
sheet_name="subtitle",
|
||||
prompt_input_class=SubtitlePromptInput,
|
||||
prompt_output_class=SubtitlePromptOutput[length],
|
||||
)
|
||||
|
||||
|
||||
def reload_all_prompt():
|
||||
marketing_prompt._reload_prompt()
|
||||
restaurant_marketing_prompt._reload_prompt()
|
||||
lyric_prompt._reload_prompt()
|
||||
restaurant_lyric_prompt._reload_prompt()
|
||||
yt_upload_prompt._reload_prompt()
|
||||
image_autotag_prompt._reload_prompt()
|
||||
@@ -94,6 +94,7 @@ class NarrativePreference(BaseModel):
|
||||
# Input 정의
|
||||
class ImageTagPromptInput(BaseModel):
|
||||
img_url : str = Field(..., description="이미지 URL")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
space_type: list[str] = Field(list(SpaceType), description="공간적 정보를 가지는 태그 리스트")
|
||||
subject: list[str] = Field(list(Subject), description="피사체 정보를 가지는 태그 리스트")
|
||||
camera: list[str] = Field(list(Camera), description="카메라 정보를 가지는 태그 리스트")
|
||||
|
||||
@@ -9,6 +9,7 @@ class LyricPromptInput(BaseModel):
|
||||
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
||||
language : str= Field(..., description = "가사 언어")
|
||||
timing_rules : str = Field(..., description = "시간 제어문")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class LyricPromptOutput(BaseModel):
|
||||
|
||||
@@ -6,6 +6,7 @@ class MarketingPromptInput(BaseModel):
|
||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||
region : str = Field(..., description = "마케팅 대상 지역")
|
||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class BrandIdentity(BaseModel):
|
||||
|
||||
@@ -10,6 +10,7 @@ class SubtitlePromptInput(BaseModel):
|
||||
customer_name : str = Field(..., description = "마케팅 대상 사업체 이름")
|
||||
detail_region_info : str = Field(..., description = "마케팅 대상 지역 상세")
|
||||
language : str = Field(default="Korean", description="자막 출력 언어 (Korean, English, Chinese, Japanese, Thai, Vietnamese)")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class PitchingOutput(BaseModel):
|
||||
|
||||
@@ -8,6 +8,7 @@ class YTUploadPromptInput(BaseModel):
|
||||
marketing_intelligence_summary : Optional[str] = Field(None, description = "마케팅 분석 정보 보고서")
|
||||
language : str= Field(..., description = "영상 언어")
|
||||
target_keywords: List[str] = Field(..., description="태그 키워드 리스트")
|
||||
industry : str = Field(default="", description = "업종 분류 (stay|restaurant|cafe|salon|clinic|fitness|academy|attraction). 통합 프롬프트가 이 값으로 내부 분기")
|
||||
|
||||
# Output 정의
|
||||
class YTUploadPromptOutput(BaseModel):
|
||||
|
||||
Reference in new issue
Block a user