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.poster_service import PosterService
|
||||
from models.request_models import ContentRequest, PosterRequest
|
||||
|
||||
|
||||
def create_app():
|
||||
"""Flask 애플리케이션 팩토리"""
|
||||
app = Flask(__name__)
|
||||
@ -25,6 +27,7 @@ def create_app():
|
||||
# 서비스 인스턴스 생성
|
||||
content_service = ContentService()
|
||||
poster_service = PosterService()
|
||||
|
||||
@app.route('/health', methods=['GET'])
|
||||
def health_check():
|
||||
"""헬스 체크 API"""
|
||||
@ -33,6 +36,7 @@ def create_app():
|
||||
'timestamp': datetime.now().isoformat(),
|
||||
'service': 'AI Marketing Service'
|
||||
})
|
||||
|
||||
@app.route('/api/content/generate', methods=['POST'])
|
||||
def generate_content():
|
||||
"""
|
||||
@ -84,6 +88,7 @@ def create_app():
|
||||
app.logger.error(f"콘텐츠 생성 중 오류 발생: {str(e)}")
|
||||
app.logger.error(traceback.format_exc())
|
||||
return jsonify({'error': f'콘텐츠 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
||||
|
||||
@app.route('/api/poster/generate', methods=['POST'])
|
||||
def generate_poster():
|
||||
"""
|
||||
@ -136,15 +141,20 @@ def create_app():
|
||||
app.logger.error(f"포스터 생성 중 오류 발생: {str(e)}")
|
||||
app.logger.error(traceback.format_exc())
|
||||
return jsonify({'error': f'포스터 생성 중 오류가 발생했습니다: {str(e)}'}), 500
|
||||
|
||||
@app.errorhandler(413)
|
||||
def too_large(e):
|
||||
"""파일 크기 초과 에러 처리"""
|
||||
return jsonify({'error': '업로드된 파일이 너무 큽니다. (최대 16MB)'}), 413
|
||||
|
||||
@app.errorhandler(500)
|
||||
def internal_error(error):
|
||||
"""내부 서버 에러 처리"""
|
||||
return jsonify({'error': '내부 서버 오류가 발생했습니다.'}), 500
|
||||
|
||||
return app
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app = create_app()
|
||||
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.image_processor import ImageProcessor
|
||||
from models.request_models import ContentRequest
|
||||
|
||||
|
||||
class ContentService:
|
||||
"""마케팅 콘텐츠 생성 서비스 클래스"""
|
||||
|
||||
def __init__(self):
|
||||
"""서비스 초기화"""
|
||||
self.ai_client = AIClient()
|
||||
@ -35,6 +38,7 @@ class ContentService:
|
||||
'매장': ['분위기', '인테리어', '편안한', '아늑한', '특별한', '방문'],
|
||||
'이벤트': ['할인', '이벤트', '특가', '한정', '기간한정', '혜택']
|
||||
}
|
||||
|
||||
def generate_content(self, request: ContentRequest) -> Dict[str, Any]:
|
||||
"""
|
||||
마케팅 콘텐츠 생성
|
||||
@ -73,6 +77,7 @@ class ContentService:
|
||||
'error': str(e),
|
||||
'generated_at': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
def _analyze_images(self, image_paths: list) -> Dict[str, Any]:
|
||||
"""
|
||||
업로드된 이미지들 분석
|
||||
@ -102,6 +107,7 @@ class ContentService:
|
||||
'total_images': len(image_paths),
|
||||
'results': analysis_results
|
||||
}
|
||||
|
||||
def _create_content_prompt(self, request: ContentRequest, image_analysis: Dict[str, Any]) -> str:
|
||||
"""
|
||||
AI 콘텐츠 생성을 위한 프롬프트 생성
|
||||
@ -143,6 +149,7 @@ class ContentService:
|
||||
해시태그는 별도로 생성하므로 본문에는 포함하지 마세요.
|
||||
"""
|
||||
return prompt
|
||||
|
||||
def _generate_hashtags(self, request: ContentRequest) -> list:
|
||||
"""
|
||||
카테고리와 플랫폼에 맞는 해시태그 생성
|
||||
@ -170,6 +177,7 @@ class ContentService:
|
||||
# 최대 개수 제한
|
||||
max_count = platform_spec['hashtag_count']
|
||||
return hashtags[:max_count]
|
||||
|
||||
def _format_content(self, content: str, hashtags: list, platform: str) -> str:
|
||||
"""
|
||||
플랫폼에 맞게 콘텐츠 포맷팅
|
||||
|
||||
@ -10,8 +10,11 @@ from PIL import Image, ImageDraw, ImageFont
|
||||
from utils.ai_client import AIClient
|
||||
from utils.image_processor import ImageProcessor
|
||||
from models.request_models import PosterRequest
|
||||
|
||||
|
||||
class PosterService:
|
||||
"""홍보 포스터 생성 서비스 클래스"""
|
||||
|
||||
def __init__(self):
|
||||
"""서비스 초기화"""
|
||||
self.ai_client = AIClient()
|
||||
@ -27,21 +30,22 @@ class PosterService:
|
||||
# 카테고리별 색상 테마
|
||||
self.category_themes = {
|
||||
'음식': {
|
||||
'primary': (255, 107, 107), # 빨강
|
||||
'secondary': (255, 206, 84), # 노랑
|
||||
'primary': (255, 107, 107), # 빨강
|
||||
'secondary': (255, 206, 84), # 노랑
|
||||
'background': (255, 248, 240) # 크림
|
||||
},
|
||||
'매장': {
|
||||
'primary': (74, 144, 226), # 파랑
|
||||
'primary': (74, 144, 226), # 파랑
|
||||
'secondary': (120, 198, 121), # 초록
|
||||
'background': (248, 251, 255) # 연한 파랑
|
||||
},
|
||||
'이벤트': {
|
||||
'primary': (156, 39, 176), # 보라
|
||||
'secondary': (255, 193, 7), # 금색
|
||||
'primary': (156, 39, 176), # 보라
|
||||
'secondary': (255, 193, 7), # 금색
|
||||
'background': (252, 248, 255) # 연한 보라
|
||||
}
|
||||
}
|
||||
|
||||
def generate_poster(self, request: PosterRequest) -> Dict[str, Any]:
|
||||
"""
|
||||
홍보 포스터 생성
|
||||
@ -74,6 +78,7 @@ class PosterService:
|
||||
'error': str(e),
|
||||
'generated_at': datetime.now().isoformat()
|
||||
}
|
||||
|
||||
def _generate_poster_text(self, request: PosterRequest) -> Dict[str, str]:
|
||||
"""
|
||||
포스터에 들어갈 텍스트 내용 생성
|
||||
@ -122,6 +127,7 @@ class PosterService:
|
||||
'description': lines[2] if len(lines) > 2 else '특별한 혜택을 놓치지 마세요',
|
||||
'call_to_action': lines[3] if len(lines) > 3 else '지금 방문하세요!'
|
||||
}
|
||||
|
||||
def _process_images(self, image_paths: list) -> list:
|
||||
"""
|
||||
포스터에 사용할 이미지들 전처리
|
||||
@ -145,6 +151,7 @@ class PosterService:
|
||||
print(f"이미지 처리 오류 {image_path}: {e}")
|
||||
continue
|
||||
return processed_images
|
||||
|
||||
def _create_poster_image(self, request: PosterRequest, poster_text: Dict[str, str], images: list) -> Image.Image:
|
||||
"""
|
||||
실제 포스터 이미지 생성
|
||||
@ -159,8 +166,8 @@ class PosterService:
|
||||
theme = self.category_themes.get(request.category, self.category_themes['음식'])
|
||||
# 캔버스 생성
|
||||
poster = Image.new('RGBA',
|
||||
(self.poster_config['width'], self.poster_config['height']),
|
||||
theme['background'])
|
||||
(self.poster_config['width'], self.poster_config['height']),
|
||||
theme['background'])
|
||||
draw = ImageDraw.Draw(poster)
|
||||
# 폰트 설정 (시스템 기본 폰트 사용)
|
||||
try:
|
||||
@ -183,7 +190,7 @@ class PosterService:
|
||||
text_width = bbox[2] - bbox[0]
|
||||
x_pos = (self.poster_config['width'] - text_width) // 2
|
||||
draw.text((x_pos, y_pos), main_headline,
|
||||
fill=theme['primary'], font=title_font)
|
||||
fill=theme['primary'], font=title_font)
|
||||
y_pos += 100
|
||||
# 2. 서브 헤드라인
|
||||
sub_headline = poster_text['sub_headline']
|
||||
@ -191,7 +198,7 @@ class PosterService:
|
||||
text_width = bbox[2] - bbox[0]
|
||||
x_pos = (self.poster_config['width'] - text_width) // 2
|
||||
draw.text((x_pos, y_pos), sub_headline,
|
||||
fill=theme['secondary'], font=subtitle_font)
|
||||
fill=theme['secondary'], font=subtitle_font)
|
||||
y_pos += 80
|
||||
# 3. 이미지 배치 (있는 경우)
|
||||
if images:
|
||||
@ -219,7 +226,7 @@ class PosterService:
|
||||
row = i // cols
|
||||
col = i % cols
|
||||
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)
|
||||
poster.paste(img, (img_x, img_y), img)
|
||||
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_y = self.poster_config['height'] - 150
|
||||
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_y = button_y + (button_height - text_height) // 2
|
||||
@ -280,6 +287,7 @@ class PosterService:
|
||||
y_pos = self.poster_config['height'] - 50
|
||||
draw.text((x_pos, y_pos), store_text, fill=(100, 100, 100), font=text_font)
|
||||
return poster
|
||||
|
||||
def _encode_image_to_base64(self, image: Image.Image) -> str:
|
||||
"""
|
||||
PIL 이미지를 base64 문자열로 인코딩
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user