aliceblue11 commited on
Commit
a0f7bb0
·
verified ·
1 Parent(s): 934cf44

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +556 -0
app.py CHANGED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+ import datetime
4
+ import calendar
5
+ import requests
6
+ import json
7
+ from datetime import datetime
8
+
9
+ # ================== 컨셉 분석 모듈 ==================
10
+ class ConceptAnalyzer:
11
+ def __init__(self):
12
+ self.monthly_data = {
13
+ "1월": {
14
+ "special_days": ["미니멀 챌린지", "새해 리셋", "플래너 스타트"],
15
+ "trends": ["미니멀", "자기계발", "플래너", "정리정돈"],
16
+ "colors": ["#FF6B6B", "#4ECDC4", "#45B7D1"],
17
+ "mood": "희망적이고 새로운 시작",
18
+ "female_appeal": ["미니멀", "자기계발", "셀프케어"]
19
+ },
20
+ "2월": {
21
+ "special_days": ["갈렌타인데이", "셀프러브", "사랑의 달"],
22
+ "trends": ["셀프러브", "갈렌타인", "로맨스", "따뜻한 감성"],
23
+ "colors": ["#FF69B4", "#FFB6C1", "#DC143C"],
24
+ "mood": "로맨틱하고 감성적",
25
+ "female_appeal": ["셀프러브", "우정", "로맨스"]
26
+ },
27
+ "3월": {
28
+ "special_days": ["여성의 날", "봄의 시작", "새학기"],
29
+ "trends": ["봄맞이", "벚꽃 시즌", "봄 패션", "새출발"],
30
+ "colors": ["#FFB6C1", "#98FB98", "#87CEEB"],
31
+ "mood": "설렘가득하고 활기찬",
32
+ "female_appeal": ["봄 패션", "꽃구경", "새출발"]
33
+ },
34
+ "4월": {
35
+ "special_days": ["벚꽃 시즌", "봄나들이", "피크닉"],
36
+ "trends": ["벚꽃축제", "봄피크닉", "아웃도어", "꽃놀이"],
37
+ "colors": ["#98FB98", "#F0E68C", "#DDA0DD"],
38
+ "mood": "생기발랄하고 즐거운",
39
+ "female_appeal": ["벚꽃놀이", "피크닉", "봄여행"]
40
+ },
41
+ "5월": {
42
+ "special_days": ["로즈데이", "감사의 달", "힐링"],
43
+ "trends": ["감사", "나들이", "로즈데이", "봄여행"],
44
+ "colors": ["#32CD32", "#FFB6C1", "#87CEEB"],
45
+ "mood": "따뜻하고 감사한",
46
+ "female_appeal": ["로즈데이", "감사표현", "힐링"]
47
+ },
48
+ "6월": {
49
+ "special_days": ["키스데이", "여름 준비", "쿨링"],
50
+ "trends": ["여름준비", "쿨링", "바캉스준비", "여름패션"],
51
+ "colors": ["#00CED1", "#FFD700", "#FF6347"],
52
+ "mood": "시원하고 활동적인",
53
+ "female_appeal": ["여름준비", "쿨링케어", "바캉스"]
54
+ },
55
+ "7월": {
56
+ "special_days": ["실버데이", "여름휴가", "바캉스"],
57
+ "trends": ["여름휴가", "바캉스", "휴가패션", "여행"],
58
+ "colors": ["#00BFFF", "#FFD700", "#FF6347"],
59
+ "mood": "역동적이고 자유로운",
60
+ "female_appeal": ["바캉스", "여행", "휴가패션"]
61
+ },
62
+ "8월": {
63
+ "special_days": ["그린데이", "여름 마무리", "휴가"],
64
+ "trends": ["여름휴가", "바다여행", "축제", "여름추억"],
65
+ "colors": ["#00BFFF", "#FF6347", "#FFD700"],
66
+ "mood": "열정적이고 추억가득한",
67
+ "female_appeal": ["여름추억", "힐링", "여행"]
68
+ },
69
+ "9월": {
70
+ "special_days": ["포토데이", "뮤직데이", "가을시작"],
71
+ "trends": ["가을패션", "독서", "문화생활", "감성"],
72
+ "colors": ["#FF8C00", "#DC143C", "#B8860B"],
73
+ "mood": "감성적이고 성숙한",
74
+ "female_appeal": ["가을패션", "카페", "독서"]
75
+ },
76
+ "10월": {
77
+ "special_days": ["와인데이", "커피데이", "독서의 달"],
78
+ "trends": ["가을단풍", "독서", "카페문화", "와인"],
79
+ "colors": ["#FF8C00", "#DC143C", "#B8860B"],
80
+ "mood": "감성적이고 여유로운",
81
+ "female_appeal": ["단풍구경", "카페", "와인"]
82
+ },
83
+ "11월": {
84
+ "special_days": ["무비데이", "오렌지데이", "연말준비"],
85
+ "trends": ["빼빼로데이", "연말준비", "겨울패션", "따뜻함"],
86
+ "colors": ["#8B4513", "#A0522D", "#CD853F"],
87
+ "mood": "포근하고 준비하는",
88
+ "female_appeal": ["빼빼로데이", "겨울패션", "연말모임"]
89
+ },
90
+ "12월": {
91
+ "special_days": ["허그데이", "연말파티", "송년"],
92
+ "trends": ["크리스마스", "연말파티", "선물", "송년회"],
93
+ "colors": ["#DC143C", "#228B22", "#FFD700"],
94
+ "mood": "축제같고 따뜻한",
95
+ "female_appeal": ["크리스마스", "연말모임", "선물"]
96
+ }
97
+ }
98
+
99
+ def extract_month_from_period(self, period_text):
100
+ """이벤트 기간에서 월 추출"""
101
+ if not period_text or period_text.strip() == "":
102
+ return None
103
+
104
+ date_patterns = [
105
+ r'(\d{4})\.(\d{1,2})\.(\d{1,2})',
106
+ r'(\d{1,2})\.(\d{1,2})',
107
+ r'(\d{1,2})월',
108
+ ]
109
+
110
+ for pattern in date_patterns:
111
+ matches = re.findall(pattern, period_text)
112
+ if matches:
113
+ if len(matches[0]) == 3:
114
+ month = int(matches[0][1])
115
+ elif len(matches[0]) == 2:
116
+ month = int(matches[0][0])
117
+ else:
118
+ month = int(matches[0])
119
+
120
+ if 1 <= month <= 12:
121
+ return f"{month}월"
122
+
123
+ return None
124
+
125
+ def analyze_concepts(self, month):
126
+ """20-40대 여성 맞춤 월별 컨셉 분석"""
127
+ data = self.monthly_data.get(month, {})
128
+
129
+ concepts = []
130
+
131
+ # 컨셉 1
132
+ if data.get("special_days"):
133
+ special = data["special_days"][0]
134
+ concepts.append({
135
+ "name": f"{special} 이벤트",
136
+ "theme": f"{special}를 테마로 한 여성 맞춤 이벤트",
137
+ "score": 8.8,
138
+ "reason": f"20-40대 여성이 공감할 수 있는 {special} 테마",
139
+ "target": "20-40대 여성",
140
+ "colors": data.get("colors", ["#FF69B4"]),
141
+ "keywords": [special] + data.get("female_appeal", [])[:2],
142
+ "is_recommended": True
143
+ })
144
+
145
+ # 컨셉 2
146
+ if data.get("trends"):
147
+ trend = data["trends"][0]
148
+ concepts.append({
149
+ "name": f"{trend} 챌린지",
150
+ "theme": f"{trend} 트렌드 참여형 이벤트",
151
+ "score": 8.0,
152
+ "reason": f"인기 {trend} 트렌드로 높은 관심도",
153
+ "target": "20-30대 트렌드 민감층",
154
+ "colors": data.get("colors", ["#4ECDC4"]),
155
+ "keywords": data.get("trends", [])[:3],
156
+ "is_recommended": False
157
+ })
158
+
159
+ # 컨셉 3
160
+ concepts.append({
161
+ "name": f"{month} 셀프케어 위크",
162
+ "theme": "나를 위한 특별한 시간",
163
+ "score": 8.3,
164
+ "reason": "셀프케어로 강한 어필",
165
+ "target": "20-40대 여성",
166
+ "colors": data.get("colors", ["#FFB6C1"]),
167
+ "keywords": ["셀프케어", "힐링", "나를 위한 시간"],
168
+ "is_recommended": True
169
+ })
170
+
171
+ concepts.sort(key=lambda x: (x.get("is_recommended", False), x["score"]), reverse=True)
172
+
173
+ recommended_concept = next((c for c in concepts if c.get("is_recommended", False)), concepts[0])
174
+
175
+ result = f"# 🎯 {month} 20-40대 여성 맞춤 컨셉 분석\n\n"
176
+ result += f"## 🏆 이달의 추천 컨셉: {recommended_concept['name']}\n"
177
+ result += f"**⭐ 추천 이유:** {recommended_concept['reason']}\n"
178
+ result += f"**📊 예상 참여도:** {recommended_concept['score']}/10점\n\n"
179
+ result += "---\n\n"
180
+
181
+ concept_names = []
182
+
183
+ for i, concept in enumerate(concepts, 1):
184
+ is_recommended_mark = " 🏆 **추천**" if concept.get("is_recommended", False) else ""
185
+ result += f"## {i}. {concept['name']}{is_recommended_mark}\n"
186
+ result += f"**🏷️ 테마:** {concept['theme']}\n"
187
+ result += f"**⭐ 참여도 점수:** {concept['score']}/10점\n"
188
+ result += f"**💡 선정 이유:** {concept['reason']}\n"
189
+ result += f"**🎯 주요 타겟:** {concept['target']}\n"
190
+ result += f"**🔑 핵심 키워드:** {', '.join(concept['keywords'])}\n"
191
+ result += f"**🎨 추천 색상:** {', '.join(concept['colors'])}\n\n"
192
+ result += "---\n\n"
193
+
194
+ concept_names.append(concept['name'])
195
+
196
+ return result, concept_names
197
+
198
+ # ================== 이벤트 관리 모듈 ==================
199
+ class EventManager:
200
+ def __init__(self):
201
+ self.reward_types = [
202
+ "네이버페이 금액권",
203
+ "배달의민족 상품권",
204
+ "스타벅스 기프트카드",
205
+ "CGV 영화관람권",
206
+ "올리브영 상품권"
207
+ ]
208
+
209
+ def calculate_event_duration(self, start_date, end_date):
210
+ """이벤트 기간 계산"""
211
+ try:
212
+ start = datetime.strptime(start_date, "%Y-%m-%d")
213
+ end = datetime.strptime(end_date, "%Y-%m-%d")
214
+ duration = (end - start).days + 1
215
+ month = start.month
216
+
217
+ start_weekday = start.strftime("(%a)")
218
+ end_weekday = end.strftime("(%a)")
219
+
220
+ return duration, month, start_weekday, end_weekday, start, end
221
+ except:
222
+ return 0, 0, "", "", None, None
223
+
224
+ def generate_detailed_comment_event(self, start_date, end_date, concept, reward_structure, kakao_id, phone_number):
225
+ """상세 댓글 이벤트 템플릿 생성"""
226
+
227
+ if not concept:
228
+ return "먼저 이벤트 컨셉을 입력해주세요."
229
+
230
+ # 날짜 포맷팅
231
+ duration_info, month, start_weekday, end_weekday, start_dt, end_dt = self.calculate_event_duration(start_date, end_date)
232
+
233
+ if duration_info == 0:
234
+ return "날짜 형식을 확인해주세요."
235
+
236
+ formatted_start = f"{start_dt.year}년 {start_dt.month}월 {start_dt.day}일 {start_weekday} 00:00"
237
+ formatted_end = f"{end_dt.year}년 {end_dt.month}월 {end_dt.day}일 {end_weekday} 23:59"
238
+
239
+ template = f"""댓글 남기면 1시간마다 선물이!
240
+ 🎉 {concept} 이벤트
241
+
242
+ {formatted_start} - {formatted_end} ({duration_info}일간)
243
+
244
+ ========================
245
+ EVENT
246
+ <커뮤니티>에 작성된 글에 유익하고 착한 댓글을 남기면
247
+ 1시간마다 1명씩! 하루 24명에게 선물을드려요!
248
+
249
+ {formatted_start} - {formatted_end} ({duration_info}일간)
250
+
251
+ =====================
252
+ STEP 1
253
+ 회사명 <커뮤니티>에 작성된 글에
254
+ 유익하고 착한 댓글 작성
255
+ * 이쁘고 좋은 말 많이 해주는 회원님들이 되길 부탁드려요
256
+
257
+ STEP 2
258
+ 댓글 작성 후 선물 당첨 팝업이 나타나면
259
+ 화면캡쳐 또는 사진촬영하기!
260
+ *당첨팝업은 이벤트 기간동안 1시간마다 1명씩!
261
+ 하루 24명에게 나타나요!
262
+
263
+ STEP 3
264
+ 당첨팝업 캡쳐 & 촬영했으면
265
+ 카카오톡 또는 고객센터로 연락하기!
266
+
267
+ =================
268
+ 당첨혜택
269
+ {reward_structure}
270
+
271
+ ========================
272
+ 이벤트 대상
273
+ 일반 여성회원이라면 누구나!
274
+ (*회원, 비회원 모두 참여가능 / 기업회원제외)
275
+
276
+ ========================
277
+ 수령방법
278
+ 댓글 작성 후 랜덤하게뜨는 이미지를 캡처 or 사진 촬영하기!
279
+ 꼭 캡처후 팝업을 닫아주세요!
280
+
281
+ 1.상단 당첨 날짜와 시간이 함께 나오도록
282
+ 화면캡쳐 또는 사진촬영
283
+
284
+ 2.카카오톡 ({kakao_id}) 로 캡쳐 사진 보내기
285
+
286
+ 3.카카오톡으로 연락처를 남기거나
287
+ 고객센터 운영시간에 맞춰 전화하기
288
+
289
+ 4. 고객센터와 여성회원 확인 통화 후
290
+ 선물 받기!
291
+
292
+ =========================
293
+ 꼭 확인하세요!
294
+ ※본이벤트는 회사명 일반 여성회원만 참여가능합니다. (비회원도 가능)
295
+ ※ pc에서 캡처가 어려운 경우, 카메라로 촬영하여 연락 주셔도 됩니다.
296
+ ※이벤트 팝업 상품 이미지와 상단 당첨 날짜&시간을 함께
297
+ 화면 캡처 또는 사진 촬영해야 수령 가능합니다.
298
+ ※ 화면 캡처 전에 팝업을 닫을 시, 상품 지급이 어려우니 반드시 캡처 또는
299
+ 촬영 후 팝업을 닫아주세요!
300
+ ※당첨 시 여성확인절차가 있음으로 고객센터로 연락 주시기 바랍니다. (통화로 여성확인)
301
+ ※ 고객센터와 여성 확인 통화 후 상품 수령가능합니다.
302
+ ※ 상품은 1인 1일 최대 1회까지 수령이 가능합니다. 같은 날 재당첨되어도
303
+ 지급되지 않습니다. 단, 날짜가 다를 시 중복 수령 가능합니다.
304
+ ※ 상품 수령 가능 기간은 당첨 일로부터 영업일 기준 다음 날까지 가능합니다.
305
+ ex) 주말 당첨시, 고객센터 영업일(월) 업무 종료시간 19:00시까지 수령가능
306
+
307
+ ===========================
308
+ {phone_number}
309
+ ※ 대표번호는 문자수신이 불가합니다
310
+ 고객센터 운영시간
311
+ (평일 09:30~19:00 / 점심 12:00~13:30)
312
+ ※ 주말 및 공휴일은 운영하지 않습니다.
313
+ 카카오톡 ID: {kakao_id}
314
+ """
315
+
316
+ return template
317
+
318
+ def generate_design_advice(self, concept):
319
+ """디자인 조언 생성"""
320
+
321
+ advice = f"""🎨 디자인 조언 ({concept} 테마)
322
+
323
+ 🎯 컬러 팔레트
324
+ - 20-40대 여성에게 어필하는 따뜻하고 친근한 색상
325
+ - 메인 컬러: 브랜드 컬러와 조화
326
+ - 서브 컬러: 가독성을 높이는 대비 색상
327
+
328
+ 📐 레이아웃 구조
329
+ 1. **메인 제목**: 임팩트 있는 큰 폰트 + 이모티콘
330
+ 2. **날짜 정보**: 박스로 구분하여 명확하게 표시
331
+ 3. **EVENT 섹션**: 굵은 구분선으로 강조
332
+ 4. **STEP 가이드**: 숫자와 함께 단계별 명확한 구분
333
+ 5. **당첨혜택**: 상품 이미지와 함께 시각적으로 강조
334
+ 6. **주의사항**: 읽기 쉽게 ※ 기호로 구분
335
+
336
+ 👀 가독성 향상 포인트
337
+ - 구분선(=====) 활용으로 섹션 명확히 분리
338
+ - 중요 정보는 박스 처리 또는 배경색 변경
339
+ - 단계별 가이드는 아이콘과 함께 시각화
340
+ - 모바일에서도 스크롤하며 읽기 편하게 구성
341
+
342
+ 🔥 핵심 강조 요소
343
+ - "1시간마다 1명씩" - 긴급성 강조
344
+ - "하루 24명" - 기회의 많음 어필
345
+ - 상품 이미지 - 실제 혜택 시각화
346
+ - 참여 방법 - 간단함 강조"""
347
+
348
+ return advice
349
+
350
+ # ================== API 연동 모듈 ==================
351
+ class APIIntegrations:
352
+ def __init__(self):
353
+ self.api_status = {}
354
+
355
+ def test_instagram_api(self, access_token):
356
+ """Instagram API 연결 테스트"""
357
+ try:
358
+ if not access_token:
359
+ return {"status": "error", "message": "Access Token이 필요합니다"}
360
+
361
+ url = f"https://graph.instagram.com/me?fields=id,username&access_token={access_token}"
362
+ response = requests.get(url, timeout=10)
363
+
364
+ if response.status_code == 200:
365
+ data = response.json()
366
+ return {
367
+ "status": "success",
368
+ "message": f"Instagram 연결 성공 - @{data.get('username', 'unknown')}"
369
+ }
370
+ else:
371
+ return {"status": "error", "message": "Instagram API 인증 실패"}
372
+
373
+ except Exception as e:
374
+ return {"status": "error", "message": f"Instagram 연결 오류: {str(e)}"}
375
+
376
+ def test_analytics_api(self, tracking_id):
377
+ """Google Analytics 연결 테스트"""
378
+ try:
379
+ if not tracking_id:
380
+ return {"status": "error", "message": "Tracking ID가 필요합니다"}
381
+
382
+ if tracking_id.startswith("G-"):
383
+ return {"status": "success", "message": f"Google Analytics 설정 확인됨 - {tracking_id}"}
384
+ else:
385
+ return {"status": "error", "message": "올바른 GA4 Tracking ID 형식이 아닙니다 (G-XXXXXXXXX)"}
386
+
387
+ except Exception as e:
388
+ return {"status": "error", "message": f"Analytics 연결 오류: {str(e)}"}
389
+
390
+ def test_openai_api(self, api_key):
391
+ """OpenAI API 연결 테스트"""
392
+ try:
393
+ if not api_key:
394
+ return {"status": "error", "message": "API Key가 필요합니다"}
395
+
396
+ headers = {
397
+ "Authorization": f"Bearer {api_key}",
398
+ "Content-Type": "application/json"
399
+ }
400
+
401
+ url = "https://api.openai.com/v1/models"
402
+ response = requests.get(url, headers=headers, timeout=10)
403
+
404
+ if response.status_code == 200:
405
+ return {"status": "success", "message": "OpenAI API 연결 성공"}
406
+ else:
407
+ return {"status": "error", "message": "OpenAI API 인증 실패"}
408
+
409
+ except Exception as e:
410
+ return {"status": "error", "message": f"OpenAI API 연결 오류: {str(e)}"}
411
+
412
+ def test_all_connections(self, enable_instagram, instagram_token, enable_analytics, ga_tracking_id, enable_chatgpt, openai_api_key):
413
+ """모든 API 연결 테스트"""
414
+ results = []
415
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
416
+
417
+ results.append(f"🔍 API 연결 테스트 결과 - {timestamp}\n" + "="*50 + "\n")
418
+
419
+ if enable_instagram:
420
+ instagram_result = self.test_instagram_api(instagram_token)
421
+ status_icon = "✅" if instagram_result["status"] == "success" else "❌"
422
+ results.append(f"{status_icon} Instagram: {instagram_result['message']}")
423
+
424
+ if enable_analytics:
425
+ analytics_result = self.test_analytics_api(ga_tracking_id)
426
+ status_icon = "✅" if analytics_result["status"] == "success" else "❌"
427
+ results.append(f"{status_icon} Analytics: {analytics_result['message']}")
428
+
429
+ if enable_chatgpt:
430
+ openai_result = self.test_openai_api(openai_api_key)
431
+ status_icon = "✅" if openai_result["status"] == "success" else "❌"
432
+ results.append(f"{status_icon} OpenAI: {openai_result['message']}")
433
+
434
+ if len(results) == 1:
435
+ results.append("⚠️ 설정된 API가 없습니다. API를 활성화해주세요.")
436
+
437
+ return "\n".join(results)
438
+
439
+ def generate_enhanced_concept_with_chatgpt(self, month, api_key):
440
+ """ChatGPT API를 활용한 고도화된 컨셉 생성"""
441
+ try:
442
+ headers = {
443
+ "Authorization": f"Bearer {api_key}",
444
+ "Content-Type": "application/json"
445
+ }
446
+
447
+ prompt = f"""
448
+ {month}에 진행할 20-40대 여성 대상 이벤트의 창의적인 컨셉을 3개 제안해주세요.
449
+ 각 컨셉은 다음을 포함해야 합니다:
450
+ - 컨셉명
451
+ - 핵심 아이디어
452
+ - 예상 참여도 (1-10점)
453
+ - 타겟층 특징
454
+ - 트렌디한 해시태그 3개
455
+ - 실행 방법
456
+
457
+ 현재 유행하는 소셜미디어 트렌드와 MZ세대 관심사를 반영해주세요.
458
+ 2024년 하반기 트렌드를 고려하여 답변해주세요.
459
+ """
460
+
461
+ data = {
462
+ "model": "gpt-3.5-turbo",
463
+ "messages": [
464
+ {"role": "user", "content": prompt}
465
+ ],
466
+ "max_tokens": 1500,
467
+ "temperature": 0.8
468
+ }
469
+
470
+ response = requests.post(
471
+ "https://api.openai.com/v1/chat/completions",
472
+ headers=headers,
473
+ json=data,
474
+ timeout=30
475
+ )
476
+
477
+ if response.status_code == 200:
478
+ result = response.json()
479
+ enhanced_content = result["choices"][0]["message"]["content"]
480
+
481
+ return f"""🤖 AI로 강화된 {month} 이벤트 컨셉
482
+
483
+ {enhanced_content}
484
+
485
+ ---
486
+ 💡 이 컨셉들을 기본 컨셉과 결합하여 더욱 창의적인 이벤트를 만들어보세요!
487
+ 📊 각 컨셉의 예상 참여도를 참고하여 최적의 컨셉을 선택하실 수 있습니다."""
488
+ else:
489
+ return "ChatGPT API 요청 실패. API Key와 네트워크 연결을 확인해주세요."
490
+
491
+ except Exception as e:
492
+ return f"ChatGPT API 오류: {str(e)}"
493
+
494
+ # ================== 메인 애플리케이션 ==================
495
+ def create_interface():
496
+ concept_analyzer = ConceptAnalyzer()
497
+ event_manager = EventManager()
498
+ api_integrations = APIIntegrations()
499
+
500
+ with gr.Blocks(title="통합 이벤트 관리 시스템", theme=gr.themes.Soft()) as demo:
501
+
502
+ gr.Markdown("# 🎉 통합 이벤트 관리 시스템")
503
+ gr.Markdown("### 컨셉 분석 + 이벤트 생성 + API 연동을 한 번에!")
504
+
505
+ with gr.Tabs():
506
+ # 탭 1: 컨셉 분석
507
+ with gr.Tab("🎯 컨셉 분석"):
508
+ with gr.Row():
509
+ with gr.Column():
510
+ gr.Markdown("## 📅 이벤트 기간 설정")
511
+ concept_event_period = gr.Textbox(
512
+ label="이벤트 기간",
513
+ placeholder="예: 2025.8.1 ~ 2025.8.10",
514
+ info="기간을 입력하면 자동으로 월별 컨셉 분석"
515
+ )
516
+
517
+ concept_month = gr.Dropdown(
518
+ choices=[f"{i}월" for i in range(1, 13)],
519
+ label="월 선택",
520
+ value="8월"
521
+ )
522
+
523
+ analyze_concept_btn = gr.Button("🔍 컨셉 분석하기", variant="primary")
524
+
525
+ selected_concept = gr.Dropdown(
526
+ label="분석된 컨셉 선택",
527
+ visible=False
528
+ )
529
+
530
+ with gr.Column():
531
+ concept_result = gr.Textbox(
532
+ label="컨셉 분석 결과",
533
+ lines=25,
534
+ placeholder="'컨셉 분석하기' 버튼을 클릭하세요"
535
+ )
536
+
537
+ # 탭 2: 이벤트 생성
538
+ with gr.Tab("📋 이벤트 생성"):
539
+ with gr.Row():
540
+ with gr.Column():
541
+ gr.Markdown("## 📅 기본 정보")
542
+ event_start_date = gr.Textbox(
543
+ label="시작일",
544
+ placeholder="YYYY-MM-DD",
545
+ value="2025-08-01"
546
+ )
547
+
548
+ event_end_date = gr.Textbox(
549
+ label="종료일",
550
+ placeholder="YYYY-MM-DD",
551
+ value="2025-08-10"
552
+ )
553
+
554
+ event_concept_input = gr.Textbox(
555
+ label="이벤트 컨셉",
556
+ placeholder="분석된 컨셉을 선택하거나