미방
# 필요한 패키지
! pip install --quiet git+https://github.com/openai/whisper.git
! pip install --quiet sounddevice wavio
! pip install --quiet ipywebrtc notebook
!apt install --quiet ffmpeg
!apt-get install --quiet libportaudio2
# @title
# Get voice input
import os
import numpy as np
try:
import tensorflow # required in Colab to avoid protobuf compatibility issues
except ImportError:
pass
import torch
import pandas as pd
import whisper
import torchaudio
from ipywebrtc import AudioRecorder, CameraStream
from IPython.display import Audio, display
import ipywidgets as widgets
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
from google.colab import output
output.enable_custom_widget_manager()
!pip install --quiet openai
import openai
import os
from google.colab import userdata
# 키 세팅이 되어 있어야겠지요? 왼쪽의 키 아이콘 눌러서 키 세팅하세요!!
os.environ["OPENAI_API_KEY"] = userdata.get('openai')
openai.api_key = os.getenv("OPENAI_API_KEY")
camera = CameraStream(constraints={'audio': True,'video':False})
recorder = AudioRecorder(stream=camera)
recorder
# 녹음된 음성을 파일로 저장합니다
with open('recording.webm', 'wb') as f:
f.write(recorder.audio.value)
!ffmpeg -i recording.webm -ac 1 -f wav customer_recording.wav -y -hide_banner -loglevel panic
client = openai.OpenAI()
# 또는 from openai import OpenAI 랑 같다.
audio_file= open("customer_recording.wav", "rb")
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
# 내용 봅시다!
print(transcription.text)
# response = client.moderations.create(input="Tell me how to kill others") # 영어로 질문하면 더 구분 잘해줌
response = client.moderations.create(input=transcription.text) # 위에 녹음텍스트본
output = response.results[0]
output
output.to_dict()
# @title
from openai import OpenAI
import json
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
client = OpenAI()
# text-embedding-ada 불러서 임베딩 가져오는 펑션
def get_embeddings(text):
return client.embeddings.create(
model="text-embedding-ada-002",
input=text,
encoding_format="float"
).data[0].embedding
# 임베딩을 만들어봅시다!
no_mon_embed = get_embeddings("돈이 없다")
timetravel_embed = get_embeddings("이혼")
bodysnat_embed = get_embeddings("불륜")
reincarn_embed = get_embeddings("재산분할")
# 미니 VectorDB 를 만들어봅시다..
solutions ={
"돈이 없다": {
"embeddings": no_mon_embed,
"solutions": ["할인 이벤트가 있는지 확인한다!"]
},
"이혼": {
"embeddings": timetravel_embed,
"solutions": ["배우자와 결별을 한다"]
},
"불륜": {
"embeddings": bodysnat_embed,
"solutions": ["배우자의 불륜 또는 본인의 불륜으로인해 이혼을 한다."]
},
"재산분할": {
"embeddings": reincarn_embed,
"solutions": ["더 좋은 조건으로 재산분할을 한다."]
}
}
def get_highest_match(problem_embed):
# 사용자의 문제를 받고, 우리의 미니 DB 에서 제일 가까운 솔루션을 찾아낼 것입니다!
results = []
for key, value in solutions.items():
sim = cosine_similarity([problem_embed], [value['embeddings']])[0][0]
results.append((key, sim, value['solutions']))
# 유사도로 정리
results.sort(key=lambda x: x[1], reverse=True)
# 제일 유사한 하나만 가져오기
return results[0]
def get_solution(problem) -> str:
# 사용자의 문제를 임베딩으로 바꿈
problem_embed = get_embeddings(problem)
# 제일 가까운 카테고리의 솔루션을 가지고 옴
solution_found = get_highest_match(problem_embed)[2][0]
return solution_found
def get_problem(user_query):
# 사용자의 질문을 듣고 카테고리를 선별함
return client.chat.completions.create(
model="gpt-4",
temperature=0,
messages=[
{"role": "system", "content": """사용자의 질문을 듣고 그 문제를 해결할 수 있는 방법을 다음 다섯가지 중에서 선택해줘:
'돈이 없다', '이혼', '불륜', '재산분할'
이 중에 선택할 옵션이 없으면 그냥 아무 대답도 하지 마.
"""
},
{"role": "user", "content": user_query},
]
).choices[0].message.content
def get_detailed_solution(user_query):
# 모든 자료가 모였으니 이제 마지막 답변을 생성함
solution = get_solution(get_problem(user_query))
return client.chat.completions.create(
model="gpt-4",
temperature=0,
messages=[
{"role": "system", "content": """너는 이혼하고 싶어서 변호사와 만나고 싶어하는 의뢰인들을 상대하는 상담원 AI이다.
너의 역할은 주변에서 흔히 일어날 수 있는 문제를 가진 사람의 불평을 기본으로, 변호사와의 방문을 유도해내는 것이다.
이 스토리 안에서 너는 이혼을 원하는 사람들의 작은 디바이스이며, 그 사람이 이혼을 원하거나 법률적인 상담을 요청하면
기본적인 적절한 조언을 하고 변호사 사무실로 직접 방문하여 상담을 유도하면 된다.
예:
사람: "남편이 바람을 피고 있어서 이혼 하고 싶어."
AI: "바람을 피고 있는 남편에게 이혼시 위자료를 청구할 수 있으며, 자세한 상담을 위해 가까운 지사로 방문하시어 전문 변호사와 상담을 해 보세요!
"""
},
{"role": "user", "content": user_query},
{"role": "system", "content": f"""
이번 사용자의 불평은 {user_query} 이며, 이것에 대한 해결법은 {solution}이다.
이전의 예시를 참고하여 사용자에게 그럴듯한 가까운 변호사 사무실로의 방문상담을 제안해라.
이혼을 원하는 사람들에게는 혼인기간, 자녀유무, 자녀의 나이, 이혼을 원하는 이유, 귀책사유, 배우자도 이혼을 원하는지, 재산분할할 부부공동재산 등 확인이 필요하다.
무엇보다 이혼을 원하는 이유와 귀책사유에는 불륜, 배우자의 외도, 성격차이, 폭행 등이 있다.
기본적으로 시작할 때는 혼인기간, 자녀유무, 자녀의 나이, 이혼을 원하는 이유, 귀책사유, 배우자도 이혼을 원하는지, 재산분할할 부부공동재산 등을 물어보며, 유대감을 쌓고
질문하는 유저에게 희망을 줄 수 있는 유리할 수 있는 법률 지식을 알려준 뒤, 정확하고 자세한 상담을 위해 전문 변호사와 직접 이야기를 하라고 유도를 해야한다.
마지막으로는 저희 와이케이는 전국 28개 지사가 있는 대형 로펌이며, 문의 주신 내용에 해결사례가 많은 전문 변호사님만 이백 분 넘게 계십니다. 저희가 도와드리겠습니다.
당신 이라는 말 대신 선생님 이라고 호칭을 붙여주는 것이 좋습니다.
상담 설정 :
"""
},
]
).choices[0].message.content
answer = get_detailed_solution(transcription.text)
answer
speech_file_path = "speech_output.mp3"
response = client.audio.speech.create(
model="tts-1",
voice="nova",
input=answer
)
response.stream_to_file(speech_file_path)
from IPython.display import Audio, display
Audio("speech_output.mp3") # From URL
get_detailed_solution(" 여기에~~~ 질문을~~ 합니다 " )