add logs for tracing processing task
This commit is contained in:
1 parent
efddee217a
commit
073777081e
81 files changed
+25300
-24561
No files matched your search
+379
-329
@@ -1,329 +1,379 @@
|
||||
import json
|
||||
import re
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from config import apikey_settings
|
||||
|
||||
# fmt: off
|
||||
LYRICS_PROMPT_TEMPLATE_ORI = """
|
||||
1.Act as a content marketing expert with domain knowledges in [pension/staying services] in Korea, Goal: plan viral content creation that lead online reservations and promotion
|
||||
2.Conduct an in-depth analysis of [업체명:{customer_name}] in [지역명:{region}] by examining their official website or informations, photos on never map and online presence. Create a comprehensive "[지역 상세: {detail_region_info}]_Brand & Marketing Intelligence Report in Korean, that includes:
|
||||
|
||||
**Core Analysis:**
|
||||
- Target customer segments & personas
|
||||
- Unique Selling Propositions (USPs) and competitive differentiators
|
||||
- Comprehensive competitor landscape analysis (direct & indirect competitors)
|
||||
- Market positioning assessment
|
||||
|
||||
**Content Strategy Framework:**
|
||||
- Seasonal content calendar with trend integration
|
||||
- Visual storytelling direction (shot-by-shot creative guidance)
|
||||
- Brand tone & voice guidelines
|
||||
- Content themes aligned with target audience behaviors
|
||||
|
||||
**SEO & AEO Optimization:**
|
||||
- Recommended primary and long-tail keywords
|
||||
- SEO-optimized taglines and meta descriptions
|
||||
- Answer Engine Optimization (AEO) content suggestions
|
||||
- Local search optimization strategies
|
||||
|
||||
**Actionable Recommendations:**
|
||||
- Content distribution strategy across platforms
|
||||
- KPI measurement framework
|
||||
- Budget allocation recommendations by content type
|
||||
|
||||
콘텐츠 기획(Lyrics, Prompt for SUNO)
|
||||
1. Based on the Brand & Marketing Intelligence Report for [업체명 + 지역명 / {customer_name} ({region})], create original lyrics and define music attributes (song mood, BPM, genres, and key musical motifs, Prompt for Suno.com) specifically tailored for viral content.
|
||||
2. The lyrics should include, the name of [ Promotion Subject], [location], [main target],[Famous place, accessible in 10min], promotional words including but not limited to [인스타 감성], [사진같은 하루]
|
||||
|
||||
Deliver outputs optimized for three formats:1 minute. Ensure that each version aligns with the brand's core identity and is suitable for use in digital marketing and social media campaigns, in Korean
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
LYRICS_PROMPT_TEMPLATE = """
|
||||
[ROLE]
|
||||
Content marketing expert and creative songwriter specializing in pension/accommodation services
|
||||
|
||||
[INPUT]
|
||||
- Business Name: {customer_name}
|
||||
- Region: {region}
|
||||
- Region Details: {detail_region_info}
|
||||
- Output Language: {language}
|
||||
|
||||
[INTERNAL ANALYSIS - DO NOT OUTPUT]
|
||||
Analyze the following internally to inform lyrics creation:
|
||||
- Target customer segments and personas
|
||||
- Unique Selling Propositions (USPs)
|
||||
- Regional characteristics and nearby attractions (within 10 min access)
|
||||
- Seasonal appeal points
|
||||
- Emotional triggers for the target audience
|
||||
|
||||
[LYRICS REQUIREMENTS]
|
||||
1. Must Include Elements:
|
||||
- Business name (TRANSLATED or TRANSLITERATED to {language})
|
||||
- Region name (TRANSLATED or TRANSLITERATED to {language})
|
||||
- Main target audience appeal
|
||||
- Nearby famous places or regional characteristics
|
||||
|
||||
2. Keywords to Incorporate (use language-appropriate trendy expressions):
|
||||
- Korean: 인스타 감성, 사진같은 하루, 힐링, 여행, 감성 숙소
|
||||
- English: Instagram vibes, picture-perfect day, healing, travel, getaway
|
||||
- Chinese: 网红打卡, 治愈系, 旅行, 度假, 拍照圣地
|
||||
- Japanese: インスタ映え, 写真のような一日, 癒し, 旅行, 絶景
|
||||
- Thai: ที่พักสวย, ฮีลใจ, เที่ยว, ถ่ายรูป, วิวสวย
|
||||
- Vietnamese: check-in đẹp, healing, du lịch, nghỉ dưỡng, view đẹp
|
||||
|
||||
3. Structure:
|
||||
- Length: For 1-minute video (approximately 8-12 lines)
|
||||
- Flow: Verse structure suitable for music
|
||||
- Rhythm: Natural speech rhythm in the specified language
|
||||
|
||||
4. Tone:
|
||||
- Emotional and heartfelt
|
||||
- Trendy and viral-friendly
|
||||
- Relatable to target audience
|
||||
|
||||
[CRITICAL LANGUAGE REQUIREMENT - ABSOLUTE RULE]
|
||||
ALL OUTPUT MUST BE 100% WRITTEN IN {language} - NO EXCEPTIONS
|
||||
- ALL lyrics content: {language} ONLY
|
||||
- ALL proper nouns (business names, region names, place names): MUST be translated or transliterated to {language}
|
||||
- Korean input like "군산" must become "Gunsan" in English, "群山" in Chinese, "グンサン" in Japanese, etc.
|
||||
- Korean input like "스테이 머뭄" must become "Stay Meoum" in English, "住留" in Chinese, "ステイモーム" in Japanese, etc.
|
||||
- ZERO Korean characters (한글) allowed when output language is NOT Korean
|
||||
- ZERO mixing of languages - the entire output must be monolingual in {language}
|
||||
- This is a NON-NEGOTIABLE requirement
|
||||
- Any output containing characters from other languages is considered a COMPLETE FAILURE
|
||||
- Violation of this rule invalidates the entire response
|
||||
|
||||
[OUTPUT RULES - STRICTLY ENFORCED]
|
||||
- Output lyrics ONLY
|
||||
- Lyrics MUST be written ENTIRELY in {language} - NO EXCEPTIONS
|
||||
- ALL names and places MUST be in {language} script/alphabet
|
||||
- NO Korean (한글), Chinese (漢字), Japanese (仮名), Thai (ไทย), or Vietnamese (Tiếng Việt) characters unless that is the selected output language
|
||||
- NO titles, descriptions, analysis, or explanations
|
||||
- NO greetings or closing remarks
|
||||
- NO additional commentary before or after lyrics
|
||||
- NO line numbers or labels
|
||||
- Follow the exact format below
|
||||
|
||||
[OUTPUT FORMAT - SUCCESS]
|
||||
---
|
||||
[Lyrics ENTIRELY in {language} here - no other language characters allowed]
|
||||
---
|
||||
|
||||
[OUTPUT FORMAT - FAILURE]
|
||||
If you cannot generate lyrics due to insufficient information, invalid input, or any other reason:
|
||||
---
|
||||
ERROR: [Brief reason for failure in English]
|
||||
---
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
MARKETING_ANALYSIS_PROMPT_TEMPLATE = """
|
||||
[ROLE]
|
||||
Content marketing expert specializing in pension/accommodation services in Korea
|
||||
|
||||
[INPUT]
|
||||
- Business Name: {customer_name}
|
||||
- Region: {region}
|
||||
- Region Details: {detail_region_info}
|
||||
|
||||
[ANALYSIS REQUIREMENTS]
|
||||
Provide comprehensive marketing analysis including:
|
||||
1. Target Customer Segments
|
||||
- Primary and secondary target personas
|
||||
- Age groups, travel preferences, booking patterns
|
||||
2. Unique Selling Propositions (USPs)
|
||||
- Key differentiators based on location and region details
|
||||
- Competitive advantages
|
||||
3. Regional Characteristics
|
||||
- Nearby attractions and famous places (within 10 min access)
|
||||
- Local food, activities, and experiences
|
||||
- Transportation accessibility
|
||||
4. Seasonal Appeal Points
|
||||
- Best seasons to visit
|
||||
- Seasonal activities and events
|
||||
- Peak/off-peak marketing opportunities
|
||||
5. Marketing Keywords
|
||||
- Recommended hashtags and search keywords
|
||||
- Trending terms relevant to the property
|
||||
|
||||
[ADDITIONAL REQUIREMENTS]
|
||||
1. Recommended Tags
|
||||
- Generate 5 recommended hashtags/tags based on the business characteristics
|
||||
- Tags should be trendy, searchable, and relevant to accommodation marketing
|
||||
- Return as JSON with key "tags"
|
||||
- **MUST be written in Korean (한국어)**
|
||||
|
||||
2. Facilities
|
||||
- Based on the business name and region details, identify 5 likely facilities/amenities
|
||||
- Consider typical facilities for accommodations in the given region
|
||||
- Examples: 바베큐장, 수영장, 주차장, 와이파이, 주방, 테라스, 정원, etc.
|
||||
- Return as JSON with key "facilities"
|
||||
- **MUST be written in Korean (한국어)**
|
||||
|
||||
[CRITICAL LANGUAGE REQUIREMENT - ABSOLUTE RULE]
|
||||
ALL OUTPUT MUST BE WRITTEN IN KOREAN (한국어)
|
||||
- Analysis sections: Korean only
|
||||
- Tags: Korean only
|
||||
- Facilities: Korean only
|
||||
- This is a NON-NEGOTIABLE requirement
|
||||
- Any output in English or other languages is considered a FAILURE
|
||||
- Violation of this rule invalidates the entire response
|
||||
|
||||
[OUTPUT RULES - STRICTLY ENFORCED]
|
||||
- Output analysis ONLY
|
||||
- ALL content MUST be written in Korean (한국어) - NO EXCEPTIONS
|
||||
- NO greetings or closing remarks
|
||||
- NO additional commentary before or after analysis
|
||||
- Follow the exact format below
|
||||
|
||||
[OUTPUT FORMAT - SUCCESS]
|
||||
---
|
||||
## 타겟 고객 분석
|
||||
[한국어로 작성된 타겟 고객 분석]
|
||||
|
||||
## 핵심 차별점 (USP)
|
||||
[한국어로 작성된 USP 분석]
|
||||
|
||||
## 지역 특성
|
||||
[한국어로 작성된 지역 특성 분석]
|
||||
|
||||
## 시즌별 매력 포인트
|
||||
[한국어로 작성된 시즌별 분석]
|
||||
|
||||
## 마케팅 키워드
|
||||
[한국어로 작성된 마케팅 키워드]
|
||||
|
||||
## JSON Data
|
||||
```json
|
||||
{{
|
||||
"tags": ["태그1", "태그2", "태그3", "태그4", "태그5"],
|
||||
"facilities": ["부대시설1", "부대시설2", "부대시설3", "부대시설4", "부대시설5"]
|
||||
}}
|
||||
```
|
||||
---
|
||||
|
||||
[OUTPUT FORMAT - FAILURE]
|
||||
If you cannot generate analysis due to insufficient information, invalid input, or any other reason:
|
||||
---
|
||||
ERROR: [Brief reason for failure in English]
|
||||
---
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
|
||||
class ChatgptService:
|
||||
def __init__(
|
||||
self,
|
||||
customer_name: str,
|
||||
region: str,
|
||||
detail_region_info: str = "",
|
||||
language: str = "Korean",
|
||||
):
|
||||
# 최신 모델: GPT-5, GPT-5 mini, GPT-5 nano, GPT-4.1, GPT-4.1 mini, GPT-4.1 nano
|
||||
# 이전 세대: GPT-4o, GPT-4o mini, GPT-4 Turbo, GPT-3.5 Turbo
|
||||
self.model = "gpt-4o"
|
||||
self.client = AsyncOpenAI(api_key=apikey_settings.CHATGPT_API_KEY)
|
||||
self.customer_name = customer_name
|
||||
self.region = region
|
||||
self.detail_region_info = detail_region_info
|
||||
self.language = language
|
||||
|
||||
def build_lyrics_prompt(self) -> str:
|
||||
"""LYRICS_PROMPT_TEMPLATE에 고객 정보를 대입하여 완성된 프롬프트 반환"""
|
||||
return LYRICS_PROMPT_TEMPLATE.format(
|
||||
customer_name=self.customer_name,
|
||||
region=self.region,
|
||||
detail_region_info=self.detail_region_info,
|
||||
language=self.language,
|
||||
)
|
||||
|
||||
def build_market_analysis_prompt(self) -> str:
|
||||
"""MARKETING_ANALYSIS_PROMPT_TEMPLATE에 고객 정보를 대입하여 완성된 프롬프트 반환"""
|
||||
return MARKETING_ANALYSIS_PROMPT_TEMPLATE.format(
|
||||
customer_name=self.customer_name,
|
||||
region=self.region,
|
||||
detail_region_info=self.detail_region_info,
|
||||
)
|
||||
|
||||
async def generate(self, prompt: str | None = None) -> str:
|
||||
"""GPT에게 프롬프트를 전달하여 결과를 반환"""
|
||||
if prompt is None:
|
||||
prompt = self.build_lyrics_prompt()
|
||||
print("Generated Prompt: ", prompt)
|
||||
completion = await self.client.chat.completions.create(
|
||||
model=self.model, messages=[{"role": "user", "content": prompt}]
|
||||
)
|
||||
message = completion.choices[0].message.content
|
||||
return message or ""
|
||||
|
||||
async def summarize_marketing(self, text: str) -> str:
|
||||
"""마케팅 텍스트를 항목으로 구분하여 500자로 요약 정리"""
|
||||
prompt = f"""[ROLE]
|
||||
마케팅 콘텐츠 요약 전문가
|
||||
|
||||
[INPUT]
|
||||
{text}
|
||||
|
||||
[TASK]
|
||||
위 텍스트를 분석하여 핵심 내용을 항목별로 구분하여 500자 이내로 요약해주세요.
|
||||
|
||||
[OUTPUT REQUIREMENTS]
|
||||
- 항목별로 구분하여 정리 (예: 타겟 고객, 차별점, 지역 특성 등)
|
||||
- 총 500자 이내로 요약
|
||||
- 핵심 정보만 간결하게 포함
|
||||
- 한국어로 작성
|
||||
|
||||
[OUTPUT FORMAT]
|
||||
---
|
||||
[항목별로 구분된 500자 이내 요약]
|
||||
---
|
||||
"""
|
||||
completion = await self.client.chat.completions.create(
|
||||
model=self.model, messages=[{"role": "user", "content": prompt}]
|
||||
)
|
||||
message = completion.choices[0].message.content
|
||||
result = message or ""
|
||||
|
||||
# --- 구분자 제거
|
||||
if result.startswith("---"):
|
||||
result = result[3:].strip()
|
||||
if result.endswith("---"):
|
||||
result = result[:-3].strip()
|
||||
|
||||
return result
|
||||
|
||||
async def parse_marketing_analysis(self, raw_response: str) -> dict:
|
||||
"""ChatGPT 마케팅 분석 응답을 파싱하고 요약하여 딕셔너리로 반환
|
||||
|
||||
Returns:
|
||||
dict: {"report": str, "tags": list[str], "facilities": list[str]}
|
||||
"""
|
||||
tags: list[str] = []
|
||||
facilities: list[str] = []
|
||||
report = raw_response
|
||||
|
||||
# JSON 블록 추출 시도
|
||||
json_match = re.search(r"```json\s*(\{.*?\})\s*```", raw_response, re.DOTALL)
|
||||
if json_match:
|
||||
try:
|
||||
json_data = json.loads(json_match.group(1))
|
||||
tags = json_data.get("tags", [])
|
||||
facilities = json_data.get("facilities", [])
|
||||
# JSON 블록을 제외한 리포트 부분 추출
|
||||
report = raw_response[: json_match.start()].strip()
|
||||
# --- 구분자 제거
|
||||
if report.startswith("---"):
|
||||
report = report[3:].strip()
|
||||
if report.endswith("---"):
|
||||
report = report[:-3].strip()
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# 리포트 내용을 500자로 요약
|
||||
if report:
|
||||
report = await self.summarize_marketing(report)
|
||||
|
||||
return {"report": report, "tags": tags, "facilities": facilities}
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from config import apikey_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# fmt: off
|
||||
LYRICS_PROMPT_TEMPLATE_ORI = """
|
||||
1.Act as a content marketing expert with domain knowledges in [pension/staying services] in Korea, Goal: plan viral content creation that lead online reservations and promotion
|
||||
2.Conduct an in-depth analysis of [업체명:{customer_name}] in [지역명:{region}] by examining their official website or informations, photos on never map and online presence. Create a comprehensive "[지역 상세: {detail_region_info}]_Brand & Marketing Intelligence Report in Korean, that includes:
|
||||
|
||||
**Core Analysis:**
|
||||
- Target customer segments & personas
|
||||
- Unique Selling Propositions (USPs) and competitive differentiators
|
||||
- Comprehensive competitor landscape analysis (direct & indirect competitors)
|
||||
- Market positioning assessment
|
||||
|
||||
**Content Strategy Framework:**
|
||||
- Seasonal content calendar with trend integration
|
||||
- Visual storytelling direction (shot-by-shot creative guidance)
|
||||
- Brand tone & voice guidelines
|
||||
- Content themes aligned with target audience behaviors
|
||||
|
||||
**SEO & AEO Optimization:**
|
||||
- Recommended primary and long-tail keywords
|
||||
- SEO-optimized taglines and meta descriptions
|
||||
- Answer Engine Optimization (AEO) content suggestions
|
||||
- Local search optimization strategies
|
||||
|
||||
**Actionable Recommendations:**
|
||||
- Content distribution strategy across platforms
|
||||
- KPI measurement framework
|
||||
- Budget allocation recommendations by content type
|
||||
|
||||
콘텐츠 기획(Lyrics, Prompt for SUNO)
|
||||
1. Based on the Brand & Marketing Intelligence Report for [업체명 + 지역명 / {customer_name} ({region})], create original lyrics and define music attributes (song mood, BPM, genres, and key musical motifs, Prompt for Suno.com) specifically tailored for viral content.
|
||||
2. The lyrics should include, the name of [ Promotion Subject], [location], [main target],[Famous place, accessible in 10min], promotional words including but not limited to [인스타 감성], [사진같은 하루]
|
||||
|
||||
Deliver outputs optimized for three formats:1 minute. Ensure that each version aligns with the brand's core identity and is suitable for use in digital marketing and social media campaigns, in Korean
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
LYRICS_PROMPT_TEMPLATE = """
|
||||
[ROLE]
|
||||
Content marketing expert and creative songwriter specializing in pension/accommodation services
|
||||
|
||||
[INPUT]
|
||||
- Business Name: {customer_name}
|
||||
- Region: {region}
|
||||
- Region Details: {detail_region_info}
|
||||
- Output Language: {language}
|
||||
|
||||
[INTERNAL ANALYSIS - DO NOT OUTPUT]
|
||||
Analyze the following internally to inform lyrics creation:
|
||||
- Target customer segments and personas
|
||||
- Unique Selling Propositions (USPs)
|
||||
- Regional characteristics and nearby attractions (within 10 min access)
|
||||
- Seasonal appeal points
|
||||
- Emotional triggers for the target audience
|
||||
|
||||
[LYRICS REQUIREMENTS]
|
||||
1. Must Include Elements:
|
||||
- Business name (TRANSLATED or TRANSLITERATED to {language})
|
||||
- Region name (TRANSLATED or TRANSLITERATED to {language})
|
||||
- Main target audience appeal
|
||||
- Nearby famous places or regional characteristics
|
||||
|
||||
2. Keywords to Incorporate (use language-appropriate trendy expressions):
|
||||
- Korean: 인스타 감성, 사진같은 하루, 힐링, 여행, 감성 숙소
|
||||
- English: Instagram vibes, picture-perfect day, healing, travel, getaway
|
||||
- Chinese: 网红打卡, 治愈系, 旅行, 度假, 拍照圣地
|
||||
- Japanese: インスタ映え, 写真のような一日, 癒し, 旅行, 絶景
|
||||
- Thai: ที่พักสวย, ฮีลใจ, เที่ยว, ถ่ายรูป, วิวสวย
|
||||
- Vietnamese: check-in đẹp, healing, du lịch, nghỉ dưỡng, view đẹp
|
||||
|
||||
3. Structure:
|
||||
- Length: For 1-minute video (approximately 8-12 lines)
|
||||
- Flow: Verse structure suitable for music
|
||||
- Rhythm: Natural speech rhythm in the specified language
|
||||
|
||||
4. Tone:
|
||||
- Emotional and heartfelt
|
||||
- Trendy and viral-friendly
|
||||
- Relatable to target audience
|
||||
|
||||
[CRITICAL LANGUAGE REQUIREMENT - ABSOLUTE RULE]
|
||||
ALL OUTPUT MUST BE 100% WRITTEN IN {language} - NO EXCEPTIONS
|
||||
- ALL lyrics content: {language} ONLY
|
||||
- ALL proper nouns (business names, region names, place names): MUST be translated or transliterated to {language}
|
||||
- Korean input like "군산" must become "Gunsan" in English, "群山" in Chinese, "グンサン" in Japanese, etc.
|
||||
- Korean input like "스테이 머뭄" must become "Stay Meoum" in English, "住留" in Chinese, "ステイモーム" in Japanese, etc.
|
||||
- ZERO Korean characters (한글) allowed when output language is NOT Korean
|
||||
- ZERO mixing of languages - the entire output must be monolingual in {language}
|
||||
- This is a NON-NEGOTIABLE requirement
|
||||
- Any output containing characters from other languages is considered a COMPLETE FAILURE
|
||||
- Violation of this rule invalidates the entire response
|
||||
|
||||
[OUTPUT RULES - STRICTLY ENFORCED]
|
||||
- Output lyrics ONLY
|
||||
- Lyrics MUST be written ENTIRELY in {language} - NO EXCEPTIONS
|
||||
- ALL names and places MUST be in {language} script/alphabet
|
||||
- NO Korean (한글), Chinese (漢字), Japanese (仮名), Thai (ไทย), or Vietnamese (Tiếng Việt) characters unless that is the selected output language
|
||||
- NO titles, descriptions, analysis, or explanations
|
||||
- NO greetings or closing remarks
|
||||
- NO additional commentary before or after lyrics
|
||||
- NO line numbers or labels
|
||||
- Follow the exact format below
|
||||
|
||||
[OUTPUT FORMAT - SUCCESS]
|
||||
---
|
||||
[Lyrics ENTIRELY in {language} here - no other language characters allowed]
|
||||
---
|
||||
|
||||
[OUTPUT FORMAT - FAILURE]
|
||||
If you cannot generate lyrics due to insufficient information, invalid input, or any other reason:
|
||||
---
|
||||
ERROR: [Brief reason for failure in English]
|
||||
---
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
MARKETING_ANALYSIS_PROMPT_TEMPLATE = """
|
||||
[ROLE]
|
||||
Content marketing expert specializing in pension/accommodation services in Korea
|
||||
|
||||
[INPUT]
|
||||
- Business Name: {customer_name}
|
||||
- Region: {region}
|
||||
- Region Details: {detail_region_info}
|
||||
|
||||
[ANALYSIS REQUIREMENTS]
|
||||
Provide comprehensive marketing analysis including:
|
||||
1. Target Customer Segments
|
||||
- Primary and secondary target personas
|
||||
- Age groups, travel preferences, booking patterns
|
||||
2. Unique Selling Propositions (USPs)
|
||||
- Key differentiators based on location and region details
|
||||
- Competitive advantages
|
||||
3. Regional Characteristics
|
||||
- Nearby attractions and famous places (within 10 min access)
|
||||
- Local food, activities, and experiences
|
||||
- Transportation accessibility
|
||||
4. Seasonal Appeal Points
|
||||
- Best seasons to visit
|
||||
- Seasonal activities and events
|
||||
- Peak/off-peak marketing opportunities
|
||||
5. Marketing Keywords
|
||||
- Recommended hashtags and search keywords
|
||||
- Trending terms relevant to the property
|
||||
|
||||
[ADDITIONAL REQUIREMENTS]
|
||||
1. Recommended Tags
|
||||
- Generate 5 recommended hashtags/tags based on the business characteristics
|
||||
- Tags should be trendy, searchable, and relevant to accommodation marketing
|
||||
- Return as JSON with key "tags"
|
||||
- **MUST be written in Korean (한국어)**
|
||||
|
||||
2. Facilities
|
||||
- Based on the business name and region details, identify 5 likely facilities/amenities
|
||||
- Consider typical facilities for accommodations in the given region
|
||||
- Examples: 바베큐장, 수영장, 주차장, 와이파이, 주방, 테라스, 정원, etc.
|
||||
- Return as JSON with key "facilities"
|
||||
- **MUST be written in Korean (한국어)**
|
||||
|
||||
[CRITICAL LANGUAGE REQUIREMENT - ABSOLUTE RULE]
|
||||
ALL OUTPUT MUST BE WRITTEN IN KOREAN (한국어)
|
||||
- Analysis sections: Korean only
|
||||
- Tags: Korean only
|
||||
- Facilities: Korean only
|
||||
- This is a NON-NEGOTIABLE requirement
|
||||
- Any output in English or other languages is considered a FAILURE
|
||||
- Violation of this rule invalidates the entire response
|
||||
|
||||
[OUTPUT RULES - STRICTLY ENFORCED]
|
||||
- Output analysis ONLY
|
||||
- ALL content MUST be written in Korean (한국어) - NO EXCEPTIONS
|
||||
- NO greetings or closing remarks
|
||||
- NO additional commentary before or after analysis
|
||||
- Follow the exact format below
|
||||
|
||||
[OUTPUT FORMAT - SUCCESS]
|
||||
---
|
||||
## 타겟 고객 분석
|
||||
[한국어로 작성된 타겟 고객 분석]
|
||||
|
||||
## 핵심 차별점 (USP)
|
||||
[한국어로 작성된 USP 분석]
|
||||
|
||||
## 지역 특성
|
||||
[한국어로 작성된 지역 특성 분석]
|
||||
|
||||
## 시즌별 매력 포인트
|
||||
[한국어로 작성된 시즌별 분석]
|
||||
|
||||
## 마케팅 키워드
|
||||
[한국어로 작성된 마케팅 키워드]
|
||||
|
||||
## JSON Data
|
||||
```json
|
||||
{{
|
||||
"tags": ["태그1", "태그2", "태그3", "태그4", "태그5"],
|
||||
"facilities": ["부대시설1", "부대시설2", "부대시설3", "부대시설4", "부대시설5"]
|
||||
}}
|
||||
```
|
||||
---
|
||||
|
||||
[OUTPUT FORMAT - FAILURE]
|
||||
If you cannot generate analysis due to insufficient information, invalid input, or any other reason:
|
||||
---
|
||||
ERROR: [Brief reason for failure in English]
|
||||
---
|
||||
""".strip()
|
||||
# fmt: on
|
||||
|
||||
|
||||
class ChatgptService:
|
||||
"""ChatGPT API 서비스 클래스
|
||||
|
||||
GPT 5.0 모델을 사용하여 마케팅 가사 및 분석을 생성합니다.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
customer_name: str,
|
||||
region: str,
|
||||
detail_region_info: str = "",
|
||||
language: str = "Korean",
|
||||
):
|
||||
# 최신 모델: gpt-5-mini
|
||||
self.model = "gpt-5-mini"
|
||||
self.client = AsyncOpenAI(api_key=apikey_settings.CHATGPT_API_KEY)
|
||||
self.customer_name = customer_name
|
||||
self.region = region
|
||||
self.detail_region_info = detail_region_info
|
||||
self.language = language
|
||||
|
||||
def build_lyrics_prompt(self) -> str:
|
||||
"""LYRICS_PROMPT_TEMPLATE에 고객 정보를 대입하여 완성된 프롬프트 반환"""
|
||||
return LYRICS_PROMPT_TEMPLATE.format(
|
||||
customer_name=self.customer_name,
|
||||
region=self.region,
|
||||
detail_region_info=self.detail_region_info,
|
||||
language=self.language,
|
||||
)
|
||||
|
||||
def build_market_analysis_prompt(self) -> str:
|
||||
"""MARKETING_ANALYSIS_PROMPT_TEMPLATE에 고객 정보를 대입하여 완성된 프롬프트 반환"""
|
||||
return MARKETING_ANALYSIS_PROMPT_TEMPLATE.format(
|
||||
customer_name=self.customer_name,
|
||||
region=self.region,
|
||||
detail_region_info=self.detail_region_info,
|
||||
)
|
||||
|
||||
async def _call_gpt_api(self, prompt: str) -> str:
|
||||
"""GPT API를 직접 호출합니다 (내부 메서드).
|
||||
|
||||
Args:
|
||||
prompt: GPT에 전달할 프롬프트
|
||||
|
||||
Returns:
|
||||
GPT 응답 문자열
|
||||
|
||||
Raises:
|
||||
APIError, APIConnectionError, RateLimitError: OpenAI API 오류
|
||||
"""
|
||||
completion = await self.client.chat.completions.create(
|
||||
model=self.model, messages=[{"role": "user", "content": prompt}]
|
||||
)
|
||||
message = completion.choices[0].message.content
|
||||
return message or ""
|
||||
|
||||
async def generate(
|
||||
self,
|
||||
prompt: str | None = None,
|
||||
) -> str:
|
||||
"""GPT에게 프롬프트를 전달하여 결과를 반환합니다.
|
||||
|
||||
Args:
|
||||
prompt: GPT에 전달할 프롬프트 (None이면 기본 가사 프롬프트 사용)
|
||||
|
||||
Returns:
|
||||
GPT 응답 문자열
|
||||
|
||||
Raises:
|
||||
APIError, APIConnectionError, RateLimitError: OpenAI API 오류
|
||||
"""
|
||||
if prompt is None:
|
||||
prompt = self.build_lyrics_prompt()
|
||||
|
||||
print(f"[ChatgptService] Generated Prompt (length: {len(prompt)})")
|
||||
logger.info(f"[ChatgptService] Starting GPT request with model: {self.model}")
|
||||
|
||||
# GPT API 호출
|
||||
response = await self._call_gpt_api(prompt)
|
||||
|
||||
print(f"[ChatgptService] SUCCESS - Response length: {len(response)}")
|
||||
logger.info(f"[ChatgptService] SUCCESS - Response length: {len(response)}")
|
||||
return response
|
||||
|
||||
async def summarize_marketing(self, text: str) -> str:
|
||||
"""마케팅 텍스트를 항목으로 구분하여 500자로 요약 정리.
|
||||
|
||||
Args:
|
||||
text: 요약할 마케팅 텍스트
|
||||
|
||||
Returns:
|
||||
요약된 텍스트
|
||||
|
||||
Raises:
|
||||
APIError, APIConnectionError, RateLimitError: OpenAI API 오류
|
||||
"""
|
||||
prompt = f"""[ROLE]
|
||||
마케팅 콘텐츠 요약 전문가
|
||||
|
||||
[INPUT]
|
||||
{text}
|
||||
|
||||
[TASK]
|
||||
위 텍스트를 분석하여 핵심 내용을 항목별로 구분하여 500자 이내로 요약해주세요.
|
||||
|
||||
[OUTPUT REQUIREMENTS]
|
||||
- 항목별로 구분하여 정리 (예: 타겟 고객, 차별점, 지역 특성 등)
|
||||
- 총 500자 이내로 요약
|
||||
- 핵심 정보만 간결하게 포함
|
||||
- 한국어로 작성
|
||||
|
||||
[OUTPUT FORMAT]
|
||||
---
|
||||
[항목별로 구분된 500자 이내 요약]
|
||||
---
|
||||
"""
|
||||
|
||||
result = await self.generate(prompt=prompt)
|
||||
|
||||
# --- 구분자 제거
|
||||
if result.startswith("---"):
|
||||
result = result[3:].strip()
|
||||
if result.endswith("---"):
|
||||
result = result[:-3].strip()
|
||||
|
||||
return result
|
||||
|
||||
async def parse_marketing_analysis(self, raw_response: str) -> dict:
|
||||
"""ChatGPT 마케팅 분석 응답을 파싱하고 요약하여 딕셔너리로 반환
|
||||
|
||||
Returns:
|
||||
dict: {"report": str, "tags": list[str], "facilities": list[str]}
|
||||
"""
|
||||
tags: list[str] = []
|
||||
facilities: list[str] = []
|
||||
report = raw_response
|
||||
|
||||
# JSON 블록 추출 시도
|
||||
json_match = re.search(r"```json\s*(\{.*?\})\s*```", raw_response, re.DOTALL)
|
||||
if json_match:
|
||||
try:
|
||||
json_data = json.loads(json_match.group(1))
|
||||
tags = json_data.get("tags", [])
|
||||
facilities = json_data.get("facilities", [])
|
||||
# JSON 블록을 제외한 리포트 부분 추출
|
||||
report = raw_response[: json_match.start()].strip()
|
||||
# --- 구분자 제거
|
||||
if report.startswith("---"):
|
||||
report = report[3:].strip()
|
||||
if report.endswith("---"):
|
||||
report = report[:-3].strip()
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# 리포트 내용을 500자로 요약
|
||||
if report:
|
||||
report = await self.summarize_marketing(report)
|
||||
|
||||
return {"report": report, "tags": tags, "facilities": facilities}
|
||||
+24
-24
@@ -1,24 +1,24 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from config import cors_settings
|
||||
|
||||
# sys.path.append(
|
||||
# os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
# ) # root 경로 추가
|
||||
|
||||
|
||||
class CustomCORSMiddleware:
|
||||
def __init__(self, app: FastAPI):
|
||||
self.app = app
|
||||
|
||||
def configure_cors(self):
|
||||
self.app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_settings.CORS_ALLOW_ORIGINS,
|
||||
allow_credentials=cors_settings.CORS_ALLOW_CREDENTIALS,
|
||||
allow_methods=cors_settings.CORS_ALLOW_METHODS,
|
||||
allow_headers=cors_settings.CORS_ALLOW_HEADERS,
|
||||
expose_headers=cors_settings.CORS_EXPOSE_HEADERS,
|
||||
max_age=cors_settings.CORS_MAX_AGE,
|
||||
)
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from config import cors_settings
|
||||
|
||||
# sys.path.append(
|
||||
# os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
# ) # root 경로 추가
|
||||
|
||||
|
||||
class CustomCORSMiddleware:
|
||||
def __init__(self, app: FastAPI):
|
||||
self.app = app
|
||||
|
||||
def configure_cors(self):
|
||||
self.app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_settings.CORS_ALLOW_ORIGINS,
|
||||
allow_credentials=cors_settings.CORS_ALLOW_CREDENTIALS,
|
||||
allow_methods=cors_settings.CORS_ALLOW_METHODS,
|
||||
allow_headers=cors_settings.CORS_ALLOW_HEADERS,
|
||||
expose_headers=cors_settings.CORS_EXPOSE_HEADERS,
|
||||
max_age=cors_settings.CORS_MAX_AGE,
|
||||
)
|
||||
+473
-437
@@ -1,437 +1,473 @@
|
||||
"""
|
||||
Creatomate API 클라이언트 모듈
|
||||
|
||||
API 문서: https://creatomate.com/docs/api
|
||||
|
||||
## 사용법
|
||||
```python
|
||||
from app.utils.creatomate import CreatomateService
|
||||
|
||||
# config에서 자동으로 API 키를 가져옴
|
||||
creatomate = CreatomateService()
|
||||
|
||||
# 또는 명시적으로 API 키 전달
|
||||
creatomate = CreatomateService(api_key="your_api_key")
|
||||
|
||||
# 템플릿 목록 조회 (비동기)
|
||||
templates = await creatomate.get_all_templates_data()
|
||||
|
||||
# 특정 템플릿 조회 (비동기)
|
||||
template = await creatomate.get_one_template_data(template_id)
|
||||
|
||||
# 영상 렌더링 요청 (비동기)
|
||||
response = await creatomate.make_creatomate_call(template_id, modifications)
|
||||
```
|
||||
|
||||
## 성능 최적화
|
||||
- 템플릿 캐싱: 템플릿 데이터는 메모리에 캐싱되어 반복 조회 시 API 호출을 줄입니다.
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀을 재사용합니다.
|
||||
- 캐시 만료: 기본 5분 후 자동 만료 (CACHE_TTL_SECONDS로 조정 가능)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
|
||||
from config import apikey_settings, creatomate_settings
|
||||
|
||||
|
||||
# Orientation 타입 정의
|
||||
OrientationType = Literal["horizontal", "vertical"]
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 캐시 및 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 템플릿 캐시: {template_id: {"data": dict, "cached_at": float}}
|
||||
_template_cache: dict[str, dict] = {}
|
||||
|
||||
# 캐시 TTL (초) - 기본 5분
|
||||
CACHE_TTL_SECONDS = 300
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_client
|
||||
if _shared_client is None or _shared_client.is_closed:
|
||||
_shared_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(60.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
return _shared_client
|
||||
|
||||
|
||||
async def close_shared_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_client
|
||||
if _shared_client is not None and not _shared_client.is_closed:
|
||||
await _shared_client.aclose()
|
||||
_shared_client = None
|
||||
print("[CreatomateService] Shared HTTP client closed")
|
||||
|
||||
|
||||
def clear_template_cache() -> None:
|
||||
"""템플릿 캐시를 전체 삭제합니다."""
|
||||
global _template_cache
|
||||
_template_cache.clear()
|
||||
print("[CreatomateService] Template cache cleared")
|
||||
|
||||
|
||||
def _is_cache_valid(cached_at: float) -> bool:
|
||||
"""캐시가 유효한지 확인합니다."""
|
||||
return (time.time() - cached_at) < CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
class CreatomateService:
|
||||
"""Creatomate API를 통한 영상 생성 서비스
|
||||
|
||||
모든 HTTP 호출 메서드는 비동기(async)로 구현되어 있습니다.
|
||||
"""
|
||||
|
||||
BASE_URL = "https://api.creatomate.com"
|
||||
|
||||
# 템플릿 설정 (config에서 가져옴)
|
||||
TEMPLATE_CONFIG = {
|
||||
"horizontal": {
|
||||
"template_id": creatomate_settings.TEMPLATE_ID_HORIZONTAL,
|
||||
"duration": creatomate_settings.TEMPLATE_DURATION_HORIZONTAL,
|
||||
},
|
||||
"vertical": {
|
||||
"template_id": creatomate_settings.TEMPLATE_ID_VERTICAL,
|
||||
"duration": creatomate_settings.TEMPLATE_DURATION_VERTICAL,
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
api_key: str | None = None,
|
||||
orientation: OrientationType = "vertical",
|
||||
target_duration: float | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
api_key: Creatomate API 키 (Bearer token으로 사용)
|
||||
None일 경우 config에서 자동으로 가져옴
|
||||
orientation: 영상 방향 ("horizontal" 또는 "vertical", 기본값: "vertical")
|
||||
target_duration: 목표 영상 길이 (초)
|
||||
None일 경우 orientation에 해당하는 기본값 사용
|
||||
"""
|
||||
self.api_key = api_key or apikey_settings.CREATOMATE_API_KEY
|
||||
self.orientation = orientation
|
||||
|
||||
# orientation에 따른 템플릿 설정 가져오기
|
||||
config = self.TEMPLATE_CONFIG.get(
|
||||
orientation, self.TEMPLATE_CONFIG["vertical"]
|
||||
)
|
||||
self.template_id = config["template_id"]
|
||||
self.target_duration = (
|
||||
target_duration if target_duration is not None else config["duration"]
|
||||
)
|
||||
|
||||
self.headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
async def get_all_templates_data(self) -> dict:
|
||||
"""모든 템플릿 정보를 조회합니다."""
|
||||
url = f"{self.BASE_URL}/v1/templates"
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def get_one_template_data(
|
||||
self,
|
||||
template_id: str,
|
||||
use_cache: bool = True,
|
||||
) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다.
|
||||
|
||||
Args:
|
||||
template_id: 조회할 템플릿 ID
|
||||
use_cache: 캐시 사용 여부 (기본: True)
|
||||
|
||||
Returns:
|
||||
템플릿 데이터 (deep copy)
|
||||
"""
|
||||
global _template_cache
|
||||
|
||||
# 캐시 확인
|
||||
if use_cache and template_id in _template_cache:
|
||||
cached = _template_cache[template_id]
|
||||
if _is_cache_valid(cached["cached_at"]):
|
||||
print(f"[CreatomateService] Cache HIT - {template_id}")
|
||||
return copy.deepcopy(cached["data"])
|
||||
else:
|
||||
# 만료된 캐시 삭제
|
||||
del _template_cache[template_id]
|
||||
print(f"[CreatomateService] Cache EXPIRED - {template_id}")
|
||||
|
||||
# API 호출
|
||||
url = f"{self.BASE_URL}/v1/templates/{template_id}"
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# 캐시 저장
|
||||
_template_cache[template_id] = {
|
||||
"data": data,
|
||||
"cached_at": time.time(),
|
||||
}
|
||||
print(f"[CreatomateService] Cache MISS - {template_id} (cached)")
|
||||
|
||||
return copy.deepcopy(data)
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_one_template_data_async(self, template_id: str) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다.
|
||||
|
||||
Deprecated: get_one_template_data()를 사용하세요.
|
||||
"""
|
||||
return await self.get_one_template_data(template_id)
|
||||
|
||||
def parse_template_component_name(self, template_source: list) -> dict:
|
||||
"""템플릿 정보를 파싱하여 리소스 이름을 추출합니다."""
|
||||
|
||||
def recursive_parse_component(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
result_element_name_type = {element["name"]: element["type"]}
|
||||
else:
|
||||
result_element_name_type = {}
|
||||
|
||||
if element["type"] == "composition":
|
||||
minor_component_list = [
|
||||
recursive_parse_component(minor) for minor in element["elements"]
|
||||
]
|
||||
# WARNING: Same name component should shroud other component
|
||||
for minor_component in minor_component_list:
|
||||
result_element_name_type.update(minor_component)
|
||||
|
||||
return result_element_name_type
|
||||
|
||||
result = {}
|
||||
for result_element_dict in [
|
||||
recursive_parse_component(component) for component in template_source
|
||||
]:
|
||||
result.update(result_element_dict)
|
||||
|
||||
return result
|
||||
|
||||
async def template_connect_resource_blackbox(
|
||||
self,
|
||||
template_id: str,
|
||||
image_url_list: list[str],
|
||||
lyric: str,
|
||||
music_url: str,
|
||||
) -> dict:
|
||||
"""템플릿 정보와 이미지/가사/음악 리소스를 매핑합니다.
|
||||
|
||||
Note:
|
||||
- 이미지는 순차적으로 집어넣기
|
||||
- 가사는 개행마다 한 텍스트 삽입
|
||||
- Template에 audio-music 항목이 있어야 함
|
||||
"""
|
||||
template_data = await self.get_one_template_data(template_id)
|
||||
template_component_data = self.parse_template_component_name(
|
||||
template_data["source"]["elements"]
|
||||
)
|
||||
|
||||
lyric = lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def elements_connect_resource_blackbox(
|
||||
self,
|
||||
elements: list,
|
||||
image_url_list: list[str],
|
||||
lyric: str,
|
||||
music_url: str,
|
||||
) -> dict:
|
||||
"""elements 정보와 이미지/가사/음악 리소스를 매핑합니다."""
|
||||
template_component_data = self.parse_template_component_name(elements)
|
||||
|
||||
lyric = lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def modify_element(self, elements: list, modification: dict) -> list:
|
||||
"""elements의 source를 modification에 따라 수정합니다."""
|
||||
|
||||
def recursive_modify(element: dict) -> None:
|
||||
if "name" in element:
|
||||
match element["type"]:
|
||||
case "image":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "audio":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "video":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "text":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "composition":
|
||||
for minor in element["elements"]:
|
||||
recursive_modify(minor)
|
||||
|
||||
for minor in elements:
|
||||
recursive_modify(minor)
|
||||
|
||||
return elements
|
||||
|
||||
async def make_creatomate_call(
|
||||
self, template_id: str, modifications: dict
|
||||
) -> dict:
|
||||
"""Creatomate에 렌더링 요청을 보냅니다.
|
||||
|
||||
Note:
|
||||
response에 요청 정보가 있으니 폴링 필요
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v2/renders"
|
||||
data = {
|
||||
"template_id": template_id,
|
||||
"modifications": modifications,
|
||||
}
|
||||
client = await get_shared_client()
|
||||
response = await client.post(
|
||||
url, json=data, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def make_creatomate_custom_call(self, source: dict) -> dict:
|
||||
"""템플릿 없이 Creatomate에 커스텀 렌더링 요청을 보냅니다.
|
||||
|
||||
Note:
|
||||
response에 요청 정보가 있으니 폴링 필요
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v2/renders"
|
||||
client = await get_shared_client()
|
||||
response = await client.post(
|
||||
url, json=source, headers=self.headers, timeout=60.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def make_creatomate_custom_call_async(self, source: dict) -> dict:
|
||||
"""템플릿 없이 Creatomate에 커스텀 렌더링 요청을 보냅니다.
|
||||
|
||||
Deprecated: make_creatomate_custom_call()을 사용하세요.
|
||||
"""
|
||||
return await self.make_creatomate_custom_call(source)
|
||||
|
||||
async def get_render_status(self, render_id: str) -> dict:
|
||||
"""렌더링 작업의 상태를 조회합니다.
|
||||
|
||||
Args:
|
||||
render_id: Creatomate 렌더 ID
|
||||
|
||||
Returns:
|
||||
렌더링 상태 정보
|
||||
|
||||
Note:
|
||||
상태 값:
|
||||
- planned: 예약됨
|
||||
- waiting: 대기 중
|
||||
- transcribing: 트랜스크립션 중
|
||||
- rendering: 렌더링 중
|
||||
- succeeded: 성공
|
||||
- failed: 실패
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v1/renders/{render_id}"
|
||||
client = await get_shared_client()
|
||||
response = await client.get(url, headers=self.headers, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_render_status_async(self, render_id: str) -> dict:
|
||||
"""렌더링 작업의 상태를 조회합니다.
|
||||
|
||||
Deprecated: get_render_status()를 사용하세요.
|
||||
"""
|
||||
return await self.get_render_status(render_id)
|
||||
|
||||
def calc_scene_duration(self, template: dict) -> float:
|
||||
"""템플릿의 전체 장면 duration을 계산합니다."""
|
||||
total_template_duration = 0.0
|
||||
|
||||
for elem in template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
total_template_duration += elem["duration"]
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
if animation["transition"]:
|
||||
total_template_duration -= animation["duration"]
|
||||
except Exception as e:
|
||||
print(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
||||
|
||||
return total_template_duration
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
||||
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
||||
template["duration"] = target_duration
|
||||
total_template_duration = self.calc_scene_duration(template)
|
||||
extend_rate = target_duration / total_template_duration
|
||||
new_template = copy.deepcopy(template)
|
||||
|
||||
for elem in new_template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
elem["duration"] = elem["duration"] * extend_rate
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
animation["duration"] = animation["duration"] * extend_rate
|
||||
except Exception as e:
|
||||
print(
|
||||
f"[extend_template_duration] Error processing element: {elem}, {e}"
|
||||
)
|
||||
|
||||
return new_template
|
||||
"""
|
||||
Creatomate API 클라이언트 모듈
|
||||
|
||||
API 문서: https://creatomate.com/docs/api
|
||||
|
||||
## 사용법
|
||||
```python
|
||||
from app.utils.creatomate import CreatomateService
|
||||
|
||||
# config에서 자동으로 API 키를 가져옴
|
||||
creatomate = CreatomateService()
|
||||
|
||||
# 또는 명시적으로 API 키 전달
|
||||
creatomate = CreatomateService(api_key="your_api_key")
|
||||
|
||||
# 템플릿 목록 조회 (비동기)
|
||||
templates = await creatomate.get_all_templates_data()
|
||||
|
||||
# 특정 템플릿 조회 (비동기)
|
||||
template = await creatomate.get_one_template_data(template_id)
|
||||
|
||||
# 영상 렌더링 요청 (비동기)
|
||||
response = await creatomate.make_creatomate_call(template_id, modifications)
|
||||
```
|
||||
|
||||
## 성능 최적화
|
||||
- 템플릿 캐싱: 템플릿 데이터는 메모리에 캐싱되어 반복 조회 시 API 호출을 줄입니다.
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀을 재사용합니다.
|
||||
- 캐시 만료: 기본 5분 후 자동 만료 (CACHE_TTL_SECONDS로 조정 가능)
|
||||
"""
|
||||
|
||||
import copy
|
||||
import logging
|
||||
import time
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
|
||||
from config import apikey_settings, creatomate_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Orientation 타입 정의
|
||||
OrientationType = Literal["horizontal", "vertical"]
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 캐시 및 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 템플릿 캐시: {template_id: {"data": dict, "cached_at": float}}
|
||||
_template_cache: dict[str, dict] = {}
|
||||
|
||||
# 캐시 TTL (초) - 기본 5분
|
||||
CACHE_TTL_SECONDS = 300
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_client
|
||||
if _shared_client is None or _shared_client.is_closed:
|
||||
_shared_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(60.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
return _shared_client
|
||||
|
||||
|
||||
async def close_shared_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_client
|
||||
if _shared_client is not None and not _shared_client.is_closed:
|
||||
await _shared_client.aclose()
|
||||
_shared_client = None
|
||||
print("[CreatomateService] Shared HTTP client closed")
|
||||
|
||||
|
||||
def clear_template_cache() -> None:
|
||||
"""템플릿 캐시를 전체 삭제합니다."""
|
||||
global _template_cache
|
||||
_template_cache.clear()
|
||||
print("[CreatomateService] Template cache cleared")
|
||||
|
||||
|
||||
def _is_cache_valid(cached_at: float) -> bool:
|
||||
"""캐시가 유효한지 확인합니다."""
|
||||
return (time.time() - cached_at) < CACHE_TTL_SECONDS
|
||||
|
||||
|
||||
class CreatomateService:
|
||||
"""Creatomate API를 통한 영상 생성 서비스
|
||||
|
||||
모든 HTTP 호출 메서드는 비동기(async)로 구현되어 있습니다.
|
||||
"""
|
||||
|
||||
BASE_URL = "https://api.creatomate.com"
|
||||
|
||||
# 템플릿 설정 (config에서 가져옴)
|
||||
TEMPLATE_CONFIG = {
|
||||
"horizontal": {
|
||||
"template_id": creatomate_settings.TEMPLATE_ID_HORIZONTAL,
|
||||
"duration": creatomate_settings.TEMPLATE_DURATION_HORIZONTAL,
|
||||
},
|
||||
"vertical": {
|
||||
"template_id": creatomate_settings.TEMPLATE_ID_VERTICAL,
|
||||
"duration": creatomate_settings.TEMPLATE_DURATION_VERTICAL,
|
||||
},
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
api_key: str | None = None,
|
||||
orientation: OrientationType = "vertical",
|
||||
target_duration: float | None = None,
|
||||
):
|
||||
"""
|
||||
Args:
|
||||
api_key: Creatomate API 키 (Bearer token으로 사용)
|
||||
None일 경우 config에서 자동으로 가져옴
|
||||
orientation: 영상 방향 ("horizontal" 또는 "vertical", 기본값: "vertical")
|
||||
target_duration: 목표 영상 길이 (초)
|
||||
None일 경우 orientation에 해당하는 기본값 사용
|
||||
"""
|
||||
self.api_key = api_key or apikey_settings.CREATOMATE_API_KEY
|
||||
self.orientation = orientation
|
||||
|
||||
# orientation에 따른 템플릿 설정 가져오기
|
||||
config = self.TEMPLATE_CONFIG.get(
|
||||
orientation, self.TEMPLATE_CONFIG["vertical"]
|
||||
)
|
||||
self.template_id = config["template_id"]
|
||||
self.target_duration = (
|
||||
target_duration if target_duration is not None else config["duration"]
|
||||
)
|
||||
|
||||
self.headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
async def _request(
|
||||
self,
|
||||
method: str,
|
||||
url: str,
|
||||
timeout: float = 30.0,
|
||||
**kwargs,
|
||||
) -> httpx.Response:
|
||||
"""HTTP 요청을 수행합니다.
|
||||
|
||||
Args:
|
||||
method: HTTP 메서드 ("GET", "POST", etc.)
|
||||
url: 요청 URL
|
||||
timeout: 요청 타임아웃 (초)
|
||||
**kwargs: httpx 요청에 전달할 추가 인자
|
||||
|
||||
Returns:
|
||||
httpx.Response: 응답 객체
|
||||
|
||||
Raises:
|
||||
httpx.HTTPError: 요청 실패 시
|
||||
"""
|
||||
logger.info(f"[Creatomate] {method} {url}")
|
||||
print(f"[Creatomate] {method} {url}")
|
||||
|
||||
client = await get_shared_client()
|
||||
|
||||
if method.upper() == "GET":
|
||||
response = await client.get(
|
||||
url, headers=self.headers, timeout=timeout, **kwargs
|
||||
)
|
||||
elif method.upper() == "POST":
|
||||
response = await client.post(
|
||||
url, headers=self.headers, timeout=timeout, **kwargs
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Unsupported HTTP method: {method}")
|
||||
|
||||
logger.info(f"[Creatomate] Response - Status: {response.status_code}")
|
||||
print(f"[Creatomate] Response - Status: {response.status_code}")
|
||||
return response
|
||||
|
||||
async def get_all_templates_data(self) -> dict:
|
||||
"""모든 템플릿 정보를 조회합니다."""
|
||||
url = f"{self.BASE_URL}/v1/templates"
|
||||
response = await self._request("GET", url, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def get_one_template_data(
|
||||
self,
|
||||
template_id: str,
|
||||
use_cache: bool = True,
|
||||
) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다.
|
||||
|
||||
Args:
|
||||
template_id: 조회할 템플릿 ID
|
||||
use_cache: 캐시 사용 여부 (기본: True)
|
||||
|
||||
Returns:
|
||||
템플릿 데이터 (deep copy)
|
||||
"""
|
||||
global _template_cache
|
||||
|
||||
# 캐시 확인
|
||||
if use_cache and template_id in _template_cache:
|
||||
cached = _template_cache[template_id]
|
||||
if _is_cache_valid(cached["cached_at"]):
|
||||
print(f"[CreatomateService] Cache HIT - {template_id}")
|
||||
return copy.deepcopy(cached["data"])
|
||||
else:
|
||||
# 만료된 캐시 삭제
|
||||
del _template_cache[template_id]
|
||||
print(f"[CreatomateService] Cache EXPIRED - {template_id}")
|
||||
|
||||
# API 호출
|
||||
url = f"{self.BASE_URL}/v1/templates/{template_id}"
|
||||
response = await self._request("GET", url, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# 캐시 저장
|
||||
_template_cache[template_id] = {
|
||||
"data": data,
|
||||
"cached_at": time.time(),
|
||||
}
|
||||
print(f"[CreatomateService] Cache MISS - {template_id} (cached)")
|
||||
|
||||
return copy.deepcopy(data)
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_one_template_data_async(self, template_id: str) -> dict:
|
||||
"""특정 템플릿 ID로 템플릿 정보를 조회합니다.
|
||||
|
||||
Deprecated: get_one_template_data()를 사용하세요.
|
||||
"""
|
||||
return await self.get_one_template_data(template_id)
|
||||
|
||||
def parse_template_component_name(self, template_source: list) -> dict:
|
||||
"""템플릿 정보를 파싱하여 리소스 이름을 추출합니다."""
|
||||
|
||||
def recursive_parse_component(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
result_element_name_type = {element["name"]: element["type"]}
|
||||
else:
|
||||
result_element_name_type = {}
|
||||
|
||||
if element["type"] == "composition":
|
||||
minor_component_list = [
|
||||
recursive_parse_component(minor) for minor in element["elements"]
|
||||
]
|
||||
# WARNING: Same name component should shroud other component
|
||||
for minor_component in minor_component_list:
|
||||
result_element_name_type.update(minor_component)
|
||||
|
||||
return result_element_name_type
|
||||
|
||||
result = {}
|
||||
for result_element_dict in [
|
||||
recursive_parse_component(component) for component in template_source
|
||||
]:
|
||||
result.update(result_element_dict)
|
||||
|
||||
return result
|
||||
|
||||
async def template_connect_resource_blackbox(
|
||||
self,
|
||||
template_id: str,
|
||||
image_url_list: list[str],
|
||||
lyric: str,
|
||||
music_url: str,
|
||||
) -> dict:
|
||||
"""템플릿 정보와 이미지/가사/음악 리소스를 매핑합니다.
|
||||
|
||||
Note:
|
||||
- 이미지는 순차적으로 집어넣기
|
||||
- 가사는 개행마다 한 텍스트 삽입
|
||||
- Template에 audio-music 항목이 있어야 함
|
||||
"""
|
||||
template_data = await self.get_one_template_data(template_id)
|
||||
template_component_data = self.parse_template_component_name(
|
||||
template_data["source"]["elements"]
|
||||
)
|
||||
|
||||
lyric = lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def elements_connect_resource_blackbox(
|
||||
self,
|
||||
elements: list,
|
||||
image_url_list: list[str],
|
||||
lyric: str,
|
||||
music_url: str,
|
||||
) -> dict:
|
||||
"""elements 정보와 이미지/가사/음악 리소스를 매핑합니다."""
|
||||
template_component_data = self.parse_template_component_name(elements)
|
||||
|
||||
lyric = lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def modify_element(self, elements: list, modification: dict) -> list:
|
||||
"""elements의 source를 modification에 따라 수정합니다."""
|
||||
|
||||
def recursive_modify(element: dict) -> None:
|
||||
if "name" in element:
|
||||
match element["type"]:
|
||||
case "image":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "audio":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "video":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "text":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "composition":
|
||||
for minor in element["elements"]:
|
||||
recursive_modify(minor)
|
||||
|
||||
for minor in elements:
|
||||
recursive_modify(minor)
|
||||
|
||||
return elements
|
||||
|
||||
async def make_creatomate_call(
|
||||
self, template_id: str, modifications: dict
|
||||
) -> dict:
|
||||
"""Creatomate에 렌더링 요청을 보냅니다.
|
||||
|
||||
Note:
|
||||
response에 요청 정보가 있으니 폴링 필요
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v2/renders"
|
||||
data = {
|
||||
"template_id": template_id,
|
||||
"modifications": modifications,
|
||||
}
|
||||
response = await self._request("POST", url, timeout=60.0, json=data)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
async def make_creatomate_custom_call(self, source: dict) -> dict:
|
||||
"""템플릿 없이 Creatomate에 커스텀 렌더링 요청을 보냅니다.
|
||||
|
||||
Note:
|
||||
response에 요청 정보가 있으니 폴링 필요
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v2/renders"
|
||||
response = await self._request("POST", url, timeout=60.0, json=source)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def make_creatomate_custom_call_async(self, source: dict) -> dict:
|
||||
"""템플릿 없이 Creatomate에 커스텀 렌더링 요청을 보냅니다.
|
||||
|
||||
Deprecated: make_creatomate_custom_call()을 사용하세요.
|
||||
"""
|
||||
return await self.make_creatomate_custom_call(source)
|
||||
|
||||
async def get_render_status(self, render_id: str) -> dict:
|
||||
"""렌더링 작업의 상태를 조회합니다.
|
||||
|
||||
Args:
|
||||
render_id: Creatomate 렌더 ID
|
||||
|
||||
Returns:
|
||||
렌더링 상태 정보
|
||||
|
||||
Note:
|
||||
상태 값:
|
||||
- planned: 예약됨
|
||||
- waiting: 대기 중
|
||||
- transcribing: 트랜스크립션 중
|
||||
- rendering: 렌더링 중
|
||||
- succeeded: 성공
|
||||
- failed: 실패
|
||||
"""
|
||||
url = f"{self.BASE_URL}/v1/renders/{render_id}"
|
||||
response = await self._request("GET", url, timeout=30.0)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
|
||||
# 하위 호환성을 위한 별칭 (deprecated)
|
||||
async def get_render_status_async(self, render_id: str) -> dict:
|
||||
"""렌더링 작업의 상태를 조회합니다.
|
||||
|
||||
Deprecated: get_render_status()를 사용하세요.
|
||||
"""
|
||||
return await self.get_render_status(render_id)
|
||||
|
||||
def calc_scene_duration(self, template: dict) -> float:
|
||||
"""템플릿의 전체 장면 duration을 계산합니다."""
|
||||
total_template_duration = 0.0
|
||||
|
||||
for elem in template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
total_template_duration += elem["duration"]
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
if animation["transition"]:
|
||||
total_template_duration -= animation["duration"]
|
||||
except Exception as e:
|
||||
print(f"[calc_scene_duration] Error processing element: {elem}, {e}")
|
||||
|
||||
return total_template_duration
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float) -> dict:
|
||||
"""템플릿의 duration을 target_duration으로 확장합니다."""
|
||||
template["duration"] = target_duration
|
||||
total_template_duration = self.calc_scene_duration(template)
|
||||
extend_rate = target_duration / total_template_duration
|
||||
new_template = copy.deepcopy(template)
|
||||
|
||||
for elem in new_template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
elem["duration"] = elem["duration"] * extend_rate
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
animation["duration"] = animation["duration"] * extend_rate
|
||||
except Exception as e:
|
||||
print(
|
||||
f"[extend_template_duration] Error processing element: {elem}, {e}"
|
||||
)
|
||||
|
||||
return new_template
|
||||
+163
-114
@@ -1,114 +1,163 @@
|
||||
import json
|
||||
import re
|
||||
|
||||
import aiohttp
|
||||
|
||||
from config import crawler_settings
|
||||
|
||||
|
||||
class GraphQLException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NvMapScraper:
|
||||
GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql"
|
||||
|
||||
OVERVIEW_QUERY: str = """
|
||||
query getAccommodation($id: String!, $deviceType: String) {
|
||||
business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) {
|
||||
base {
|
||||
id
|
||||
name
|
||||
category
|
||||
roadAddress
|
||||
address
|
||||
phone
|
||||
virtualPhone
|
||||
microReviews
|
||||
conveniences
|
||||
visitorReviewsTotal
|
||||
}
|
||||
images { images { origin url } }
|
||||
cpImages(source: [ugcImage]) { images { origin url } }
|
||||
}
|
||||
}"""
|
||||
|
||||
DEFAULT_HEADERS: dict = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
|
||||
"Referer": "https://map.naver.com/",
|
||||
"Origin": "https://map.naver.com",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def __init__(self, url: str, cookies: str | None = None):
|
||||
self.url = url
|
||||
self.cookies = (
|
||||
cookies if cookies is not None else crawler_settings.NAVER_COOKIES
|
||||
)
|
||||
self.scrap_type: str | None = None
|
||||
self.rawdata: dict | None = None
|
||||
self.image_link_list: list[str] | None = None
|
||||
self.base_info: dict | None = None
|
||||
|
||||
def _get_request_headers(self) -> dict:
|
||||
headers = self.DEFAULT_HEADERS.copy()
|
||||
if self.cookies:
|
||||
headers["Cookie"] = self.cookies
|
||||
return headers
|
||||
|
||||
def parse_url(self) -> str:
|
||||
place_pattern = r"/place/(\d+)"
|
||||
match = re.search(place_pattern, self.url)
|
||||
if not match:
|
||||
raise GraphQLException("Failed to parse place ID from URL")
|
||||
return match[1]
|
||||
|
||||
async def scrap(self):
|
||||
try:
|
||||
place_id = self.parse_url()
|
||||
data = await self._call_get_accommodation(place_id)
|
||||
self.rawdata = data
|
||||
self.image_link_list = [
|
||||
nv_image["origin"]
|
||||
for nv_image in data["data"]["business"]["images"]["images"]
|
||||
]
|
||||
self.base_info = data["data"]["business"]["base"]
|
||||
self.scrap_type = "GraphQL"
|
||||
|
||||
except GraphQLException:
|
||||
print("fallback")
|
||||
self.scrap_type = "Playwright"
|
||||
pass # 나중에 pw 이용한 crawling으로 fallback 추가
|
||||
|
||||
return
|
||||
|
||||
async def _call_get_accommodation(self, place_id: str) -> dict:
|
||||
payload = {
|
||||
"operationName": "getAccommodation",
|
||||
"variables": {"id": place_id, "deviceType": "pc"},
|
||||
"query": self.OVERVIEW_QUERY,
|
||||
}
|
||||
json_payload = json.dumps(payload)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(
|
||||
self.GRAPHQL_URL, data=json_payload, headers=self._get_request_headers()
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
return await response.json()
|
||||
else:
|
||||
print("실패 상태 코드:", response.status)
|
||||
raise GraphQLException(
|
||||
f"Request failed with status {response.status}"
|
||||
)
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# import asyncio
|
||||
|
||||
# url = "https://map.naver.com/p/search/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/place/1133638931?c=14.70,0,0,0,dh&placePath=/photo?businessCategory=pension&fromPanelNum=2&locale=ko&searchText=%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84&svcName=map_pcv5×tamp=202512191123&fromPanelNum=2&locale=ko&searchText=%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84&svcName=map_pcv5×tamp=202512191007&from=map&entry=bmp&filterType=%EC%97%85%EC%B2%B4&businessCategory=pension"
|
||||
# scraper = NvMapScraper(url)
|
||||
# asyncio.run(scraper.scrap())
|
||||
# print(scraper.image_link_list)
|
||||
# print(len(scraper.image_link_list) if scraper.image_link_list else 0)
|
||||
# print(scraper.base_info)
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
import aiohttp
|
||||
|
||||
from config import crawler_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GraphQLException(Exception):
|
||||
"""GraphQL 요청 실패 시 발생하는 예외"""
|
||||
pass
|
||||
|
||||
|
||||
class CrawlingTimeoutException(Exception):
|
||||
"""크롤링 타임아웃 시 발생하는 예외"""
|
||||
pass
|
||||
|
||||
|
||||
class NvMapScraper:
|
||||
"""네이버 지도 GraphQL API 스크래퍼
|
||||
|
||||
네이버 지도에서 숙소/장소 정보를 크롤링합니다.
|
||||
"""
|
||||
|
||||
GRAPHQL_URL: str = "https://pcmap-api.place.naver.com/graphql"
|
||||
REQUEST_TIMEOUT = 30 # 초
|
||||
|
||||
OVERVIEW_QUERY: str = """
|
||||
query getAccommodation($id: String!, $deviceType: String) {
|
||||
business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) {
|
||||
base {
|
||||
id
|
||||
name
|
||||
category
|
||||
roadAddress
|
||||
address
|
||||
phone
|
||||
virtualPhone
|
||||
microReviews
|
||||
conveniences
|
||||
visitorReviewsTotal
|
||||
}
|
||||
images { images { origin url } }
|
||||
cpImages(source: [ugcImage]) { images { origin url } }
|
||||
}
|
||||
}"""
|
||||
|
||||
DEFAULT_HEADERS: dict = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
|
||||
"Referer": "https://map.naver.com/",
|
||||
"Origin": "https://map.naver.com",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def __init__(self, url: str, cookies: str | None = None):
|
||||
self.url = url
|
||||
self.cookies = (
|
||||
cookies if cookies is not None else crawler_settings.NAVER_COOKIES
|
||||
)
|
||||
self.scrap_type: str | None = None
|
||||
self.rawdata: dict | None = None
|
||||
self.image_link_list: list[str] | None = None
|
||||
self.base_info: dict | None = None
|
||||
|
||||
def _get_request_headers(self) -> dict:
|
||||
headers = self.DEFAULT_HEADERS.copy()
|
||||
if self.cookies:
|
||||
headers["Cookie"] = self.cookies
|
||||
return headers
|
||||
|
||||
def parse_url(self) -> str:
|
||||
place_pattern = r"/place/(\d+)"
|
||||
match = re.search(place_pattern, self.url)
|
||||
if not match:
|
||||
raise GraphQLException("Failed to parse place ID from URL")
|
||||
return match[1]
|
||||
|
||||
async def scrap(self):
|
||||
try:
|
||||
place_id = self.parse_url()
|
||||
data = await self._call_get_accommodation(place_id)
|
||||
self.rawdata = data
|
||||
self.image_link_list = [
|
||||
nv_image["origin"]
|
||||
for nv_image in data["data"]["business"]["images"]["images"]
|
||||
]
|
||||
self.base_info = data["data"]["business"]["base"]
|
||||
self.scrap_type = "GraphQL"
|
||||
|
||||
except GraphQLException:
|
||||
print("fallback")
|
||||
self.scrap_type = "Playwright"
|
||||
pass # 나중에 pw 이용한 crawling으로 fallback 추가
|
||||
|
||||
return
|
||||
|
||||
async def _call_get_accommodation(self, place_id: str) -> dict:
|
||||
"""GraphQL API를 호출하여 숙소 정보를 가져옵니다.
|
||||
|
||||
Args:
|
||||
place_id: 네이버 지도 장소 ID
|
||||
|
||||
Returns:
|
||||
GraphQL 응답 데이터
|
||||
|
||||
Raises:
|
||||
GraphQLException: API 호출 실패 시
|
||||
CrawlingTimeoutException: 타임아웃 발생 시
|
||||
"""
|
||||
payload = {
|
||||
"operationName": "getAccommodation",
|
||||
"variables": {"id": place_id, "deviceType": "pc"},
|
||||
"query": self.OVERVIEW_QUERY,
|
||||
}
|
||||
json_payload = json.dumps(payload)
|
||||
timeout = aiohttp.ClientTimeout(total=self.REQUEST_TIMEOUT)
|
||||
|
||||
try:
|
||||
logger.info(f"[NvMapScraper] Requesting place_id: {place_id}")
|
||||
print(f"[NvMapScraper] Requesting place_id: {place_id}")
|
||||
|
||||
async with aiohttp.ClientSession(timeout=timeout) as session:
|
||||
async with session.post(
|
||||
self.GRAPHQL_URL,
|
||||
data=json_payload,
|
||||
headers=self._get_request_headers()
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
logger.info(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] SUCCESS - place_id: {place_id}")
|
||||
return await response.json()
|
||||
|
||||
# 실패 상태 코드
|
||||
logger.error(f"[NvMapScraper] Failed with status {response.status} - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] 실패 상태 코드: {response.status}")
|
||||
raise GraphQLException(
|
||||
f"Request failed with status {response.status}"
|
||||
)
|
||||
|
||||
except TimeoutError:
|
||||
logger.error(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
print(f"[NvMapScraper] Timeout - place_id: {place_id}")
|
||||
raise CrawlingTimeoutException(f"Request timed out after {self.REQUEST_TIMEOUT}s")
|
||||
|
||||
except aiohttp.ClientError as e:
|
||||
logger.error(f"[NvMapScraper] Client error: {e}")
|
||||
print(f"[NvMapScraper] Client error: {e}")
|
||||
raise GraphQLException(f"Client error: {e}")
|
||||
|
||||
|
||||
# if __name__ == "__main__":
|
||||
# import asyncio
|
||||
|
||||
# url = "https://map.naver.com/p/search/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/place/1133638931?c=14.70,0,0,0,dh&placePath=/photo?businessCategory=pension&fromPanelNum=2&locale=ko&searchText=%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84&svcName=map_pcv5×tamp=202512191123&fromPanelNum=2&locale=ko&searchText=%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84&svcName=map_pcv5×tamp=202512191007&from=map&entry=bmp&filterType=%EC%97%85%EC%B2%B4&businessCategory=pension"
|
||||
# scraper = NvMapScraper(url)
|
||||
# asyncio.run(scraper.scrap())
|
||||
# print(scraper.image_link_list)
|
||||
# print(len(scraper.image_link_list) if scraper.image_link_list else 0)
|
||||
# print(scraper.base_info)
|
||||
+468
-443
@@ -1,443 +1,468 @@
|
||||
"""
|
||||
Azure Blob Storage 업로드 유틸리티
|
||||
|
||||
Azure Blob Storage에 파일을 업로드하는 클래스를 제공합니다.
|
||||
파일 경로 또는 바이트 데이터를 직접 업로드할 수 있습니다.
|
||||
|
||||
URL 경로 형식:
|
||||
- 음악: {BASE_URL}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{task_id}/image/{파일명}
|
||||
|
||||
사용 예시:
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
|
||||
# 파일 경로로 업로드
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
|
||||
# 바이트 데이터로 직접 업로드 (media 저장 없이)
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
success = await uploader.upload_image_bytes(image_bytes, "my_image.png")
|
||||
|
||||
print(uploader.public_url) # 마지막 업로드의 공개 URL
|
||||
|
||||
성능 최적화:
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀 재사용
|
||||
- 동시 업로드: 공유 클라이언트를 통해 동시 요청 처리가 개선됩니다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
import httpx
|
||||
|
||||
from config import azure_blob_settings
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_blob_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_blob_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is None or _shared_blob_client.is_closed:
|
||||
print("[AzureBlobUploader] Creating shared HTTP client...")
|
||||
_shared_blob_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(180.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
print("[AzureBlobUploader] Shared HTTP client created - "
|
||||
"max_connections: 20, max_keepalive: 10")
|
||||
return _shared_blob_client
|
||||
|
||||
|
||||
async def close_shared_blob_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is not None and not _shared_blob_client.is_closed:
|
||||
await _shared_blob_client.aclose()
|
||||
_shared_blob_client = None
|
||||
print("[AzureBlobUploader] Shared HTTP client closed")
|
||||
|
||||
|
||||
class AzureBlobUploader:
|
||||
"""Azure Blob Storage 업로드 클래스
|
||||
|
||||
Azure Blob Storage에 음악, 영상, 이미지 파일을 업로드합니다.
|
||||
URL 형식: {BASE_URL}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
|
||||
카테고리별 경로:
|
||||
- 음악: {task_id}/song/{file_name}
|
||||
- 영상: {task_id}/video/{file_name}
|
||||
- 이미지: {task_id}/image/{file_name}
|
||||
|
||||
Attributes:
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
|
||||
# Content-Type 매핑
|
||||
IMAGE_CONTENT_TYPES = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".bmp": "image/bmp",
|
||||
}
|
||||
|
||||
def __init__(self, task_id: str):
|
||||
"""AzureBlobUploader 초기화
|
||||
|
||||
Args:
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@property
|
||||
def task_id(self) -> str:
|
||||
"""작업 고유 식별자"""
|
||||
return self._task_id
|
||||
|
||||
@property
|
||||
def public_url(self) -> str:
|
||||
"""마지막 업로드의 공개 URL (SAS 토큰 제외)"""
|
||||
return self._last_public_url
|
||||
|
||||
def _build_upload_url(self, category: str, file_name: str) -> str:
|
||||
"""업로드 URL 생성 (SAS 토큰 포함)"""
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
sas_token = self._sas_token.strip("?'\"")
|
||||
return (
|
||||
f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
)
|
||||
|
||||
def _build_public_url(self, category: str, file_name: str) -> str:
|
||||
"""공개 URL 생성 (SAS 토큰 제외)"""
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
|
||||
|
||||
async def _upload_bytes(
|
||||
self,
|
||||
file_content: bytes,
|
||||
upload_url: str,
|
||||
headers: dict,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
) -> bool:
|
||||
"""바이트 데이터를 업로드하는 공통 내부 메서드"""
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
print(f"[{log_prefix}] Getting shared client...")
|
||||
client = await get_shared_blob_client()
|
||||
client_time = time.perf_counter()
|
||||
elapsed_ms = (client_time - start_time) * 1000
|
||||
print(f"[{log_prefix}] Client acquired in {elapsed_ms:.1f}ms")
|
||||
|
||||
size = len(file_content)
|
||||
print(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
upload_time = time.perf_counter()
|
||||
duration_ms = (upload_time - start_time) * 1000
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
print(f"[{log_prefix}] SUCCESS - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
else:
|
||||
print(f"[{log_prefix}] FAILED - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Response: {response.text[:500]}")
|
||||
return False
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s "
|
||||
f"(limit: {timeout}s)")
|
||||
return False
|
||||
except httpx.ConnectError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] CONNECT_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
except httpx.ReadError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] READ_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
print(f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
self,
|
||||
file_path: str,
|
||||
category: str,
|
||||
content_type: str,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
) -> bool:
|
||||
"""파일을 Azure Blob Storage에 업로드하는 내부 메서드
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
category: 카테고리 (song, video, image)
|
||||
content_type: Content-Type 헤더 값
|
||||
timeout: 요청 타임아웃 (초)
|
||||
log_prefix: 로그 접두사
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
"""
|
||||
# 파일 경로에서 파일명 추출
|
||||
file_name = Path(file_path).name
|
||||
|
||||
upload_url = self._build_upload_url(category, file_name)
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
file_content = await file.read()
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
"""음악 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="song",
|
||||
content_type="audio/mpeg",
|
||||
timeout=120.0,
|
||||
log_prefix="upload_music",
|
||||
)
|
||||
|
||||
async def upload_music_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명 (확장자가 없으면 .mp3 추가)
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp3 추가
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp3"
|
||||
|
||||
upload_url = self._build_upload_url("song", file_name)
|
||||
self._last_public_url = self._build_public_url("song", file_name)
|
||||
log_prefix = "upload_music_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=120.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_video(self, file_path: str) -> bool:
|
||||
"""영상 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="video",
|
||||
content_type="video/mp4",
|
||||
timeout=180.0,
|
||||
log_prefix="upload_video",
|
||||
)
|
||||
|
||||
async def upload_video_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명 (확장자가 없으면 .mp4 추가)
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp4 추가
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp4"
|
||||
|
||||
upload_url = self._build_upload_url("video", file_name)
|
||||
self._last_public_url = self._build_public_url("video", file_name)
|
||||
log_prefix = "upload_video_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=180.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_image(self, file_path: str) -> bool:
|
||||
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_path).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="image",
|
||||
content_type=content_type,
|
||||
timeout=60.0,
|
||||
log_prefix="upload_image",
|
||||
)
|
||||
|
||||
async def upload_image_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
with open("my_image.png", "rb") as f:
|
||||
content = f.read()
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=60.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
|
||||
# 사용 예시:
|
||||
# import asyncio
|
||||
#
|
||||
# async def main():
|
||||
# uploader = AzureBlobUploader(task_id="task-123")
|
||||
#
|
||||
# # 음악 업로드 -> {BASE_URL}/task-123/song/my_song.mp3
|
||||
# await uploader.upload_music("my_song.mp3")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 영상 업로드 -> {BASE_URL}/task-123/video/my_video.mp4
|
||||
# await uploader.upload_video("my_video.mp4")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 이미지 업로드 -> {BASE_URL}/task-123/image/my_image.png
|
||||
# await uploader.upload_image("my_image.png")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# asyncio.run(main())
|
||||
"""
|
||||
Azure Blob Storage 업로드 유틸리티
|
||||
|
||||
Azure Blob Storage에 파일을 업로드하는 클래스를 제공합니다.
|
||||
파일 경로 또는 바이트 데이터를 직접 업로드할 수 있습니다.
|
||||
|
||||
URL 경로 형식:
|
||||
- 음악: {BASE_URL}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{task_id}/image/{파일명}
|
||||
|
||||
사용 예시:
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
|
||||
# 파일 경로로 업로드
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
|
||||
# 바이트 데이터로 직접 업로드 (media 저장 없이)
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
success = await uploader.upload_image_bytes(image_bytes, "my_image.png")
|
||||
|
||||
print(uploader.public_url) # 마지막 업로드의 공개 URL
|
||||
|
||||
성능 최적화:
|
||||
- HTTP 클라이언트 재사용: 모듈 레벨의 공유 클라이언트로 커넥션 풀 재사용
|
||||
- 동시 업로드: 공유 클라이언트를 통해 동시 요청 처리가 개선됩니다.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import aiofiles
|
||||
import httpx
|
||||
|
||||
from config import azure_blob_settings
|
||||
|
||||
# 로거 설정
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# =============================================================================
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (싱글톤 패턴)
|
||||
# =============================================================================
|
||||
|
||||
# 모듈 레벨 공유 HTTP 클라이언트 (커넥션 풀 재사용)
|
||||
_shared_blob_client: httpx.AsyncClient | None = None
|
||||
|
||||
|
||||
async def get_shared_blob_client() -> httpx.AsyncClient:
|
||||
"""공유 HTTP 클라이언트를 반환합니다. 없으면 생성합니다."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is None or _shared_blob_client.is_closed:
|
||||
print("[AzureBlobUploader] Creating shared HTTP client...")
|
||||
_shared_blob_client = httpx.AsyncClient(
|
||||
timeout=httpx.Timeout(180.0, connect=10.0),
|
||||
limits=httpx.Limits(max_keepalive_connections=10, max_connections=20),
|
||||
)
|
||||
print("[AzureBlobUploader] Shared HTTP client created - "
|
||||
"max_connections: 20, max_keepalive: 10")
|
||||
return _shared_blob_client
|
||||
|
||||
|
||||
async def close_shared_blob_client() -> None:
|
||||
"""공유 HTTP 클라이언트를 닫습니다. 앱 종료 시 호출하세요."""
|
||||
global _shared_blob_client
|
||||
if _shared_blob_client is not None and not _shared_blob_client.is_closed:
|
||||
await _shared_blob_client.aclose()
|
||||
_shared_blob_client = None
|
||||
print("[AzureBlobUploader] Shared HTTP client closed")
|
||||
|
||||
|
||||
class AzureBlobUploader:
|
||||
"""Azure Blob Storage 업로드 클래스
|
||||
|
||||
Azure Blob Storage에 음악, 영상, 이미지 파일을 업로드합니다.
|
||||
URL 형식: {BASE_URL}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
|
||||
카테고리별 경로:
|
||||
- 음악: {task_id}/song/{file_name}
|
||||
- 영상: {task_id}/video/{file_name}
|
||||
- 이미지: {task_id}/image/{file_name}
|
||||
|
||||
Attributes:
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
|
||||
# Content-Type 매핑
|
||||
IMAGE_CONTENT_TYPES = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".gif": "image/gif",
|
||||
".webp": "image/webp",
|
||||
".bmp": "image/bmp",
|
||||
}
|
||||
|
||||
def __init__(self, task_id: str):
|
||||
"""AzureBlobUploader 초기화
|
||||
|
||||
Args:
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@property
|
||||
def task_id(self) -> str:
|
||||
"""작업 고유 식별자"""
|
||||
return self._task_id
|
||||
|
||||
@property
|
||||
def public_url(self) -> str:
|
||||
"""마지막 업로드의 공개 URL (SAS 토큰 제외)"""
|
||||
return self._last_public_url
|
||||
|
||||
def _build_upload_url(self, category: str, file_name: str) -> str:
|
||||
"""업로드 URL 생성 (SAS 토큰 포함)"""
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
sas_token = self._sas_token.strip("?'\"")
|
||||
return (
|
||||
f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
)
|
||||
|
||||
def _build_public_url(self, category: str, file_name: str) -> str:
|
||||
"""공개 URL 생성 (SAS 토큰 제외)"""
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
|
||||
|
||||
async def _upload_bytes(
|
||||
self,
|
||||
file_content: bytes,
|
||||
upload_url: str,
|
||||
headers: dict,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
) -> bool:
|
||||
"""바이트 데이터를 업로드하는 공통 내부 메서드
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 바이트 데이터
|
||||
upload_url: 업로드 URL
|
||||
headers: HTTP 헤더
|
||||
timeout: 요청 타임아웃 (초)
|
||||
log_prefix: 로그 접두사
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
"""
|
||||
size = len(file_content)
|
||||
start_time = time.perf_counter()
|
||||
|
||||
try:
|
||||
logger.info(f"[{log_prefix}] Starting upload")
|
||||
print(f"[{log_prefix}] Getting shared client...")
|
||||
|
||||
client = await get_shared_blob_client()
|
||||
client_time = time.perf_counter()
|
||||
elapsed_ms = (client_time - start_time) * 1000
|
||||
print(f"[{log_prefix}] Client acquired in {elapsed_ms:.1f}ms")
|
||||
|
||||
print(f"[{log_prefix}] Starting upload... "
|
||||
f"(size: {size} bytes, timeout: {timeout}s)")
|
||||
|
||||
response = await asyncio.wait_for(
|
||||
client.put(upload_url, content=file_content, headers=headers),
|
||||
timeout=timeout,
|
||||
)
|
||||
upload_time = time.perf_counter()
|
||||
duration_ms = (upload_time - start_time) * 1000
|
||||
|
||||
if response.status_code in [200, 201]:
|
||||
logger.info(f"[{log_prefix}] SUCCESS - Status: {response.status_code}")
|
||||
print(f"[{log_prefix}] SUCCESS - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Public URL: {self._last_public_url}")
|
||||
return True
|
||||
|
||||
# 업로드 실패
|
||||
logger.error(f"[{log_prefix}] FAILED - Status: {response.status_code}")
|
||||
print(f"[{log_prefix}] FAILED - Status: {response.status_code}, "
|
||||
f"Duration: {duration_ms:.1f}ms")
|
||||
print(f"[{log_prefix}] Response: {response.text[:500]}")
|
||||
return False
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
print(f"[{log_prefix}] TIMEOUT after {elapsed:.1f}s")
|
||||
return False
|
||||
|
||||
except httpx.ConnectError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] CONNECT_ERROR: {e}")
|
||||
print(f"[{log_prefix}] CONNECT_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
except httpx.ReadError as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] READ_ERROR: {e}")
|
||||
print(f"[{log_prefix}] READ_ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
elapsed = time.perf_counter() - start_time
|
||||
logger.error(f"[{log_prefix}] ERROR: {type(e).__name__}: {e}")
|
||||
print(f"[{log_prefix}] ERROR after {elapsed:.1f}s - "
|
||||
f"{type(e).__name__}: {e}")
|
||||
return False
|
||||
|
||||
async def _upload_file(
|
||||
self,
|
||||
file_path: str,
|
||||
category: str,
|
||||
content_type: str,
|
||||
timeout: float,
|
||||
log_prefix: str,
|
||||
) -> bool:
|
||||
"""파일을 Azure Blob Storage에 업로드하는 내부 메서드
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
category: 카테고리 (song, video, image)
|
||||
content_type: Content-Type 헤더 값
|
||||
timeout: 요청 타임아웃 (초)
|
||||
log_prefix: 로그 접두사
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
"""
|
||||
# 파일 경로에서 파일명 추출
|
||||
file_name = Path(file_path).name
|
||||
|
||||
upload_url = self._build_upload_url(category, file_name)
|
||||
self._last_public_url = self._build_public_url(category, file_name)
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
async with aiofiles.open(file_path, "rb") as file:
|
||||
file_content = await file.read()
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=timeout,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
"""음악 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="song",
|
||||
content_type="audio/mpeg",
|
||||
timeout=120.0,
|
||||
log_prefix="upload_music",
|
||||
)
|
||||
|
||||
async def upload_music_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명 (확장자가 없으면 .mp3 추가)
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp3 추가
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp3"
|
||||
|
||||
upload_url = self._build_upload_url("song", file_name)
|
||||
self._last_public_url = self._build_public_url("song", file_name)
|
||||
log_prefix = "upload_music_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "audio/mpeg", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=120.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_video(self, file_path: str) -> bool:
|
||||
"""영상 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="video",
|
||||
content_type="video/mp4",
|
||||
timeout=180.0,
|
||||
log_prefix="upload_video",
|
||||
)
|
||||
|
||||
async def upload_video_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명 (확장자가 없으면 .mp4 추가)
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
# 확장자가 없으면 .mp4 추가
|
||||
if not Path(file_name).suffix:
|
||||
file_name = f"{file_name}.mp4"
|
||||
|
||||
upload_url = self._build_upload_url("video", file_name)
|
||||
self._last_public_url = self._build_public_url("video", file_name)
|
||||
log_prefix = "upload_video_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": "video/mp4", "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=180.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
async def upload_image(self, file_path: str) -> bool:
|
||||
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_path).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
return await self._upload_file(
|
||||
file_path=file_path,
|
||||
category="image",
|
||||
content_type=content_type,
|
||||
timeout=60.0,
|
||||
log_prefix="upload_image",
|
||||
)
|
||||
|
||||
async def upload_image_bytes(
|
||||
self, file_content: bytes, file_name: str
|
||||
) -> bool:
|
||||
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
file_name: 저장할 파일명
|
||||
|
||||
Returns:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
with open("my_image.png", "rb") as f:
|
||||
content = f.read()
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
extension = Path(file_name).suffix.lower()
|
||||
content_type = self.IMAGE_CONTENT_TYPES.get(extension, "image/jpeg")
|
||||
|
||||
upload_url = self._build_upload_url("image", file_name)
|
||||
self._last_public_url = self._build_public_url("image", file_name)
|
||||
log_prefix = "upload_image_bytes"
|
||||
print(f"[{log_prefix}] URL (without SAS): {self._last_public_url}")
|
||||
|
||||
headers = {"Content-Type": content_type, "x-ms-blob-type": "BlockBlob"}
|
||||
|
||||
return await self._upload_bytes(
|
||||
file_content=file_content,
|
||||
upload_url=upload_url,
|
||||
headers=headers,
|
||||
timeout=60.0,
|
||||
log_prefix=log_prefix,
|
||||
)
|
||||
|
||||
|
||||
# 사용 예시:
|
||||
# import asyncio
|
||||
#
|
||||
# async def main():
|
||||
# uploader = AzureBlobUploader(task_id="task-123")
|
||||
#
|
||||
# # 음악 업로드 -> {BASE_URL}/task-123/song/my_song.mp3
|
||||
# await uploader.upload_music("my_song.mp3")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 영상 업로드 -> {BASE_URL}/task-123/video/my_video.mp4
|
||||
# await uploader.upload_video("my_video.mp4")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 이미지 업로드 -> {BASE_URL}/task-123/image/my_image.png
|
||||
# await uploader.upload_image("my_image.png")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# asyncio.run(main())
|
||||
Reference in new issue
Block a user