관리 메뉴

Leo's Garage

OpenAI/ChatGPT를 이용하여 블로그 포스팅 자동화하기 - Pandas 활용 본문

Study/AI Services

OpenAI/ChatGPT를 이용하여 블로그 포스팅 자동화하기 - Pandas 활용

LeoBehindK 2023. 2. 1. 08:31
728x90
반응형

이번에는 OpenAI API를 사용하여 블로그 포스팅을 하는 법을 간략하게 설명하겠다.

우선 이를 하기에 앞서서 OpenAI의 API를 발급받아야한다.

API를 발급받는 방법과 간단하게 Python에서 OpenAI API를 사용하는 방법은 아래 포스팅에서 확인바란다.

https://downyk.tistory.com/77

 

OpenAI API를 Python에 연동하는 방법

prompt를 통해서 문답하는 OpenAI의 API를 Python에서 사용하는 방법에 대해 간략히 설명하겠다. Setting up API credentials Python에 통합하기에 앞서서 먼저 OpenAI의 API를 발급받아야 한다. https://platform.openai.c

downyk.tistory.com

이 방법에서는 블로그의 주제를 csv 파일에 미리 저장해놓고 해당 주제에 따라서 블로그에 포스팅할 내용을 OpenAI를 통해 작성하게 만든다.

우선 아래와 같이 블로그에 포스팅할 주제를 담은 csv file을 생성한다.

id,subjects
1,Data Science with Python
2,Introduction to Machine Learning
3,Using Artificial Intelligence in Business

지금은 3개만 작성했는데 필요에 따라서 그 이상 작성해도 된다.

이렇게 작성한 csv파일을 pandas로 불러오고 아래와 같이 OpenAI 코드를 작성한다.

import openai
import pandas as pd

# Load API Key
openai.api_key = "your_api_key_here"

# Load csv file
data = pd.read_csv("blog_subjects.csv")

# Function to generate blog title, post, hashtag, and thumbnail
def generate_blog_content(subject):
    # Generate blog title
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=f"Blog Title: {subject} Can you recommend title for this [subject]",
        max_tokens=1000,
        n=1,
        stop=None,
        temperature=0.5,
    )
    title = response["choices"][0]["text"].strip()
    
    # Generate blog post
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=f"Blog Post: {subject}, Write a blog about {subject} Write a blog article around 2000 words in markdown format. and include subtitle and detail description in english. ",
        max_tokens=3500,
        n=1,
        stop=None,
        temperature=0.5,
    )
    post = response["choices"][0]["text"].strip()
    
    # Generate hashtags
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=f"generate 10 hashtags fit to this blog title. [title] and don't use '#' in front of each tags, connect each hashtag with comma",
        max_tokens=1000,
        n=1,
        stop=None,
        temperature=0.5,
    )
    hashtags = response["choices"][0]["text"].strip()
    
    # Generate thumbnail
    response = openai.Completion.create(
        engine="text-davinci-002",
        prompt=f"[INFO:Use the Unsplash API(https://source.unsplash.com/1600x900/?<PUT YOUR QUERY HERE>]. the query is just some tags that describes the image. Write the final image URL.] ##DO NOT RESPOND TO INFO BLOCK## give me a blog cover image url fit to the subject: [subject]}",
        max_tokens=1000,
        n=1,
        stop=None,
        temperature=0.5,
    )
    thumbnail = response["choices"][0]["text"].strip()
    
    return title, post, hashtags, thumbnail

# Loop through the subjects and generate content
for i, subject in enumerate(data["subjects"]):
    title, post, hashtags, thumbnail = generate_blog_content(subject)
    data.at[i, "title"] = title
    data.at[i, "post"] = post
    data.at[i, "hashtags"] = hashtags
    data.at[i, "thumbnail"] = thumbnail

# Save the result to a new csv file
data.to_csv("blog_content.csv", index=False)

위와 같이 각 주제에 맞게 제목, 블로그 내용, 이미지, 해시테그를 자동으로 생성할 수 있다. 

csv에 미리 지정해놓은 주제만큼 각 내용이 자동으로 OpenAI를 통해 생성되며 지정한 "blog_content.csv"에 저장되게 된다.

현재는 영어로 블로그를 작성하게 하였다.

이유는 한글로 할 경우, 현재 OpenAI 속도 문제도 그렇고 정상적으로 Output이 나오지 않는 이슈가 있다.

해결방법을 찾으면 해당 내용도 올리도록 하겠다.

728x90
반응형
Comments