본문 바로가기
study/Bigdata2023

그룹빅데이터교육 1주차 ) ChatGPT 블로그 자동화포스팅 / 챗지피티 답변을 그대로 출력해주는 파이썬 Streamlit 기반 웹페이지 만들기

by 고기만두(개발자) 2023. 3. 12. 20:03
728x90
반응형

7주짜리 2023 그룹 빅데이터 교육을 수강하며, 파이썬 / 머신러닝 관련 강의 내용 아카이빙할 카테고리 새로 만듦.

한동안 재테크 공부 포스팅을 많이 하고 있었는데 생각해보니까 이거 개발블로그로 시작한 거잖아?


0주차. 오티 는 패스.

1주차. 파이썬 기본 되짚기 + 실습

파이썬 환경설정 및 타 계열사 비개발자 현업들이 같이 듣는 교육이다보니, 기본 문법 개념 정리하는 시간이 필요.

파이썬을 접해는 봤지만 주 언어가 아니라 익숙하진 않아서, 도움이 되었음

(주 언어는 아무래도 그래도 자바..)

배운 내용을 바로바로 연습문제 풀면서 테스트해볼 수 있어서 좋았음.

약간 많이 쉬운 코테 보는 느낌도 나고.

 

1. 챗GPT 로 블로그 포스팅 자동화하기

# openai 설치 코드
!pip install openai

import openai

openai.api_key = "API_KEY 지급받은거"

#주제 선정
city = "New York"
topic = f"Top 10 Restaurants you must visit when traveling to {city}"
category = "travel"
print(topic)
#결과: Top 10 Restaurants you must visit when traveling to New York

#세부지시사항 (영어로 작성필요)
# 프롬프트 (내용 수정 가능)
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.
'''
#답변생성
def generate_answer(prompt):
    # 모델 엔진 선택
    model_engine = "text-davinci-003"

    # 맥스 토큰
    max_tokens = 2048

    # ChatGPT 요청 
    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
#챗GPT 테스트
answer = generate_answer('Hi, Who are you?')
print(answer['choices'][0]['text'])
#print answer 내용: My name is John. Nice to meet you!

print(prompt)
#생성된 prompt 내용
#Write blog posts in markdown format.
#Write the theme of your blog as "Top 10 Restaurants you must visit when traveling to New York".
#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.

#결과를 전달 받아 출력합니다.
response = generate_answer(prompt)

# 생성된 글 출력
print(response.choices[0].text)

해당 코드를 실행해서 뉴욕맛집 10개 추천 블로그 포스팅(당연히 영어) 을 뽑아보니 꽤 그럴듯 했다.

뉴욕을 못 가봐서 진짜 맛집인진 모르겠으나.. 쉐이크쉑 하나 알겠다 ㅋㅋㅋㅋㅋㅋㅋㅋ

네이버 2호점 확장공사에 요즘 여념이 없기도 하고 되게 인상깊었다.

사람의 검수가 어느 정도는 필요할 것 같지만, 이걸로 수익화 블로그 시작했다는 주변 사례를 요즘 많이 보기도 했고...

관심이 가는 사례.

티스토리에서 개인 공부를 아카이빙하고, 2호점 네이버에서 일상을 기록하고 있는 내가

당장 양산형 포스팅을 챗GPT에 의뢰 할 생각은 없지만, 그래도 수익증대 측면에서 혹하고 있음...ㅋㅋ

#Top10Restaurants #NYC #FoodLovers
**Are you planning a trip to New York? Are you looking for the best restaurants to visit while you're there? Look no further! Here are the top 10 restaurants you must visit when traveling to New York.**
1. Katz's Delicatessen
- 205 E Houston St, New York, NY 10002
- Menu Recommendation: Pastrami Sandwich
- Opening Hours: Mon-Thurs 8am-10:45pm, Fri-Sat 8am-2:45am, Sun 9am-10:45pm
2. Peter Luger Steak House
- 178 Broadway, Brooklyn, NY 11211
- Menu Recommendation: Porterhouse Steak
- Opening Hours: Mon-Thurs 11:45am-9:30pm, Fri-Sat 11:45am-10:30pm, Sun 12pm-9:30pm
3. The Smith
- 956 2nd Ave, New York, NY 10022
- Menu Recommendation: Mac & Cheese
- Opening Hours: Mon-Thurs 11:30am-11pm, Fri 11:30am-12am, Sat 10am-12am, Sun 10am-11pm
4. Shake Shack
- Multiple Locations
- Menu Recommendation: Shack Burger
- Opening Hours: Mon-Sun 11am-11pm
5. The Spotted Pig
- 314 W 11th St, New York, NY 10014
- Menu Recommendation: Roquefort Burger
- Opening Hours: Mon-Thurs 11:30am-2am, Fri-Sat 11:30am-4am, Sun 11:30am-2am
6. Momofuku Noodle Bar
- 171 1st Ave, New York, NY 10003
- Menu Recommendation: Pork Buns
- Opening Hours: Mon-Thurs 11:30am-10:30pm, Fri-Sat 11:30am-11pm, Sun 11:30am-10pm
7. Di Fara Pizza - 1424 Avenue J, Brooklyn, NY 11230
- Menu Recommendation: Classic Pizza
- Opening Hours: Mon-Thurs 12pm-9pm, Fri-Sat 12pm-10pm, Sun 12pm-9pm
8. Balthazar - 80 Spring St, New York, NY 10012
- Menu Recommendation: Steak Frites
- Opening Hours: Mon-Fri 7am-11:30pm, Sat-Sun 8am-11:30pm
9. Carbone - 181 Thompson St, New York, NY 10012
- Menu Recommendation: Veal Parmesan
- Opening Hours: Mon-Thurs 5:30pm-11:30pm, Fri 5:30pm-12am, Sat 5pm-12am, Sun 5pm-11:30pm
10. The Dutch - 131 Sullivan St, New York, NY 10012
- Menu Recommendation: Fried Chicken
- Opening Hours: Mon-Thurs 5:30pm-11pm, Fri 5:30pm-12am, Sat 11:30am-12am, Sun 11:30am-11pm
These are the top 10 restaurants you must visit when traveling to New York. From classic delis to upscale steakhouses, there is something for everyone. Whether you're looking for a quick bite or a full-on dining experience, these restaurants will not disappoint. So, what are you waiting for? Get out there and explore the best of New York's culinary scene!
#NYCFood #NYCRestaurants #FoodLovers

2. Streamlit을 활용하여 웹페이지 휘딱 만들기 & 챗GPT 답변 바로 출력하기

import streamlit as st
import openai


openai.api_key = "지급받은 API KEY"

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

    # 맥스 토큰
    max_tokens = 2048

    # ChatGPT 요청 
    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

st.title('챗쥐피티')
f = st.file_uploader('파일 업로드')

prompt = st.text_input('프롬프트')
if prompt:
    response = generate_answer(prompt)
    # 생성된 글 출력
    st.write(response.choices[0].text)
반응형

streamlit

streamlit 프레임워크 도입 하나로 , 순식간에 로컬서버에 그럴듯한 깔끔한 웹페이지가 하나 뚝딱 배포되었다.

백엔드 프론트엔드 서버 이런거 하나도 신경쓸 필요 없이 정말 5분 걸렸다. 나 이러다 일자리 잃는거 아니람..

streamlit 소개 및 사용방법은 유튜브 영상 참고

https://www.youtube.com/watch?v=Gr5Vuo7TCaE 

프롬프트에 답변을 쳤더니 바로 답변이 출력되었다.

728x90
반응형

댓글