반응형
www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio
Python Extension Packages for Windows - Christoph Gohlke
by Christoph Gohlke, Laboratory for Fluorescence Dynamics, University of California, Irvine. Updated on 11 October 2020 at 06:09 UTC. This page provides 32- and 64-bit Windows binaries of many scientific open-source extension packages for the official CPyt
www.lfd.uci.edu
현재진행상황 :
1. stt 로 정해진 글자수(50자) 제한으로 setence 출력되고
행태소 분석 -> 단어리스트 출력
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Google Cloud Speech API sample application using the streaming API.
NOTE: This module requires the additional dependency `pyaudio`. To install
using pip:
pip install pyaudio
Example usage:
python transcribe_streaming_mic.py
"""
# [START speech_transcribe_streaming_mic]
from __future__ import division
import re
import sys
#from google.cloud import speech
#from google.cloud.speech import enums
#from google.cloud.speech import types
from google.cloud import speech_v1 as speech
#from google.cloud.speech_v1 import enums
from google.cloud.speech_v1 import types
import pyaudio
from six.moves import queue
# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10) # 100ms
#------------Tongue teeth--------------------
from konlpy.tag import Hannanum
hannanum = Hannanum()
hannanum.pos
#-------------------------KO------------------------# if chunk == none -> break
#WordInfo word
import time
def get_current_time():
"""Return Current Time in MS."""
return int(round(time.time())%1000) # 372
#print('\nNow time : %d\n'%get_current_time()) #1602095050 vs 1602094617790
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
# Create start_time from KO
self.start_time = get_current_time()
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 (get_current_time()-self.start_time)%15 == 0:
#print('\nsuccess\n')
#self._buff.put(None)
#print('\ncurrnet_time : %d\n'%get_current_time())
#print('\nstart_time : %d\n'%self.start_time)
if chunk is None: # when only Ctrl + C
print('\n-----Out chunk is None----\n')
return
data = [chunk]
# Now consume whatever other data's still buffered.
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
print('\n---while chunk is none----\n')
#break
return
data.append(chunk)
#print('---generating..---\n') # start & after final
except queue.Empty:
#print('\nQueue Empty\n') #print many many times
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(=='\n') 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.
"""
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.
if len(result.alternatives[0].transcript) > 30 :
print('\nGrater than 30letters\n')
print('\nsentence :%s'%result.alternatives[0].transcript)
print(hannanum.remove_j(result.alternatives[0].transcript))
break;
else:
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))
#print('\noverwrite_chars : %s\nendOfOverWrite\n'%overwrite_chars) #empty space
if not result.is_final:
#print('\ning\n')
sys.stdout.write(transcript + overwrite_chars +'\r') # before final
if len(transcript) > 30:
sys.stdout.write('\nIF Grater than 30letters\n')
sys.stdout.write('\nsentence :%s'%transcript)
sys,stdout.write(hannanum.remove_j(transcript))
break;
else:
#print(transcript + overwrite_chars + 'ko') # after final
print('\n' , 'final!!')
print('transcript : %s\n end of transcript\n'%transcript)
print(hannanum.remove_j(u'%s'%transcript))
# Exit recognition if any of the transcribed phrases could be
# one of our keywords.
if re.search(r'\b(exit|quit)\b', transcript, re.I):
print('\nEnter the re.search\n')
print('Exiting..')
break
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 = types.RecognitionConfig(
#encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
encoding=types.RecognitionConfig.AudioEncoding.LINEAR16,
sample_rate_hertz=RATE,
language_code=language_code)
streaming_config = types.StreamingRecognitionConfig(
config=config,
interim_results=True)
with MicrophoneStream(RATE, CHUNK) as stream:
audio_generator = stream.generator()
requests = (types.StreamingRecognizeRequest(audio_content=content)
for content in audio_generator)
responses = client.streaming_recognize(streaming_config, requests)
# Now, put the transcription responses to use.
print('enter the loop!\n')
listen_print_loop(responses)
if __name__ == '__main__':
main()
# [END speech_transcribe_streaming_mic]
반응형
'연구 > 경환 - 서기' 카테고리의 다른 글
[20/10/22]nanos해결로 인한 시간무제한 & return 찾기 (0) | 2020.10.22 |
---|---|
[20/10/05]구글STT_API: A-Z(feat. python 3.8.3) (0) | 2020.10.06 |
[200929] STT -> 형태소분석 (0) | 2020.09.29 |
TensorFlow정리 (0) | 2020.07.26 |
[200724]Google Cloud Platform_API에서 제공하는 STT기능 구현 및 STT기능을 수행하는 실행파일 만들기 by Python & Pyinstaller (0) | 2020.07.24 |