범용 프롬프트 적용

This commit is contained in:
skkim committed 2026-06-29 15:06:04 +09:00
1 parent 8415e1c3a7
commit 04d8614919
18 files changed
+140 -85

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@ async def autotag_images(image_url_list : list[str]) -> list[dict]: #tag_list
image_result_tasks = [chatgpt.generate_structured_output(image_autotag_prompt, image_input_data, image_input_data['img_url'], False, silent = True) for image_input_data in image_input_data_list]
image_result_list: list[BaseModel | BaseException] = await asyncio.gather(*image_result_tasks, return_exceptions=True)
MAX_RETRY = 2 # 하드코딩, 어떻게 처리할지는 나중에
MAX_RETRY = 2
for _ in range(MAX_RETRY):
failed_idx = [i for i, r in enumerate(image_result_list) if isinstance(r, Exception)]
print("Failed", failed_idx)
+14 -1
View File
@@ -30,6 +30,7 @@ response = await creatomate.make_creatomate_call(template_id, modifications)
"""
import copy
import random
import time
from enum import StrEnum
from typing import Literal
@@ -470,10 +471,20 @@ class CreatomateService:
match template_type:
case "image":
image_score_list = self.calculate_image_slot_score_multi(taged_image_list, template_component_name)
maximum_idx = image_score_list.index(max(image_score_list))
if duplicate:
# 이미지 부족(슬롯 수 > 이미지 수): 재사용이 불가피하므로 슬롯에 가장 적합한 이미지(최고점) 선택
maximum_idx = image_score_list.index(max(image_score_list))
selected = taged_image_list[maximum_idx]
else:
# 이미지 충분(슬롯 수 <= 이미지 수): 상위 3장 중 점수 비례 확률로 선택해 영상 다양화
# 동일 요청을 반복할 때 매번 같은 영상이 생성되는 문제 방지
sorted_indices = sorted(range(len(image_score_list)), key=lambda i: image_score_list[i], reverse=True)
top_indices = sorted_indices[:min(3, len(sorted_indices))]
weights = [image_score_list[i] for i in top_indices]
if sum(weights) > 0:
maximum_idx = random.choices(top_indices, weights=weights, k=1)[0]
else:
maximum_idx = random.choice(top_indices)
selected = taged_image_list.pop(maximum_idx)
image_name = selected["image_url"]
modifications[template_component_name] =image_name
@@ -679,6 +690,8 @@ class CreatomateService:
"""
url = f"{self.BASE_URL}/v2/renders"
source["frame_rate"] = 30
last_error: Exception | None = None
for attempt in range(recovery_settings.CREATOMATE_MAX_RETRIES + 1):
+50 -35
View File
@@ -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()
+1
View File
@@ -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="카메라 정보를 가지는 태그 리스트")
+1
View File
@@ -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):
+1
View File
@@ -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):
+1
View File
@@ -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):
+1
View File
@@ -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):
+5 -3
View File
@@ -16,16 +16,17 @@ class SubtitleContentsGenerator():
def __init__(self):
self.chatgpt_service = ChatgptService(timeout=60.0)
async def generate_subtitle_contents(self, marketing_intelligence : dict[str, Any], pitching_label_list : list[Any], customer_name : str, detail_region_info : str, language : str = "Korean") -> SubtitlePromptOutput:
async def generate_subtitle_contents(self, marketing_intelligence : dict[str, Any], pitching_label_list : list[Any], customer_name : str, detail_region_info : str, language : str = "Korean", industry: str = "") -> SubtitlePromptOutput:
start = time.perf_counter()
logger.info(
f"[SubtitleContentsGenerator] START - customer: {customer_name}, "
f"pitching_count: {len(pitching_label_list)}, "
f"labels: {pitching_label_list}, "
f"language: {language}"
f"language: {language}, "
f"industry: {industry}"
)
dynamic_subtitle_prompt = create_dynamic_subtitle_prompt(len(pitching_label_list))
dynamic_subtitle_prompt = create_dynamic_subtitle_prompt(len(pitching_label_list), industry)
pitching_label_string = "\n".join(pitching_label_list)
marketing_intel_string = json.dumps(marketing_intelligence, ensure_ascii=False)
input_data = {
@@ -34,6 +35,7 @@ class SubtitleContentsGenerator():
"customer_name" : customer_name,
"detail_region_info" : detail_region_info,
"language" : language,
"industry": industry, # 가사/영상 파이프라인에서 전달된 업종 enum
}
logger.info(