본문 바로가기
블로그 글 생성기

글 생성기 특별편

by travelai 2023. 4. 12.
반응형
import csv
import time
import os
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QFileDialog, QLineEdit, QTextEdit
import openai

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.csv_file = None
        self.output_dir = None
        self.api_key = None

        self.init_ui()

    def init_ui(self):
        # UI 초기화
        self.setGeometry(100, 100, 500, 300)
        self.setWindowTitle('OpenAI Article Generator')

        # UI 위젯 생성
        self.csv_label = QLabel('CSV 파일 선택', self)
        self.csv_label.move(20, 20)

        self.csv_button = QPushButton('파일 선택', self)
        self.csv_button.move(120, 20)
        self.csv_button.clicked.connect(self.select_csv_file)

        self.output_label = QLabel('저장 경로', self)
        self.output_label.move(20, 60)

        self.output_button = QPushButton('폴더 선택', self)
        self.output_button.move(120, 60)
        self.output_button.clicked.connect(self.select_output_dir)

        self.api_key_label = QLabel('OpenAI API 키', self)
        self.api_key_label.move(20, 100)

        self.api_key_edit = QLineEdit(self)
        self.api_key_edit.move(120, 100)

        self.start_button = QPushButton('시작', self)
        self.start_button.move(200, 140)
        self.start_button.clicked.connect(self.start_generation)

        self.log_text = QTextEdit(self)
        self.log_text.move(20, 180)
        self.log_text.setReadOnly(True)

        # UI 보여주기
        self.show()

    def select_csv_file(self):
        # CSV 파일 선택
        self.csv_file, _ = QFileDialog.getOpenFileName(self, 'Select CSV File', '', 'CSV Files (*.csv)')
        self.csv_label.setText(f'CSV 파일 선택: {self.csv_file}')

    def select_output_dir(self):
        # 출력 폴더 선택
        self.output_dir = QFileDialog.getExistingDirectory(self, 'Select Output Directory')
        self.output_label.setText(f'저장 경로: {self.output_dir}')

    def start_generation(self):
        # OpenAI API를 사용하여 글 생성 시작
        if not self.csv_file or not self.output_dir or not self.api_key_edit.text():
            self.log('CSV 파일, 저장 경로, API 키를 모두 입력하세요.')
            return

        self.api_key = self.api_key_edit.text()
        openai.api_key = self.api_key

        with open(self.csv_file, 'r', encoding='utf-8') as f:
            csv_reader = csv.reader(f)
            next(csv_reader) # Header skip

            for row in csv_reader:
                topic = row[0]
                file_name = os.path.join(self.output_dir, f'{topic}.txt')

                if os.path.exists(file_name):
                    self.log(f'"{file_name}" 이미 존재합니다.')
                    continue

                self.log(f'{topic} 글 생성 시작')

                try:
                    response = openai.Completion.create(
                        engine="text-curie-001",
                        prompt=f'This is a blog post about economics. Please write directly from the content without the need for an explanation of the article. As for the format of the writing, there are 3 sub-topics under the subject, and the contents under the 3 sub-topics are 300 characters each, and the subject of the writing is {topic}.',
                        max_tokens=1500,
                        n = 1,
                        temperature=0.7,
                        
                    )

                    text = response.choices[0].text

                    with open(file_name, 'w', encoding='utf-8') as f:
                        f.write(text)

                    self.log(f'{topic} 글 생성 완료')

                except Exception as e:
                    self.log(f'{topic} 글 생성 중 에러 발생: {e}')

                time.sleep(10)

    def log(self, message):
        # 로그 메시지 출력
        timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
        self.log_text.append(f'[{timestamp}] {message}')

if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    app.exec_()

말이 특별편이지 다 보시는게 좋습니다!

 

 

chatgpt 모델 

제가 작성해드린 코드 안에는 기본적으로 curie 모델이 삽입되어있습니다.

chatgpt (openai) api모델은 기본적으로 1000토큰당으로 계산이 됩니다. 가격은 아래 가셔서 보시면 되구요.

기본적으로 블로그나 스크립트를 작성할때 사용할 모델은 text 모델입니다. 

다빈치 모델이 가장 비싸고 ada가 가장 쌉니다. 

 

여기서 중요한점!!! 다빈치 이외에 text 모델들은 2019년도까지의 정보 밖에 없습니다!!!! 다빈치 모델은 chatgpt 웹사이트 버전과 같이 2021년까지의 정보가 있구요.

 

 

 

모델 다르다 = 한번에 사용할수 있는 토큰수도 다르다.

 

제가 제공해드린 코드에는 chatgpt가 답변을 할때 기본적으로 최대 1500토큰까지 쓸수 있도록 해놓았습니다. 

모델마다 최대로 요청할수 있는 토큰수가 다르니 글의 분량도 달라 지겠죠.

 

모델 설명

모델 최대 토큰수  학습 기간 가격 간단한 설명
text-curie-001 2,049 tokens Up to Oct 2019 $0.0020 / 1K tokens Very capable, faster and lower cost than Davinci.
text-babbage-001 2,049 tokens Up to Oct 2019 $0.0005 / 1K tokens Capable of straightforward tasks, very fast, and lower cost.
text-ada-001 2,049 tokens Up to Oct 2019 $0.0004 / 1K tokens Capable of very simple tasks, usually the fastest model in the GPT-3 series, and lowest cost.
text-davinci-003 4,097 tokens Up to Jun 2021 $0.0200 / 1K tokens Can do any language task with better quality, longer output, and consistent instruction-following than the curie, babbage, or ada models. Also supports inserting completions within text.
text-davinci-002 4,097 tokens Up to Jun 2021 $0.0200 / 1K tokens Similar capabilities to text-davinci-003 but trained with supervised fine-tuning instead of reinforcement learning

 

 

 

제가 제공한 코드에서

try:
                    response = openai.Completion.create(
                        engine="text-curie-001",
                        prompt=f'This is a blog post about economics. Please write directly from the content without the need for an explanation of the article. As for the format of the writing, there are 3 sub-topics under the subject, and the contents under the 3 sub-topics are 300 characters each, and the subject of the writing is {topic}.',
                        max_tokens=1500,
                        n = 1,
                        temperature=0.7,
                        
                    )

이 부분에 engine 부분을 원하는 모델로 바꾸시면 됩니다.

 

 

토큰에 대해 주의해야할 한가지!!

요청한 말 + 제공받는 글 = 토큰 요청에 반영입니다. 즉

 

맥스 토큰을 2000으로 해두고 openai api에 요청하는 글이 너무 길어서 50 토큰 이상이 나오면 

 

요청 토큰 2050토큰 으로 curie 모델을 기준으로 했을때 최대 요청 토큰수가 초과되는 것입니다.

 

그러니 토큰수를 보수적으로 잡으세요!!

 

 

https://travelai.tistory.com/12

 

블로그 자동 글 생성기 chapter 5

이전 챕터( 코드 전부 제공 ) https://travelai.tistory.com/11 사용법 1.csv 파일을 선택하시면 됩니다. csv 파일이란 " , "(쉼표)를 기준으로 구분된 파일 확장자를 말합니다. 예를 들어서 경제 관련 주제 10

2.damback.com

 

반응형

댓글