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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -19
app.py CHANGED
@@ -97,7 +97,6 @@ class ConceptAnalyzer:
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
 
@@ -123,12 +122,10 @@ class ConceptAnalyzer:
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({
@@ -142,7 +139,6 @@ class ConceptAnalyzer:
142
  "is_recommended": True
143
  })
144
 
145
- # 컨셉 2
146
  if data.get("trends"):
147
  trend = data["trends"][0]
148
  concepts.append({
@@ -156,7 +152,6 @@ class ConceptAnalyzer:
156
  "is_recommended": False
157
  })
158
 
159
- # 컨셉 3
160
  concepts.append({
161
  "name": f"{month} 셀프케어 위크",
162
  "theme": "나를 위한 특별한 시간",
@@ -207,7 +202,6 @@ class EventManager:
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")
@@ -222,12 +216,9 @@ class EventManager:
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:
@@ -316,8 +307,6 @@ ex) 주말 당첨시, 고객센터 영업일(월) 업무 종료시간 19:00시
316
  return template
317
 
318
  def generate_design_advice(self, concept):
319
- """디자인 조언 생성"""
320
-
321
  advice = f"""🎨 디자인 조언 ({concept} 테마)
322
 
323
  🎯 컬러 팔레트
@@ -353,7 +342,6 @@ class APIIntegrations:
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이 필요합니다"}
@@ -374,7 +362,6 @@ class APIIntegrations:
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가 필요합니다"}
@@ -388,7 +375,6 @@ class APIIntegrations:
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가 필요합니다"}
@@ -410,7 +396,6 @@ class APIIntegrations:
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
 
@@ -437,7 +422,6 @@ class APIIntegrations:
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}",
@@ -503,7 +487,6 @@ def create_interface():
503
  gr.Markdown("### 컨셉 분석 + 이벤트 생성 + API 연동을 한 번에!")
504
 
505
  with gr.Tabs():
506
- # 탭 1: 컨셉 분석
507
  with gr.Tab("🎯 컨셉 분석"):
508
  with gr.Row():
509
  with gr.Column():
@@ -534,7 +517,6 @@ def create_interface():
534
  placeholder="'컨셉 분석하기' 버튼을 클릭하세요"
535
  )
536
 
537
- # 탭 2: 이벤트 생성
538
  with gr.Tab("📋 이벤트 생성"):
539
  with gr.Row():
540
  with gr.Column():
@@ -553,4 +535,248 @@ def create_interface():
553
 
554
  event_concept_input = gr.Textbox(
555
  label="이벤트 컨셉",
556
- placeholder="분석된 컨셉을 선택하거나
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  }
98
 
99
  def extract_month_from_period(self, period_text):
 
100
  if not period_text or period_text.strip() == "":
101
  return None
102
 
 
122
  return None
123
 
124
  def analyze_concepts(self, month):
 
125
  data = self.monthly_data.get(month, {})
126
 
127
  concepts = []
128
 
 
129
  if data.get("special_days"):
130
  special = data["special_days"][0]
131
  concepts.append({
 
139
  "is_recommended": True
140
  })
141
 
 
142
  if data.get("trends"):
143
  trend = data["trends"][0]
144
  concepts.append({
 
152
  "is_recommended": False
153
  })
154
 
 
155
  concepts.append({
156
  "name": f"{month} 셀프케어 위크",
157
  "theme": "나를 위한 특별한 시간",
 
202
  ]
203
 
204
  def calculate_event_duration(self, start_date, end_date):
 
205
  try:
206
  start = datetime.strptime(start_date, "%Y-%m-%d")
207
  end = datetime.strptime(end_date, "%Y-%m-%d")
 
216
  return 0, 0, "", "", None, None
217
 
218
  def generate_detailed_comment_event(self, start_date, end_date, concept, reward_structure, kakao_id, phone_number):
 
 
219
  if not concept:
220
  return "먼저 이벤트 컨셉을 입력해주세요."
221
 
 
222
  duration_info, month, start_weekday, end_weekday, start_dt, end_dt = self.calculate_event_duration(start_date, end_date)
223
 
224
  if duration_info == 0:
 
307
  return template
308
 
309
  def generate_design_advice(self, concept):
 
 
310
  advice = f"""🎨 디자인 조언 ({concept} 테마)
311
 
312
  🎯 컬러 팔레트
 
342
  self.api_status = {}
343
 
344
  def test_instagram_api(self, access_token):
 
345
  try:
346
  if not access_token:
347
  return {"status": "error", "message": "Access Token이 필요합니다"}
 
362
  return {"status": "error", "message": f"Instagram 연결 오류: {str(e)}"}
363
 
364
  def test_analytics_api(self, tracking_id):
 
365
  try:
366
  if not tracking_id:
367
  return {"status": "error", "message": "Tracking ID가 필요합니다"}
 
375
  return {"status": "error", "message": f"Analytics 연결 오류: {str(e)}"}
376
 
377
  def test_openai_api(self, api_key):
 
378
  try:
379
  if not api_key:
380
  return {"status": "error", "message": "API Key가 필요합니다"}
 
396
  return {"status": "error", "message": f"OpenAI API 연결 오류: {str(e)}"}
397
 
398
  def test_all_connections(self, enable_instagram, instagram_token, enable_analytics, ga_tracking_id, enable_chatgpt, openai_api_key):
 
399
  results = []
400
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
401
 
 
422
  return "\n".join(results)
423
 
424
  def generate_enhanced_concept_with_chatgpt(self, month, api_key):
 
425
  try:
426
  headers = {
427
  "Authorization": f"Bearer {api_key}",
 
487
  gr.Markdown("### 컨셉 분석 + 이벤트 생성 + API 연동을 한 번에!")
488
 
489
  with gr.Tabs():
 
490
  with gr.Tab("🎯 컨셉 분석"):
491
  with gr.Row():
492
  with gr.Column():
 
517
  placeholder="'컨셉 분석하기' 버튼을 클릭하세요"
518
  )
519
 
 
520
  with gr.Tab("📋 이벤트 생성"):
521
  with gr.Row():
522
  with gr.Column():
 
535
 
536
  event_concept_input = gr.Textbox(
537
  label="이벤트 컨셉",
538
+ placeholder="분석된 컨셉을 선��하거나 직접 입력",
539
+ info="컨셉 분석 탭에서 선택된 컨셉이 자동 입력됩니다"
540
+ )
541
+
542
+ gr.Markdown("## 🎁 상품 설정")
543
+ reward_type_selector = gr.Radio(
544
+ choices=[
545
+ "단일 상품",
546
+ "등급별 상품 (1,2,3등)",
547
+ "선택형 상품",
548
+ "직접 입력"
549
+ ],
550
+ label="상품 구성 방식",
551
+ value="단일 상품"
552
+ )
553
+
554
+ with gr.Group(visible=True) as single_group:
555
+ single_type = gr.Dropdown(
556
+ choices=["네이버페이 금액권", "배달의민족 상품권", "스타벅스 기프트카드", "CGV 영화관람권"],
557
+ label="상품 종류",
558
+ value="네이버페이 금액권"
559
+ )
560
+ single_amount = gr.Number(label="금액 (원)", value=20000, step=1000)
561
+ single_frequency = gr.Textbox(
562
+ label="당첨 주기",
563
+ value="1시간마다 1명씩 하루 24명"
564
+ )
565
+
566
+ with gr.Group(visible=False) as grade_group:
567
+ with gr.Row():
568
+ grade1_amount = gr.Number(label="1등 금액", value=50000)
569
+ grade1_count = gr.Number(label="1등 인원", value=5)
570
+ with gr.Row():
571
+ grade2_amount = gr.Number(label="2등 금액", value=30000)
572
+ grade2_count = gr.Number(label="2등 인원", value=10)
573
+ with gr.Row():
574
+ grade3_amount = gr.Number(label="3등 금액", value=20000)
575
+ grade3_count = gr.Number(label="3등 인원", value=20)
576
+
577
+ with gr.Group(visible=False) as choice_group:
578
+ choice_amount = gr.Number(label="금액 (원)", value=20000)
579
+ choice_frequency = gr.Textbox(
580
+ label="당첨 주기",
581
+ value="1시간마다 1명씩 하루 24명"
582
+ )
583
+
584
+ with gr.Group(visible=False) as custom_group:
585
+ custom_reward = gr.Textbox(
586
+ label="상품 정보 직접 입력",
587
+ lines=5,
588
+ placeholder="상품 정보를 자유롭게 입력하세요"
589
+ )
590
+
591
+ gr.Markdown("## 📞 연락처")
592
+ phone_number = gr.Textbox(label="고객센터", value="1544-1234")
593
+ kakao_id = gr.Textbox(label="카카오톡 ID", value="company_kakao")
594
+
595
+ generate_event_btn = gr.Button("✨ 이벤트 생성하기", variant="primary")
596
+
597
+ with gr.Column():
598
+ with gr.Tabs():
599
+ with gr.Tab("📋 공지사항"):
600
+ event_result = gr.Textbox(
601
+ label="생성된 이벤트 공지사항",
602
+ lines=30,
603
+ interactive=False
604
+ )
605
+
606
+ with gr.Tab("🎨 디자인 가이드"):
607
+ design_result = gr.Textbox(
608
+ label="디자인 가이드",
609
+ lines=20,
610
+ interactive=False
611
+ )
612
+
613
+ with gr.Tab("🔗 API 연동"):
614
+ with gr.Row():
615
+ with gr.Column():
616
+ gr.Markdown("## 🌐 외부 API 설정")
617
+
618
+ with gr.Group():
619
+ gr.Markdown("### 📱 소셜미디어 API")
620
+ enable_instagram = gr.Checkbox(label="Instagram API 연동", value=False)
621
+ instagram_token = gr.Textbox(
622
+ label="Instagram Access Token",
623
+ type="password",
624
+ visible=False
625
+ )
626
+
627
+ with gr.Group():
628
+ gr.Markdown("### 📊 분석 & AI API")
629
+ enable_analytics = gr.Checkbox(label="Google Analytics", value=False)
630
+ ga_tracking_id = gr.Textbox(
631
+ label="GA Tracking ID",
632
+ visible=False
633
+ )
634
+
635
+ enable_chatgpt = gr.Checkbox(label="ChatGPT API (컨셉 생성)", value=False)
636
+ openai_api_key = gr.Textbox(
637
+ label="OpenAI API Key",
638
+ type="password",
639
+ visible=False
640
+ )
641
+
642
+ test_api_btn = gr.Button("🔍 API 연결 테스트", variant="secondary")
643
+ enhance_concept_btn = gr.Button("✨ AI로 컨셉 강화", variant="primary")
644
+
645
+ with gr.Column():
646
+ api_status = gr.Textbox(
647
+ label="API 연동 상태",
648
+ lines=15,
649
+ placeholder="API 설정 후 연결 테스트를 진행하세요"
650
+ )
651
+
652
+ ai_enhanced_result = gr.Textbox(
653
+ label="AI 강화 컨셉",
654
+ lines=15,
655
+ placeholder="ChatGPT API로 컨셉을 더욱 창의적으로 발전시킬 수 있습니다"
656
+ )
657
+
658
+ concepts_state = gr.State([])
659
+
660
+ def handle_period_change(period_text):
661
+ month = concept_analyzer.extract_month_from_period(period_text)
662
+ if month:
663
+ return gr.update(value=month)
664
+ return gr.update()
665
+
666
+ def handle_concept_analysis(month):
667
+ result, concepts = concept_analyzer.analyze_concepts(month)
668
+ return (
669
+ result,
670
+ gr.update(choices=concepts, visible=True, value=concepts[0] if concepts else ""),
671
+ concepts
672
+ )
673
+
674
+ def handle_concept_selection(concept):
675
+ return gr.update(value=concept)
676
+
677
+ def update_reward_ui(reward_type):
678
+ return (
679
+ gr.update(visible=(reward_type == "단일 상품")),
680
+ gr.update(visible=(reward_type == "등급별 상품 (1,2,3등)")),
681
+ gr.update(visible=(reward_type == "선택형 상품")),
682
+ gr.update(visible=(reward_type == "직접 입력"))
683
+ )
684
+
685
+ def generate_event_template(start_date, end_date, concept, reward_type,
686
+ single_type, single_amount, single_frequency,
687
+ g1_amount, g1_count, g2_amount, g2_count, g3_amount, g3_count,
688
+ choice_amount, choice_frequency, custom_reward,
689
+ phone, kakao):
690
+
691
+ if reward_type == "단일 상품":
692
+ reward_structure = f"{single_type} {int(single_amount):,}원\n{single_frequency}"
693
+ elif reward_type == "등급별 상품 (1,2,3등)":
694
+ reward_structure = f"🥇 1등: {int(g1_amount):,}원 ({int(g1_count)}명)\n🥈 2등: {int(g2_amount):,}원 ({int(g2_count)}명)\n🥉 3등: {int(g3_amount):,}원 ({int(g3_count)}명)"
695
+ elif reward_type == "선택형 상품":
696
+ reward_structure = f"네이버페이 or 배달의민족 {int(choice_amount):,}원\n{choice_frequency}"
697
+ else:
698
+ reward_structure = custom_reward
699
+
700
+ event_template = event_manager.generate_detailed_comment_event(
701
+ start_date, end_date, concept, reward_structure, kakao, phone
702
+ )
703
+
704
+ design_guide = event_manager.generate_design_advice(concept)
705
+
706
+ return event_template, design_guide
707
+
708
+ def toggle_api_inputs(instagram, analytics, chatgpt):
709
+ return (
710
+ gr.update(visible=instagram),
711
+ gr.update(visible=analytics),
712
+ gr.update(visible=chatgpt)
713
+ )
714
+
715
+ def test_api_connections(enable_instagram, instagram_token, enable_analytics, ga_tracking_id, enable_chatgpt, openai_api_key):
716
+ return api_integrations.test_all_connections(enable_instagram, instagram_token, enable_analytics, ga_tracking_id, enable_chatgpt, openai_api_key)
717
+
718
+ def enhance_with_ai(month, openai_key):
719
+ if not openai_key:
720
+ return "OpenAI API Key를 입력해주세요."
721
+ return api_integrations.generate_enhanced_concept_with_chatgpt(month, openai_key)
722
+
723
+ concept_event_period.change(
724
+ handle_period_change,
725
+ inputs=[concept_event_period],
726
+ outputs=[concept_month]
727
+ )
728
+
729
+ analyze_concept_btn.click(
730
+ handle_concept_analysis,
731
+ inputs=[concept_month],
732
+ outputs=[concept_result, selected_concept, concepts_state]
733
+ )
734
+
735
+ selected_concept.change(
736
+ handle_concept_selection,
737
+ inputs=[selected_concept],
738
+ outputs=[event_concept_input]
739
+ )
740
+
741
+ reward_type_selector.change(
742
+ update_reward_ui,
743
+ inputs=[reward_type_selector],
744
+ outputs=[single_group, grade_group, choice_group, custom_group]
745
+ )
746
+
747
+ generate_event_btn.click(
748
+ generate_event_template,
749
+ inputs=[
750
+ event_start_date, event_end_date, event_concept_input, reward_type_selector,
751
+ single_type, single_amount, single_frequency,
752
+ grade1_amount, grade1_count, grade2_amount, grade2_count, grade3_amount, grade3_count,
753
+ choice_amount, choice_frequency, custom_reward,
754
+ phone_number, kakao_id
755
+ ],
756
+ outputs=[event_result, design_result]
757
+ )
758
+
759
+ for checkbox in [enable_instagram, enable_analytics, enable_chatgpt]:
760
+ checkbox.change(
761
+ toggle_api_inputs,
762
+ inputs=[enable_instagram, enable_analytics, enable_chatgpt],
763
+ outputs=[instagram_token, ga_tracking_id, openai_api_key]
764
+ )
765
+
766
+ test_api_btn.click(
767
+ test_api_connections,
768
+ inputs=[enable_instagram, instagram_token, enable_analytics, ga_tracking_id, enable_chatgpt, openai_api_key],
769
+ outputs=[api_status]
770
+ )
771
+
772
+ enhance_concept_btn.click(
773
+ enhance_with_ai,
774
+ inputs=[concept_month, openai_api_key],
775
+ outputs=[ai_enhanced_result]
776
+ )
777
+
778
+ return demo
779
+
780
+ if __name__ == "__main__":
781
+ demo = create_interface()
782
+ demo.launch()