딥러닝-4단계(transformers, gradio, open ai)

엔지니어 큐브·2023년 9월 10일
0

딥러닝

목록 보기
5/5

1. transformers

  • 해당 웹에 들어가면 다양한 model을 만들어 놓은 사이트로 hugging face가 있다.

  • 어떤 문자를 입력하면 긍정인지 부정인지 알려주는 것과 텍스트를 오디오로 바꿔주는 등등의 다양한 model들이 있다.

  • 우리가 model을 만드는 것도 중요하지만, 이미 만들어진 model을 사용하는 것 또한 중요하다.

  • 해당 라이브러리 설치는 !pip install transformers datasets xformers -q 이다.

  • 파이프라인 task - identifier

      1. classifier = pipeline('pipeline identifier')의 구조이며, 내가 하고자하는 Task에 맞는 pipeline identifier을 입력한다.
      1. 실행하면 기본적인 model을 다운로드 받을 수 있다.


1) 실습-감정

from transformers import pipeline

classifier = pipeline("sentiment-analysis")   # classifier = pipeline('pipeline identifier')의 구조
result = classifier(["We are very happy.", "We hope you don't hate it."])

print(result)
print(classifier("좋아"))

<출력>
[{'label': 'POSITIVE', 'score': 0.9998819828033447}, {'label': 'NEGATIVE', 'score': 0.5308590531349182}

[{'label': 'NEGATIVE', 'score': 0.6970565319061279}]

2) 실습-감정(target 모델 사용)

  • hugging face 사이트에서 원하는 모델이 있는 경우, pipeline('identifier', 'target model')과 같이 입력해주면 된다.
classifier = pipeline("sentiment-analysis", "matthewburke/korean_sentiment")
classifier(['좋아', "별로야"])
<출력>
[{'label': 'LABEL_1', 'score': 0.9337605834007263},
 {'label': 'LABEL_0', 'score': 0.9618430137634277}]

3) 실습-자동완성(target 모델 사용)

generator = pipeline("text-generation", "skt/kogpt2-base-v2")
result = generator('오랜만에 집에 돌아왔더니, 아버지가 식사를 하고 계시는데, ')

print(result[0]['generated_text'])
<출력>
오랜만에 집에 돌아왔더니, 아버지가 식사를 하고 계시는데, 텃밭으로 가셔서 한바탕 소동을 벌였습니다.
이윽고 저녁을 먹고, 점심은 각자 거동으로 했습니다.
어깨가 몹시 아파서 식사 때 눕기도 힘들어서 아무

4) 실습-사운드를 텍스트로

from datasets import load_dataset

recognizer = pipeline("automatic-speech-recognition")
dataset = load_dataset("PolyAI/minds14", name="en-US", split="train")

print(dataset[0])

# load_dataset을 사용해야 하는 것과 입력 값에 어떤 것을 넣어야 되는지는 hugging 사이트에 나와있다.


2. gradio

  • 딥러닝 엔지니어가 앱을 쉽게 만들 수 있도록 도와주는 프레임워크이다.

  • 간략하게 말하면, hugging이나 직접 만든 model을 시현할 수 있게 구동해주는 기능을 갖고 있다.

  • 해당 라이브러리 설치는 !pip install gradio -q 이다.

1)-실습

import gradio as gr

def greet(name):
    print(name)
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

demo.launch(share=True, debug=True)    #share -> 외부 url 생성 됨 // debug=True 하면 계속해서 실행되면서 피드백을 받을 수 있음
  • 위와 같은 기본적인 형태를 지닌다.
  • fn = model을 넣어주면되고 input값과 output은 커스텀화 할 수 있다.

2)-실습

import gradio as gr

def greet(name):

    generator = pipeline("text-generation", "skt/kogpt2-base-v2")

    result = generator(name)
    return(result[0]['generated_text'])

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

demo.launch()

3)-실습

import gradio as gr

def chat(msg, history):
    history.append((msg, "안녕. 반가워"))
    return "", history

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    send = gr.Button('send')
    clear = gr.ClearButton([msg, chatbot])

    send.click(chat, [msg, chatbot], [msg, chatbot])            # send.이벤트(동작)

demo.launch(share=True)

1-좀 더 복잡한 실습 예시

import gradio as gr
import random

def chat(message, chat_history):
        bot_message = greet(message)
        chat_history.append((message, bot_message))
        return "", chat_history

def greet(message):

    generator = pipeline("text-generation", max_length=100, model="EasthShin/Youth_Chatbot_Kogpt2-base")

    result = generator(message)
    return(result[0]['generated_text'])

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    clear = gr.ClearButton([msg, chatbot])

    msg.submit(chat, [msg, chatbot], [msg, chatbot])

demo.launch()

2-좀 더 복잡한 실습 예시

import gradio as gr

def greet(name, is_morning, temperature):
    salutation = "Good morning" if is_morning else "Good evening"
    greeting = f"{salutation} {name}. It is {temperature} degrees today"
    celsius = (temperature - 32) * 5 / 9
    return greeting, round(celsius, 2)

demo = gr.Interface(
    fn=greet,
    inputs=["text", "checkbox", gr.Slider(0, 100)],
    outputs=["text", "number"],
)
if __name__ == "__main__":
    demo.launch()

3. open-ai

  • open-ai는 만들어진 model을 사용할 수 있는 사이트이다.
  • hugging과 다른 점은 api_key를 입력해야 한다. 왜냐하면 chat-gpt를 사용할 수 있기 때문에 약간의 돈을 지불해야하고 더 좋은 성능의 model을 사용한다.

1) 실습

import os
import openai

openai.api_key = "--"                    # 사이트 로그인 하면 발급되는 key가 있다.

response = openai.Completion.create(
  model="text-davinci-003",              # 사용하고자 하는 model을 작성
  prompt="옛날 옛적에 한산도 가는 날\n",     
  temperature=1, 
  max_tokens=256,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

print(response.choices[0].text)

2) 실습-gradio 같이 사용

import gradio as gr
import openai

openai.api_key = "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"

def 텍스트생성(prompt):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=f"'{prompt}' 위의 문장을 영어로 번역해줘",
        temperature=0.7,
        max_tokens=1024,
    )
    return prompt + response['choices'][0]['text'].strip()

demo = gr.Interface(fn=텍스트생성, inputs="text", outputs="text")
demo.launch(share=True)

3) 실습-gradio 같이 사용2 + prompt 역할 지정

  • 1
import os
import openai

openai.api_key = "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"

response = openai.ChatCompletion.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "넌 이제부터 나의 오랜 친구야"},
    {"role": "user", "content": "안녕 친구"},
  ],
  temperature=1,
  max_tokens=256,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)
print(response.choices[0].message['content'])
  • 2
import gradio as gr

def chat(msg, history):
    history.append((msg, "안녕. 반가워"))
    return "", history

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    send = gr.Button('send')
    clear = gr.ClearButton([msg, chatbot])

    send.click(chat, [msg, chatbot], [msg, chatbot])            # send.이벤트(동작)

demo.launch(share=True)

  • 1+2
prompt = """You are OrderBot, an automated service to collect orders for a pizza restaurant.
You first greet the customer, then collects the order, and then asks if it's a pickup or delivery.
You wait to collect the entire order, then summarize it and check for a final time if the customer wants to add anything else.
If it's a delivery, you ask for an address. Finally you collect the payment.
Make sure to clarify all options, extras and sizes to uniquely identify the item from the menu.
You respond in a short, very conversational friendly style.
The menu includes
 pepperoni pizza 12.95, 10.00, 7.00
 cheese pizza 10.95, 9.25, 6.50
 eggplant pizza 11.95, 9.75, 6.75
 fries 4.50, 3.50
 greek salad 7.25
Toppings:
 extra cheese 2.00,
 mushrooms 1.50
 sausage 3.00
 canadian bacon 3.50
 AI sauce 1.50
 peppers 1.00
Drinks:
 coke 3.00, 2.00, 1.00
 sprite 3.00, 2.00, 1.00
 bottled water 5.00
"""

import gradio as gr

import os
import openai

openai.api_key = "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"

messages = []

def chat(msg, history):
    messages.append({"role": "user", "content": msg})
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "system", "content": prompt}, *messages[-10:]],
        temperature=1,
        max_tokens=256
    )
    messages.append({"role": "assistant", "content": response.choices[0].message['content']})
    print(messages)

    history.append((msg, response.choices[0].message['content']))
    return "", history

with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox()
    send = gr.Button("Send")
    clear = gr.ClearButton([msg, chatbot])

    msg.submit(chat, [msg, chatbot], [msg, chatbot])
    send.click(chat, [msg, chatbot], [msg, chatbot])

demo.launch(share=True)
profile
큐브가 필요하다...!!!

0개의 댓글