fantaxy commited on
Commit
3fbc510
·
verified ·
1 Parent(s): c9b3974

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -54
app.py CHANGED
@@ -17,6 +17,16 @@ import json
17
  from huggingface_hub.utils._errors import HfHubHTTPError
18
  from gradio_client import Client
19
  from urllib.parse import urljoin
 
 
 
 
 
 
 
 
 
 
20
 
21
  def setup_session():
22
  try:
@@ -546,55 +556,6 @@ def update_prompts_and_description(category, style):
546
  WEBHOOK_URL = os.getenv("WEBHOOK_URL")
547
  BLOGGER_ID = os.getenv("BLOGGER_ID")
548
 
549
- def send_to_blogger(blog_title, blog_content):
550
- payload = {
551
- "id": BLOGGER_ID,
552
- "title": blog_title,
553
- "content": blog_content
554
- }
555
-
556
- try:
557
- response = requests.post(WEBHOOK_URL, json=payload)
558
- if response.status_code == 200:
559
- return "포스팅이 성공적으로 전송되었습니다."
560
- else:
561
- return f"포스팅 전송 실패. 상태 코드: {response.status_code}"
562
- except Exception as e:
563
- return f"오류 발생: {str(e)}"
564
-
565
-
566
- def process_all_titles(category, style, topic):
567
- # 제목 추천
568
- title_suggestions, _ = suggest_title(category, style, topic, "", "", "")
569
- titles = title_suggestions.split('\n')
570
-
571
- results = []
572
- for title in titles[:10]: # 처음 10개의 제목만 사용
573
- try:
574
- # 블로그 글 생성
575
- _, _, _, _, _, blog_content, _ = fetch_references_and_generate_all_steps(category, style, topic, title)
576
-
577
- if blog_content.startswith("API 호출 실패"):
578
- results.append(f"제목: {title}\n생성 실패: {blog_content}\n\n")
579
- continue
580
-
581
- # 포스팅 전송
582
- send_result = send_to_blogger(title, blog_content)
583
-
584
- results.append(f"제목: {title}\n전송 결과: {send_result}\n\n")
585
- except Exception as e:
586
- results.append(f"제목: {title}\n처리 중 오류 발생: {str(e)}\n\n")
587
-
588
- time.sleep(5) # API 호출 사이에 5초 대기
589
-
590
- return "\n".join(results)
591
-
592
-
593
- BASE_URL = "http://hugpu.ai:7899" # 실제 서버 주소로 변경하세요
594
-
595
- # Pexels API 클라이언트 설정
596
- PEXELS_API_KEY = "5woz23MGx1QrSY0WHFb0BRi29JvbXPu97Hg0xnklYgHUI8G0w23FKH62"
597
- pexels_api = "5woz23MGx1QrSY0WHFb0BRi29JvbXPu97Hg0xnklYgHUI8G0w23FKH62"
598
 
599
  def get_image_url(topic):
600
  # 주제에서 핵심 키워드 추출 (여기서는 간단히 처음 두 단어를 사용)
@@ -609,13 +570,12 @@ def get_image_url(topic):
609
  # 고해상도 이미지 URL 반환
610
  return photos[0].original
611
  else:
612
- print(f"'{keywords}' 관련 이미지를 찾을 수 없습니다.")
613
  return None
614
  except Exception as e:
615
- print(f"이미지 검색 중 오류 발생: {str(e)}")
616
  return None
617
 
618
- # process_all_titles 함수 수정
619
  def process_all_titles(category, style, topic, num_titles):
620
  title_suggestions, _ = suggest_title(category, style, topic, "", "", "")
621
  titles = title_suggestions.split('\n')
@@ -641,14 +601,38 @@ def process_all_titles(category, style, topic, num_titles):
641
  # 포스팅 전송
642
  send_result = send_to_blogger(title, blog_content)
643
 
644
- results.append(f"제목: {title}\n전송 결과: {send_result}\n사용된 이미지 URL: {image_url}\n\n")
645
  except Exception as e:
 
646
  results.append(f"제목: {title}\n처리 중 오류 발생: {str(e)}\n\n")
647
 
648
  time.sleep(5) # API 호출 사이에 5초 대기
649
 
650
  return "\n".join(results)
651
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652
 
653
  with gr.Blocks() as demo:
654
  gr.Markdown(f"# {title}")
@@ -664,7 +648,7 @@ with gr.Blocks() as demo:
664
  topic = gr.Textbox(label="블로그 주제", placeholder="예시: 8월 국내 여행지 추천")
665
 
666
  gr.Markdown("### 4단계 : 자동 생성 및 전송할 블로그 수(주제는 따르되, 각기 다른 제목과 내용으로 구성)를 선택하세요")
667
- num_titles = gr.Slider(minimum=1, maximum=100, value=2, step=1, label="생성할 제목 수")
668
 
669
  start_btn = gr.Button("시작")
670
  result_output = gr.Textbox(label="처리 결과", lines=20)
 
17
  from huggingface_hub.utils._errors import HfHubHTTPError
18
  from gradio_client import Client
19
  from urllib.parse import urljoin
20
+ import requests
21
+ from pexels_api import API
22
+ import logging
23
+
24
+ # 로깅 설정
25
+ logging.basicConfig(level=logging.INFO)
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ pexels_api = "5woz23MGx1QrSY0WHFb0BRi29JvbXPu97Hg0xnklYgHUI8G0w23FKH62"
30
 
31
  def setup_session():
32
  try:
 
556
  WEBHOOK_URL = os.getenv("WEBHOOK_URL")
557
  BLOGGER_ID = os.getenv("BLOGGER_ID")
558
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559
 
560
  def get_image_url(topic):
561
  # 주제에서 핵심 키워드 추출 (여기서는 간단히 처음 두 단어를 사용)
 
570
  # 고해상도 이미지 URL 반환
571
  return photos[0].original
572
  else:
573
+ logger.warning(f"'{keywords}' 관련 이미지를 찾을 수 없습니다.")
574
  return None
575
  except Exception as e:
576
+ logger.error(f"이미지 검색 중 오류 발생: {str(e)}")
577
  return None
578
 
 
579
  def process_all_titles(category, style, topic, num_titles):
580
  title_suggestions, _ = suggest_title(category, style, topic, "", "", "")
581
  titles = title_suggestions.split('\n')
 
601
  # 포스팅 전송
602
  send_result = send_to_blogger(title, blog_content)
603
 
604
+ results.append(f"제목: {title}\n전송 결과: {send_result}\n사용된 이미지 URL: {image_url if image_url else '이미지 없음'}\n\n")
605
  except Exception as e:
606
+ logger.error(f"제목 '{title}' 처리 중 오류 발생: {str(e)}")
607
  results.append(f"제목: {title}\n처리 중 오류 발생: {str(e)}\n\n")
608
 
609
  time.sleep(5) # API 호출 사이에 5초 대기
610
 
611
  return "\n".join(results)
612
 
613
+ def send_to_blogger(blog_title, blog_content):
614
+ payload = {
615
+ "id": BLOGGER_ID,
616
+ "title": blog_title,
617
+ "content": blog_content
618
+ }
619
+
620
+ try:
621
+ # URL 유효성 검사
622
+ if "![관련 이미지](None)" in blog_content:
623
+ blog_content = blog_content.replace("![관련 이미지](None)", "관련 이미지를 찾을 수 없습니다.")
624
+
625
+ payload["content"] = blog_content
626
+
627
+ response = requests.post(WEBHOOK_URL, json=payload)
628
+ if response.status_code == 200:
629
+ return "포스팅이 성공적으로 전송되었습니다."
630
+ else:
631
+ return f"포스팅 전송 실패. 상태 코드: {response.status_code}"
632
+ except Exception as e:
633
+ logger.error(f"블로거에 전송 중 오류 발생: {str(e)}")
634
+ return f"오류 발생: {str(e)}"
635
+
636
 
637
  with gr.Blocks() as demo:
638
  gr.Markdown(f"# {title}")
 
648
  topic = gr.Textbox(label="블로그 주제", placeholder="예시: 8월 국내 여행지 추천")
649
 
650
  gr.Markdown("### 4단계 : 자동 생성 및 전송할 블로그 수(주제는 따르되, 각기 다른 제목과 내용으로 구성)를 선택하세요")
651
+ num_titles = gr.Slider(minimum=1, maximum=100, value=2, step=1, label="생성/전송할 블로그그 수")
652
 
653
  start_btn = gr.Button("시작")
654
  result_output = gr.Textbox(label="처리 결과", lines=20)