openai 관련 설정

API KEY 발급 방법 - API KEY 신청 주소 - https://beta.openai.com/ 회원 가입 후 - https://beta.openai.com/account/api-keys - create new key

# openai 설치 코드
# !pip install openai
import openai

openai.api_key = "OPEN API 키 입력"

주제와 지시사항을 선정

주제를 선정합니다.

city = "New York"
topic = f"Top 10 Restaurants you must visit when traveling to {city}"
category = "travel"
print(topic)

세부 지시사항을 입력합니다. - https://translate.google.com/

# 프롬프트 (내용 수정 가능)
prompt = f'''
Write blog posts in markdown format.
Write the theme of your blog as "{topic}".
Highlight, bold, or italicize important words or sentences.
Please include the restaurant's address, menu recommendations and other helpful information(opening and closing hours) as a list style.
Please make the entire blog less than 10 minutes long.
The audience of this article is 20-40 years old.
Create several hashtags and add them only at the end of the line.
Add a summary of the entire article at the beginning of the blog post.
'''

chatgpt api로 블로그 주제와 지시문을 전달하여 글을 생성

def generate_blog(topic, prompt):
    # 모델 엔진 선택
    model_engine = "text-davinci-003"

    # 맥스 토큰
    max_tokens = 2048

    # 블로그 생성
    completion = openai.Completion.create(
        engine=model_engine,
        prompt=prompt,
        max_tokens=max_tokens,
        temperature=0.3,      # creativity
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    return completion

결과를 전달 받아 출력합니다.

response = generate_blog(topic, prompt)
# 생성된 글 출력
print(response.choices[0].text)

해시태그 추출

import re

hashtag_pattern = r'(#+[a-zA-Z0-9(_)]{1,})'

re.findall(hashtag_pattern, response['choices'][0]['text'])

해시태그를 태그화 하기 위하여 다음과 같이 문자열 형태로 변경합니다.

hashtags = [w[1:] for w in re.findall(hashtag_pattern, response['choices'][0]['text'])]
tag_string = ""
for w in hashtags:
    tag_string += f'{w}, '
tag_string
tag_string = re.sub(r'[^a-zA-Z, ]', '', tag_string)
tag_string = tag_string.strip()[:-1]
tag_string

마크다운 형식의 블로그 글 생성

아래는 블로그의 헤더 입니다. 블로그 발행시 적용할 옵션을 지정합니다.

page_head = f'''---
layout: single
title:  "{topic}"
categories: {category}
tag: [{tag_string}]
toc: false
author_profile: false
sidebar:
    nav: "counts"
---
'''
print(page_head)
# 첫 줄은 타이틀(제목)과 겹치기 때문에 제거하도록 합니다.
body = '\n'.join(response['choices'][0]['text'].strip().split('\n')[1:])

헤더 + 블로그 본문 을 결합하여 최종 블로그 글을 완성합니다.

output = page_head + body
print(output)

블로그 .md 파일명에 기입할 날짜 형식을 생성

import os
from datetime import datetime, timedelta

# 어제 일자 생성
yesterday = datetime.now() - timedelta(days=1)
yesterday

블로그 파일명에 입력할 날짜 형식을 위한 처리를 수행합니다.

timestring = yesterday.strftime('%Y-%m-%d')
timestring

파일명을 생성합니다. - 여기서 날짜 + 블로그제목 형식으로 공백 없이 파일명을 생성합니다.

filename = f"{timestring}-{'-'.join(topic.lower().split())}.md"
filename

생성한 블로그를 github pages 경로에 생성

블로그의 _posts가 위치한 절대 경로를 지정합니다.

# github pages 주소의 _posts 절대 경로 지정
blog_directory = r"블로그_root_폴더/_posts"

블로그 경로 + 파일 이름 으로 마크다운 파일을 저장할 전체 경로를 생성합니다.

# 파일 이름 생성
filepath = os.path.join(blog_directory, filename)
filepath

마지막으로 파일에 마크다운으로 작성된 블로그 글을 쓰고 저장합니다.

with open(filepath, 'w') as f:
    f.write(output)
    f.close()