From 885fcf0977d6b37be7d8ee711cad970ceafbdc06 Mon Sep 17 00:00:00 2001 From: OhSeongRak Date: Wed, 11 Jun 2025 16:06:52 +0900 Subject: [PATCH 1/2] =?UTF-8?q?style:=20=EC=BD=94=EB=93=9C=20=ED=8F=AC?= =?UTF-8?q?=EB=A7=B7=ED=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- smarketing-ai/app.py | 12 ++++++- smarketing-ai/services/content_service.py | 14 +++++++-- smarketing-ai/services/poster_service.py | 38 ++++++++++++++--------- 3 files changed, 45 insertions(+), 19 deletions(-) diff --git a/smarketing-ai/app.py b/smarketing-ai/app.py index 0592c23..abdb87b 100644 --- a/smarketing-ai/app.py +++ b/smarketing-ai/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) \ No newline at end of file + app.run(host='0.0.0.0', port=5000, debug=True) diff --git a/smarketing-ai/services/content_service.py b/smarketing-ai/services/content_service.py index d856e05..34dc36b 100644 --- a/smarketing-ai/services/content_service.py +++ b/smarketing-ai/services/content_service.py @@ -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]: """ 마케팅 콘텐츠 생성 @@ -54,8 +58,8 @@ class ContentService: hashtags = self._generate_hashtags(request) # 최종 콘텐츠 포맷팅 formatted_content = self._format_content( - generated_content, - hashtags, + generated_content, + hashtags, request.platform ) return { @@ -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: """ 플랫폼에 맞게 콘텐츠 포맷팅 @@ -197,4 +205,4 @@ class ContentService: # 기본 형태 hashtag_string = ' '.join(hashtags) formatted = f"{content}\n\n{hashtag_string}" - return formatted \ No newline at end of file + return formatted diff --git a/smarketing-ai/services/poster_service.py b/smarketing-ai/services/poster_service.py index c1e0245..fc27adb 100644 --- a/smarketing-ai/services/poster_service.py +++ b/smarketing-ai/services/poster_service.py @@ -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: """ 실제 포스터 이미지 생성 @@ -158,9 +165,9 @@ 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']) + poster = Image.new('RGBA', + (self.poster_config['width'], self.poster_config['height']), + theme['background']) draw = ImageDraw.Draw(poster) # 폰트 설정 (시스템 기본 폰트 사용) try: @@ -182,16 +189,16 @@ class PosterService: bbox = draw.textbbox((0, 0), main_headline, font=title_font) 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) + draw.text((x_pos, y_pos), main_headline, + fill=theme['primary'], font=title_font) y_pos += 100 # 2. 서브 헤드라인 sub_headline = poster_text['sub_headline'] bbox = draw.textbbox((0, 0), sub_headline, font=subtitle_font) 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) + draw.text((x_pos, y_pos), sub_headline, + 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 문자열로 인코딩 @@ -301,4 +309,4 @@ class PosterService: img_buffer.seek(0) # base64 인코딩 img_base64 = base64.b64encode(img_buffer.getvalue()).decode('utf-8') - return f"data:image/jpeg;base64,{img_base64}" \ No newline at end of file + return f"data:image/jpeg;base64,{img_base64}" From b7c1f89269619ea7834eb1ef549a4340f2f6b8c2 Mon Sep 17 00:00:00 2001 From: OhSeongRak Date: Wed, 11 Jun 2025 16:07:05 +0900 Subject: [PATCH 2/2] feat: init --- smarketing-ai/.gitignore | 2 ++ smarketing-ai/Dockerfile | 25 +++++++++++++++++++++++++ smarketing-ai/requirements.txt | 8 ++++++++ 3 files changed, 35 insertions(+) create mode 100644 smarketing-ai/.gitignore create mode 100644 smarketing-ai/Dockerfile create mode 100644 smarketing-ai/requirements.txt diff --git a/smarketing-ai/.gitignore b/smarketing-ai/.gitignore new file mode 100644 index 0000000..3bf780b --- /dev/null +++ b/smarketing-ai/.gitignore @@ -0,0 +1,2 @@ +.idea +.env \ No newline at end of file diff --git a/smarketing-ai/Dockerfile b/smarketing-ai/Dockerfile new file mode 100644 index 0000000..897d2e0 --- /dev/null +++ b/smarketing-ai/Dockerfile @@ -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"] \ No newline at end of file diff --git a/smarketing-ai/requirements.txt b/smarketing-ai/requirements.txt new file mode 100644 index 0000000..f3f76cd --- /dev/null +++ b/smarketing-ai/requirements.txt @@ -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 \ No newline at end of file