본문 바로가기

Languages&Library/Python

Perplexity API를 활용한 블로그 포스트 자동 생성기

반응형
import os
import re
import openai
from datetime import datetime

사용자 정의 함수: Perplexity API로 글 작성
def generate_blog_posts(api_key, query_list, prompts, output_dir="output"):
    """
    Perplexity API를 이용해 특정 주제와 프롬프트로 블로그 글을 작성하는 함수.
    Parameters:
        api_key (str): Perplexity API 키
        query_list (list): 주제(키워드) 리스트
        prompts (dict): 각 주제에 대한 프롬프트 딕셔너리
        output_dir (str): 결과 파일을 저장할 디렉토리 경로 (기본값: "output")
    """
    # 결과 저장 디렉토리 생성
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Perplexity API 클라이언트 초기화
    client = openai.OpenAI(
        api_key=api_key,
        base_url="https://api.perplexity.ai"
    )

    for topic in query_list:
        # 프롬프트 가져오기
        prompt = prompts.get(topic, "주제에 대한 프롬프트가 없습니다.")
        messages = [
            {"role": "system", "content": "당신은 유능한 블로그 작성자이자 뉴스 요약 전문가입니다."},
            {"role": "user", "content": prompt}
        ]

        try:
            # Perplexity API 호출
            response = client.chat.completions.create(
                model="sonar-pro",  # Perplexity API 문서에 명시된 허용 모델 사용
                messages=messages,
                max_tokens=1024,
                temperature=0.7
            )

            # 응답에서 최종 내용 추출
            final_content = response.choices[0].message.content
            final_content = append_placeholder_links(final_content)

            # 날짜 기반 파일명 생성 및 저장 (예: blog_post_육아_20250410.txt)
            file_name = os.path.join(output_dir, f"blog_post_{topic}_{datetime.now().strftime('%Y%m%d')}.txt")
            with open(file_name, "w", encoding="utf-8") as f:
                f.write(final_content)
            print(f"✅ 저장 완료: {file_name}")

        except Exception as e:
            print(f"[오류 발생 - {topic}] {str(e)}")

def append_placeholder_links(content):
    '''
    Parameters:
        content (str): 응답 내용

    Returns:
        str: 참고 링크가 포함된 최종 내용
    ''' 
    refs = re.findall(r'\[(\d+)\]', content)
    unique_refs = sorted(set(refs), key=int)
    existing_links = re.findall(r'^\[(\d+)\].+', content, re.MULTILINE)
    missing_refs = [ref for ref in unique_refs if ref not in existing_links]

    if missing_refs:
        placeholders = "\n\n" + "\n".join([f"[{ref}] Link not available." for ref in missing_refs])
        content += placeholders

    return content
    
 if name == "main":
    # 사용자 입력 받기
    api_key = input("Perplexity API 키를 입력하세요: ").strip()
    # 검색 키워드와 프롬프트 설정 (필요에 따라 확장 가능)
    query_list = input("검색할 주제(키워드)를 쉼표로 구분하여 입력하세요 (예: 뉴스, 재테크, 인공지능): ").split(",")

    prompts = {
        "재테크": (
            "재테크 동향, 투자 방법, 금융 시장 분석, 전문가 의견 및 성공 사례를 구체적으로 소개합니다. "
            "데이터나 구체적 숫자를 포함해서 신뢰성 있는 정보를 제공해 주세요."
        )
    }

    # 함수 호출
    generate_blog_posts(api_key=api_key, query_list=query_list, prompts=prompts)

 

 

반응형