반응형
티스토리 블로그 글 생성기 class 듣고 오기
openai api키 발급까지는 블로그 글 생성기 class와 비슷합니다!
아래 링크로 이동해 chapter 3까지만 과정을 이행하고 오세요!
원리는 똑같습니다. 아래 코드는 프롬포트만 바꾼것입니다.
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'I want to make a 1 minute video script. Please write a 50-second script for YouTube shorts with the theme of {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_()
openai api에 요청을 보내는 부분에는
I want to make a 1 minute video script. Please write a 50-second script for YouTube shorts with the theme of @@@.
이렇게 되어있습니다. 여기서 @@@이가 csv에서 끌어오는 주제가 들어갈 부분입니다.
어떤가요? chatgpt는 언어모델이기에 유튜브 보다는 블로그 글 생성해 최적화되어있긴합니다. 그래도 도전해볼만은 하겠죠?
블로그 글 생성을 보고 싶으면?? 아래 클래스로 ㄱㄱ
반응형
댓글