ChatGPT 시작하기

나 안해·2023년 2월 28일
0

ChatGPT

목록 보기
1/1

1. 준비(API키)

  • OpenAI에서 회원가입 후 진행
  • API키 가져오기
    - API키 생성

2. 코드 작성

2.1 openAI 설치

터미널에서 아래 명령어 입력으로 설치

pip install openai

2.2 API 호출

import pandas as pd
import openai
openai.organization = "Organization 키를 입력"
openai.api_key = "발급받은 API 키를 입력."
  • Organization 키 확인

2.2.1 코드 설명

def get_openai_response(prompt, print_output=False):

    completions = openai.Completion.create(
        engine='text-davinci-003',  # Determines the quality, speed, and cost.
        temperature=0.5,            # Level of creativity in the response
        prompt=prompt,           # What the user typed in
        max_tokens=3072,             # Maximum tokens in the prompt AND response
        n=1,                        # The number of completions to generate
        stop=None,                  # An optional setting to control response generation
    )
    # Displaying the output can be helpful if things go wrong
    if print_output:
        print(completions)

    # Return the first choice's text
    return completions.choices[0].text
코드기능
get_openai_responseChatGPT API의 응답을 반환하는 함수
prompt를 request로 요청completions에 JSON 형태의 response가 API를 통해 반환
return completions.choices[0].textcompletions에서 사용자가 원하는 GPT 언어모델의 응답을 추출해서 반환
def split_script_1000(script):
    split_script = script.split('. ')
#    split_script = script.splitlines()
    result = []
    counter = 0
    tmp = ''
    for i in split_script:
        tmp += i
        counter += len(i)
        
        if counter > 1000:
            result.append(tmp)
            tmp = ''
            counter = 0
    return result
코드기능
split_script_1000 함수입력된 str 형태의 스크립트를 ". " 기준으로 분할해서 result에는 ". "로 분할된 스크립트의 리스트가 반환

그냥 "."이 아닌 ". "로 분할하는 이유는 실수(1.1, 2.2, 3.3... etc)는 포함시키지 않기 위해


2.3 Main

# Let's get data
df = pd.read_csv('script.csv')

# Let's make prompt
prompt = 'Rewrite this script professionally and add subheadings No Titles No Introduction No Conclusion.'

# Algo to rewrite script
result_list = []

for ind, row in df.iterrows():
    eng_result = ''
    title = row['TITLE']
    script = row['SCRIPT'].strip('\n')
    split_script = split_script_1000(script)

    for ss in split_script:
        request = prompt + ss
        response = get_openai_response(request)
        eng_result += response

    result_list.append({'title': title, 'eng': eng_result})

df_result = pd.DataFrame(result_list)

df_result.to_csv('rewrited_script.csv', mode='a', index=False, encoding='utf-8-sig')
  • prompt는 "각각의 문단에 소제목을 달고 제목, 개요 및 결론을 내지 말고 이 글을 다시 써주세요."라는 요청에 1000자 단위로 분할된 스크립트를 추가해서 API를 호출한다.

  • script.csv의 형태는 다음과 같다.
    - 엑셀로 열어보면 TITLE 칼럼과 SCRIPT칼럼을 가진 일반적인 데이터 프레임이다.
    - TITLE에는 문서의 이름 SCRIPT에는 문서 내용을 써넣으면 된다.
    결과는 rewrited_script.csv에 저장된다.

    prompt를 수정하여 API 결과에 따른 다양한 서비스를 만들 수 있다.


참고

0개의 댓글