Created
July 7, 2021 14:51
-
-
Save ProjectEli/b7b85a58be00062e3a0bfe7d5fdc7cc8 to your computer and use it in GitHub Desktop.
알파카 - GPT-3를 사용한 음성인식
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import openai | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
# https://cloud.google.com/translate/docs/basic/quickstart?hl=ko | |
def translate_text(target, text): | |
"""Translates text into the target language. | |
Target must be an ISO 639-1 language code. | |
See https://g.co/cloud/translate/v2/translate-reference#supported_languages | |
""" | |
import six | |
from google.cloud import translate_v2 as translate | |
translate_client = translate.Client() | |
if isinstance(text, six.binary_type): | |
text = text.decode("utf-8") | |
# Text can also be a sequence of strings, in which case this method | |
# will return a sequence of results for each text. | |
result = translate_client.translate(text, target_language=target) | |
# print(u"Text: {}".format(result["input"])) | |
# print(u"{}".format(result["translatedText"])) | |
# print(u"Detected source language: {}".format(result["detectedSourceLanguage"])) | |
return u"{}".format(result["translatedText"]) | |
def openAI_process(text): | |
response = openai.Completion.create( | |
engine="davinci", | |
prompt="Q: "+text+"\nA:", | |
temperature=0.5, | |
max_tokens=100, | |
top_p=1, | |
frequency_penalty=0.2, | |
presence_penalty=0, | |
stop=["\n"] | |
) | |
response_text = response["choices"][0]["text"] | |
# print(response_text) | |
translated_text = translate_text('ko',response_text) | |
print(u"알파카의 응답: {}".format(translated_text)) | |
return "{}".format(translated_text) | |
import re | |
import sys | |
from google.cloud import speech | |
import pyaudio | |
from six.moves import queue | |
# Audio recording parameters | |
RATE = 16000 | |
CHUNK = int(RATE / 10) # 100ms | |
class MicrophoneStream(object): | |
"""Opens a recording stream as a generator yielding the audio chunks.""" | |
def __init__(self, rate, chunk): | |
self._rate = rate | |
self._chunk = chunk | |
# Create a thread-safe buffer of audio data | |
self._buff = queue.Queue() | |
self.closed = True | |
def __enter__(self): | |
self._audio_interface = pyaudio.PyAudio() | |
self._audio_stream = self._audio_interface.open( | |
format=pyaudio.paInt16, | |
# The API currently only supports 1-channel (mono) audio | |
# https://goo.gl/z757pE | |
channels=1, | |
rate=self._rate, | |
input=True, | |
frames_per_buffer=self._chunk, | |
# Run the audio stream asynchronously to fill the buffer object. | |
# This is necessary so that the input device's buffer doesn't | |
# overflow while the calling thread makes network requests, etc. | |
stream_callback=self._fill_buffer, | |
) | |
self.closed = False | |
return self | |
def __exit__(self, type, value, traceback): | |
self._audio_stream.stop_stream() | |
self._audio_stream.close() | |
self.closed = True | |
# Signal the generator to terminate so that the client's | |
# streaming_recognize method will not block the process termination. | |
self._buff.put(None) | |
self._audio_interface.terminate() | |
def _fill_buffer(self, in_data, frame_count, time_info, status_flags): | |
"""Continuously collect data from the audio stream, into the buffer.""" | |
self._buff.put(in_data) | |
return None, pyaudio.paContinue | |
def generator(self): | |
while not self.closed: | |
# Use a blocking get() to ensure there's at least one chunk of | |
# data, and stop iteration if the chunk is None, indicating the | |
# end of the audio stream. | |
chunk = self._buff.get() | |
if chunk is None: | |
return | |
data = [chunk] | |
# Now consume whatever other data's still buffered. | |
while True: | |
try: | |
chunk = self._buff.get(block=False) | |
if chunk is None: | |
return | |
data.append(chunk) | |
except queue.Empty: | |
break | |
yield b"".join(data) | |
def listen_print_loop(responses): | |
"""Iterates through server responses and prints them. | |
The responses passed is a generator that will block until a response | |
is provided by the server. | |
Each response may contain multiple results, and each result may contain | |
multiple alternatives; for details, see https://goo.gl/tjCPAU. Here we | |
print only the transcription for the top alternative of the top result. | |
In this case, responses are provided for interim results as well. If the | |
response is an interim one, print a line feed at the end of it, to allow | |
the next result to overwrite it, until the response is a final one. For the | |
final one, print a newline to preserve the finalized transcription. | |
""" | |
cumulated_transcript = '' | |
num_chars_printed = 0 | |
for response in responses: | |
if not response.results: | |
continue | |
# The `results` list is consecutive. For streaming, we only care about | |
# the first result being considered, since once it's `is_final`, it | |
# moves on to considering the next utterance. | |
result = response.results[0] | |
if not result.alternatives: | |
continue | |
# Display the transcription of the top alternative. | |
transcript = result.alternatives[0].transcript | |
# Display interim results, but with a carriage return at the end of the | |
# line, so subsequent lines will overwrite them. | |
# | |
# If the previous result was longer than this one, we need to print | |
# some extra spaces to overwrite the previous result | |
overwrite_chars = " " * (num_chars_printed - len(transcript)) | |
if not result.is_final: | |
sys.stdout.write(transcript + overwrite_chars + "\r") | |
sys.stdout.flush() | |
num_chars_printed = len(transcript) | |
else: | |
print(transcript + overwrite_chars) | |
# Exit recognition if any of the transcribed phrases could be | |
# one of our keywords. | |
if re.search(r"\b(끝내자|그만하자)\b", transcript, re.I): | |
print("알파카: 알파카를 종료합니다.") | |
break | |
elif re.search(r"\b(알파카)\b", transcript, re.I): | |
print("알파카: 네, 부르셨나요?") | |
elif re.search(r"\b(고마워)\b", transcript, re.I): | |
print("알파카: 천만에요.") | |
else: | |
# https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes | |
translated_text = translate_text('en',transcript) | |
cumulated_transcript = cumulated_transcript + "\nQ: " + translated_text | |
response_text = openAI_process(translated_text) | |
cumulated_transcript = cumulated_transcript + "\nA: " + response_text | |
num_chars_printed = 0 | |
def main(): | |
# See http://g.co/cloud/speech/docs/languages | |
# for a list of supported languages. | |
language_code = "ko-KR" # a BCP-47 language tag | |
client = speech.SpeechClient() | |
config = speech.RecognitionConfig( | |
encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16, | |
sample_rate_hertz=RATE, | |
language_code=language_code, | |
) | |
streaming_config = speech.StreamingRecognitionConfig( | |
config=config, interim_results=True | |
) | |
with MicrophoneStream(RATE, CHUNK) as stream: | |
audio_generator = stream.generator() | |
print("음성 인식 시작됨.") | |
requests = ( | |
speech.StreamingRecognizeRequest(audio_content=content) | |
for content in audio_generator | |
) | |
responses = client.streaming_recognize(streaming_config, requests) | |
# Now, put the transcription responses to use. | |
listen_print_loop(responses) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment