mirror of
https://github.com/won-ktds/smarketing-backend.git
synced 2025-12-06 07:06:24 +00:00
Merge branch 'main' of https://github.com/won-ktds/smarketing-backend
This commit is contained in:
commit
7b486d853d
2
smarketing-ai/.gitignore
vendored
Normal file
2
smarketing-ai/.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
.idea
|
||||||
|
.env
|
||||||
25
smarketing-ai/Dockerfile
Normal file
25
smarketing-ai/Dockerfile
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# Dockerfile
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 시스템 패키지 설치
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
fonts-dejavu-core \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Python 의존성 설치
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# 애플리케이션 코드 복사
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# 업로드 디렉토리 생성
|
||||||
|
RUN mkdir -p uploads/temp templates/poster_templates
|
||||||
|
|
||||||
|
# 포트 노출
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
# 애플리케이션 실행
|
||||||
|
CMD ["python", "app.py"]
|
||||||
@ -12,6 +12,8 @@ from config.config import Config
|
|||||||
from services.content_service import ContentService
|
from services.content_service import ContentService
|
||||||
from services.poster_service import PosterService
|
from services.poster_service import PosterService
|
||||||
from models.request_models import ContentRequest, PosterRequest
|
from models.request_models import ContentRequest, PosterRequest
|
||||||
|
|
||||||
|
|
||||||
def create_app():
|
def create_app():
|
||||||
"""Flask 애플리케이션 팩토리"""
|
"""Flask 애플리케이션 팩토리"""
|
||||||
app = Flask(__name__)
|
app = Flask(__name__)
|
||||||
@ -25,6 +27,7 @@ def create_app():
|
|||||||
# 서비스 인스턴스 생성
|
# 서비스 인스턴스 생성
|
||||||
content_service = ContentService()
|
content_service = ContentService()
|
||||||
poster_service = PosterService()
|
poster_service = PosterService()
|
||||||
|
|
||||||
@app.route('/health', methods=['GET'])
|
@app.route('/health', methods=['GET'])
|
||||||
def health_check():
|
def health_check():
|
||||||
"""헬스 체크 API"""
|
"""헬스 체크 API"""
|
||||||
@ -33,6 +36,7 @@ def create_app():
|
|||||||
'timestamp': datetime.now().isoformat(),
|
'timestamp': datetime.now().isoformat(),
|
||||||
'service': 'AI Marketing Service'
|
'service': 'AI Marketing Service'
|
||||||
})
|
})
|
||||||
|
|
||||||
@app.route('/api/content/generate', methods=['POST'])
|
@app.route('/api/content/generate', methods=['POST'])
|
||||||
def generate_content():
|
def generate_content():
|
||||||
"""
|
"""
|
||||||
@ -84,6 +88,7 @@ def create_app():
|
|||||||
app.logger.error(f"콘텐츠 생성 중 오류 발생: {str(e)}")
|
app.logger.error(f"콘텐츠 생성 중 오류 발생: {str(e)}")
|
||||||
app.logger.error(traceback.format_exc())
|
app.logger.error(traceback.format_exc())
|
||||||
return jsonify({'error': f'콘텐츠 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
return jsonify({'error': f'콘텐츠 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
||||||
|
|
||||||
@app.route('/api/poster/generate', methods=['POST'])
|
@app.route('/api/poster/generate', methods=['POST'])
|
||||||
def generate_poster():
|
def generate_poster():
|
||||||
"""
|
"""
|
||||||
@ -136,15 +141,20 @@ def create_app():
|
|||||||
app.logger.error(f"포스터 생성 중 오류 발생: {str(e)}")
|
app.logger.error(f"포스터 생성 중 오류 발생: {str(e)}")
|
||||||
app.logger.error(traceback.format_exc())
|
app.logger.error(traceback.format_exc())
|
||||||
return jsonify({'error': f'포스터 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
return jsonify({'error': f'포스터 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
||||||
|
|
||||||
@app.errorhandler(413)
|
@app.errorhandler(413)
|
||||||
def too_large(e):
|
def too_large(e):
|
||||||
"""파일 크기 초과 에러 처리"""
|
"""파일 크기 초과 에러 처리"""
|
||||||
return jsonify({'error': '업로드된 파일이 너무 큽니다. (최대 16MB)'}), 413
|
return jsonify({'error': '업로드된 파일이 너무 큽니다. (최대 16MB)'}), 413
|
||||||
|
|
||||||
@app.errorhandler(500)
|
@app.errorhandler(500)
|
||||||
def internal_error(error):
|
def internal_error(error):
|
||||||
"""내부 서버 에러 처리"""
|
"""내부 서버 에러 처리"""
|
||||||
return jsonify({'error': '내부 서버 오류가 발생했습니다.'}), 500
|
return jsonify({'error': '내부 서버 오류가 발생했습니다.'}), 500
|
||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
app = create_app()
|
app = create_app()
|
||||||
app.run(host='0.0.0.0', port=5000, debug=True)
|
app.run(host='0.0.0.0', port=5000, debug=True)
|
||||||
|
|||||||
8
smarketing-ai/requirements.txt
Normal file
8
smarketing-ai/requirements.txt
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
Flask==3.0.0
|
||||||
|
Flask-CORS==4.0.0
|
||||||
|
Pillow>=9.0.0
|
||||||
|
requests==2.31.0
|
||||||
|
anthropic==0.8.1
|
||||||
|
openai==1.6.1
|
||||||
|
python-dotenv==1.0.0
|
||||||
|
Werkzeug==3.0.1
|
||||||
@ -8,8 +8,11 @@ from datetime import datetime
|
|||||||
from utils.ai_client import AIClient
|
from utils.ai_client import AIClient
|
||||||
from utils.image_processor import ImageProcessor
|
from utils.image_processor import ImageProcessor
|
||||||
from models.request_models import ContentRequest
|
from models.request_models import ContentRequest
|
||||||
|
|
||||||
|
|
||||||
class ContentService:
|
class ContentService:
|
||||||
"""마케팅 콘텐츠 생성 서비스 클래스"""
|
"""마케팅 콘텐츠 생성 서비스 클래스"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""서비스 초기화"""
|
"""서비스 초기화"""
|
||||||
self.ai_client = AIClient()
|
self.ai_client = AIClient()
|
||||||
@ -35,6 +38,7 @@ class ContentService:
|
|||||||
'매장': ['분위기', '인테리어', '편안한', '아늑한', '특별한', '방문'],
|
'매장': ['분위기', '인테리어', '편안한', '아늑한', '특별한', '방문'],
|
||||||
'이벤트': ['할인', '이벤트', '특가', '한정', '기간한정', '혜택']
|
'이벤트': ['할인', '이벤트', '특가', '한정', '기간한정', '혜택']
|
||||||
}
|
}
|
||||||
|
|
||||||
def generate_content(self, request: ContentRequest) -> Dict[str, Any]:
|
def generate_content(self, request: ContentRequest) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
마케팅 콘텐츠 생성
|
마케팅 콘텐츠 생성
|
||||||
@ -54,8 +58,8 @@ class ContentService:
|
|||||||
hashtags = self._generate_hashtags(request)
|
hashtags = self._generate_hashtags(request)
|
||||||
# 최종 콘텐츠 포맷팅
|
# 최종 콘텐츠 포맷팅
|
||||||
formatted_content = self._format_content(
|
formatted_content = self._format_content(
|
||||||
generated_content,
|
generated_content,
|
||||||
hashtags,
|
hashtags,
|
||||||
request.platform
|
request.platform
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
@ -73,6 +77,7 @@ class ContentService:
|
|||||||
'error': str(e),
|
'error': str(e),
|
||||||
'generated_at': datetime.now().isoformat()
|
'generated_at': datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
def _analyze_images(self, image_paths: list) -> Dict[str, Any]:
|
def _analyze_images(self, image_paths: list) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
업로드된 이미지들 분석
|
업로드된 이미지들 분석
|
||||||
@ -102,6 +107,7 @@ class ContentService:
|
|||||||
'total_images': len(image_paths),
|
'total_images': len(image_paths),
|
||||||
'results': analysis_results
|
'results': analysis_results
|
||||||
}
|
}
|
||||||
|
|
||||||
def _create_content_prompt(self, request: ContentRequest, image_analysis: Dict[str, Any]) -> str:
|
def _create_content_prompt(self, request: ContentRequest, image_analysis: Dict[str, Any]) -> str:
|
||||||
"""
|
"""
|
||||||
AI 콘텐츠 생성을 위한 프롬프트 생성
|
AI 콘텐츠 생성을 위한 프롬프트 생성
|
||||||
@ -143,6 +149,7 @@ class ContentService:
|
|||||||
해시태그는 별도로 생성하므로 본문에는 포함하지 마세요.
|
해시태그는 별도로 생성하므로 본문에는 포함하지 마세요.
|
||||||
"""
|
"""
|
||||||
return prompt
|
return prompt
|
||||||
|
|
||||||
def _generate_hashtags(self, request: ContentRequest) -> list:
|
def _generate_hashtags(self, request: ContentRequest) -> list:
|
||||||
"""
|
"""
|
||||||
카테고리와 플랫폼에 맞는 해시태그 생성
|
카테고리와 플랫폼에 맞는 해시태그 생성
|
||||||
@ -170,6 +177,7 @@ class ContentService:
|
|||||||
# 최대 개수 제한
|
# 최대 개수 제한
|
||||||
max_count = platform_spec['hashtag_count']
|
max_count = platform_spec['hashtag_count']
|
||||||
return hashtags[:max_count]
|
return hashtags[:max_count]
|
||||||
|
|
||||||
def _format_content(self, content: str, hashtags: list, platform: str) -> str:
|
def _format_content(self, content: str, hashtags: list, platform: str) -> str:
|
||||||
"""
|
"""
|
||||||
플랫폼에 맞게 콘텐츠 포맷팅
|
플랫폼에 맞게 콘텐츠 포맷팅
|
||||||
@ -197,4 +205,4 @@ class ContentService:
|
|||||||
# 기본 형태
|
# 기본 형태
|
||||||
hashtag_string = ' '.join(hashtags)
|
hashtag_string = ' '.join(hashtags)
|
||||||
formatted = f"{content}\n\n{hashtag_string}"
|
formatted = f"{content}\n\n{hashtag_string}"
|
||||||
return formatted
|
return formatted
|
||||||
|
|||||||
@ -10,8 +10,11 @@ from PIL import Image, ImageDraw, ImageFont
|
|||||||
from utils.ai_client import AIClient
|
from utils.ai_client import AIClient
|
||||||
from utils.image_processor import ImageProcessor
|
from utils.image_processor import ImageProcessor
|
||||||
from models.request_models import PosterRequest
|
from models.request_models import PosterRequest
|
||||||
|
|
||||||
|
|
||||||
class PosterService:
|
class PosterService:
|
||||||
"""홍보 포스터 생성 서비스 클래스"""
|
"""홍보 포스터 생성 서비스 클래스"""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""서비스 초기화"""
|
"""서비스 초기화"""
|
||||||
self.ai_client = AIClient()
|
self.ai_client = AIClient()
|
||||||
@ -27,21 +30,22 @@ class PosterService:
|
|||||||
# 카테고리별 색상 테마
|
# 카테고리별 색상 테마
|
||||||
self.category_themes = {
|
self.category_themes = {
|
||||||
'음식': {
|
'음식': {
|
||||||
'primary': (255, 107, 107), # 빨강
|
'primary': (255, 107, 107), # 빨강
|
||||||
'secondary': (255, 206, 84), # 노랑
|
'secondary': (255, 206, 84), # 노랑
|
||||||
'background': (255, 248, 240) # 크림
|
'background': (255, 248, 240) # 크림
|
||||||
},
|
},
|
||||||
'매장': {
|
'매장': {
|
||||||
'primary': (74, 144, 226), # 파랑
|
'primary': (74, 144, 226), # 파랑
|
||||||
'secondary': (120, 198, 121), # 초록
|
'secondary': (120, 198, 121), # 초록
|
||||||
'background': (248, 251, 255) # 연한 파랑
|
'background': (248, 251, 255) # 연한 파랑
|
||||||
},
|
},
|
||||||
'이벤트': {
|
'이벤트': {
|
||||||
'primary': (156, 39, 176), # 보라
|
'primary': (156, 39, 176), # 보라
|
||||||
'secondary': (255, 193, 7), # 금색
|
'secondary': (255, 193, 7), # 금색
|
||||||
'background': (252, 248, 255) # 연한 보라
|
'background': (252, 248, 255) # 연한 보라
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
def generate_poster(self, request: PosterRequest) -> Dict[str, Any]:
|
def generate_poster(self, request: PosterRequest) -> Dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
홍보 포스터 생성
|
홍보 포스터 생성
|
||||||
@ -74,6 +78,7 @@ class PosterService:
|
|||||||
'error': str(e),
|
'error': str(e),
|
||||||
'generated_at': datetime.now().isoformat()
|
'generated_at': datetime.now().isoformat()
|
||||||
}
|
}
|
||||||
|
|
||||||
def _generate_poster_text(self, request: PosterRequest) -> Dict[str, str]:
|
def _generate_poster_text(self, request: PosterRequest) -> Dict[str, str]:
|
||||||
"""
|
"""
|
||||||
포스터에 들어갈 텍스트 내용 생성
|
포스터에 들어갈 텍스트 내용 생성
|
||||||
@ -122,6 +127,7 @@ class PosterService:
|
|||||||
'description': lines[2] if len(lines) > 2 else '특별한 혜택을 놓치지 마세요',
|
'description': lines[2] if len(lines) > 2 else '특별한 혜택을 놓치지 마세요',
|
||||||
'call_to_action': lines[3] if len(lines) > 3 else '지금 방문하세요!'
|
'call_to_action': lines[3] if len(lines) > 3 else '지금 방문하세요!'
|
||||||
}
|
}
|
||||||
|
|
||||||
def _process_images(self, image_paths: list) -> list:
|
def _process_images(self, image_paths: list) -> list:
|
||||||
"""
|
"""
|
||||||
포스터에 사용할 이미지들 전처리
|
포스터에 사용할 이미지들 전처리
|
||||||
@ -145,6 +151,7 @@ class PosterService:
|
|||||||
print(f"이미지 처리 오류 {image_path}: {e}")
|
print(f"이미지 처리 오류 {image_path}: {e}")
|
||||||
continue
|
continue
|
||||||
return processed_images
|
return processed_images
|
||||||
|
|
||||||
def _create_poster_image(self, request: PosterRequest, poster_text: Dict[str, str], images: list) -> Image.Image:
|
def _create_poster_image(self, request: PosterRequest, poster_text: Dict[str, str], images: list) -> Image.Image:
|
||||||
"""
|
"""
|
||||||
실제 포스터 이미지 생성
|
실제 포스터 이미지 생성
|
||||||
@ -158,9 +165,9 @@ class PosterService:
|
|||||||
# 카테고리별 테마 적용
|
# 카테고리별 테마 적용
|
||||||
theme = self.category_themes.get(request.category, self.category_themes['음식'])
|
theme = self.category_themes.get(request.category, self.category_themes['음식'])
|
||||||
# 캔버스 생성
|
# 캔버스 생성
|
||||||
poster = Image.new('RGBA',
|
poster = Image.new('RGBA',
|
||||||
(self.poster_config['width'], self.poster_config['height']),
|
(self.poster_config['width'], self.poster_config['height']),
|
||||||
theme['background'])
|
theme['background'])
|
||||||
draw = ImageDraw.Draw(poster)
|
draw = ImageDraw.Draw(poster)
|
||||||
# 폰트 설정 (시스템 기본 폰트 사용)
|
# 폰트 설정 (시스템 기본 폰트 사용)
|
||||||
try:
|
try:
|
||||||
@ -182,16 +189,16 @@ class PosterService:
|
|||||||
bbox = draw.textbbox((0, 0), main_headline, font=title_font)
|
bbox = draw.textbbox((0, 0), main_headline, font=title_font)
|
||||||
text_width = bbox[2] - bbox[0]
|
text_width = bbox[2] - bbox[0]
|
||||||
x_pos = (self.poster_config['width'] - text_width) // 2
|
x_pos = (self.poster_config['width'] - text_width) // 2
|
||||||
draw.text((x_pos, y_pos), main_headline,
|
draw.text((x_pos, y_pos), main_headline,
|
||||||
fill=theme['primary'], font=title_font)
|
fill=theme['primary'], font=title_font)
|
||||||
y_pos += 100
|
y_pos += 100
|
||||||
# 2. 서브 헤드라인
|
# 2. 서브 헤드라인
|
||||||
sub_headline = poster_text['sub_headline']
|
sub_headline = poster_text['sub_headline']
|
||||||
bbox = draw.textbbox((0, 0), sub_headline, font=subtitle_font)
|
bbox = draw.textbbox((0, 0), sub_headline, font=subtitle_font)
|
||||||
text_width = bbox[2] - bbox[0]
|
text_width = bbox[2] - bbox[0]
|
||||||
x_pos = (self.poster_config['width'] - text_width) // 2
|
x_pos = (self.poster_config['width'] - text_width) // 2
|
||||||
draw.text((x_pos, y_pos), sub_headline,
|
draw.text((x_pos, y_pos), sub_headline,
|
||||||
fill=theme['secondary'], font=subtitle_font)
|
fill=theme['secondary'], font=subtitle_font)
|
||||||
y_pos += 80
|
y_pos += 80
|
||||||
# 3. 이미지 배치 (있는 경우)
|
# 3. 이미지 배치 (있는 경우)
|
||||||
if images:
|
if images:
|
||||||
@ -219,7 +226,7 @@ class PosterService:
|
|||||||
row = i // cols
|
row = i // cols
|
||||||
col = i % cols
|
col = i % cols
|
||||||
img_x = (self.poster_config['width'] // cols) * col + \
|
img_x = (self.poster_config['width'] // cols) * col + \
|
||||||
(self.poster_config['width'] // cols - img.width) // 2
|
(self.poster_config['width'] // cols - img.width) // 2
|
||||||
img_y = image_y + row * (200 + img_spacing)
|
img_y = image_y + row * (200 + img_spacing)
|
||||||
poster.paste(img, (img_x, img_y), img)
|
poster.paste(img, (img_x, img_y), img)
|
||||||
y_pos = image_y + rows * (200 + img_spacing) + 30
|
y_pos = image_y + rows * (200 + img_spacing) + 30
|
||||||
@ -266,7 +273,7 @@ class PosterService:
|
|||||||
button_x = (self.poster_config['width'] - button_width) // 2
|
button_x = (self.poster_config['width'] - button_width) // 2
|
||||||
button_y = self.poster_config['height'] - 150
|
button_y = self.poster_config['height'] - 150
|
||||||
draw.rounded_rectangle([button_x, button_y, button_x + button_width, button_y + button_height],
|
draw.rounded_rectangle([button_x, button_y, button_x + button_width, button_y + button_height],
|
||||||
radius=25, fill=theme['primary'])
|
radius=25, fill=theme['primary'])
|
||||||
# 버튼 텍스트
|
# 버튼 텍스트
|
||||||
text_x = button_x + (button_width - text_width) // 2
|
text_x = button_x + (button_width - text_width) // 2
|
||||||
text_y = button_y + (button_height - text_height) // 2
|
text_y = button_y + (button_height - text_height) // 2
|
||||||
@ -280,6 +287,7 @@ class PosterService:
|
|||||||
y_pos = self.poster_config['height'] - 50
|
y_pos = self.poster_config['height'] - 50
|
||||||
draw.text((x_pos, y_pos), store_text, fill=(100, 100, 100), font=text_font)
|
draw.text((x_pos, y_pos), store_text, fill=(100, 100, 100), font=text_font)
|
||||||
return poster
|
return poster
|
||||||
|
|
||||||
def _encode_image_to_base64(self, image: Image.Image) -> str:
|
def _encode_image_to_base64(self, image: Image.Image) -> str:
|
||||||
"""
|
"""
|
||||||
PIL 이미지를 base64 문자열로 인코딩
|
PIL 이미지를 base64 문자열로 인코딩
|
||||||
@ -301,4 +309,4 @@ class PosterService:
|
|||||||
img_buffer.seek(0)
|
img_buffer.seek(0)
|
||||||
# base64 인코딩
|
# base64 인코딩
|
||||||
img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
|
img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8')
|
||||||
return f"data:image/jpeg;base64,{img_base64}"
|
return f"data:image/jpeg;base64,{img_base64}"
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user