Не могу решить получить стенограмму снова для использования города - PullRequest
0 голосов
/ 21 декабря 2018

Я хочу создать программу, которая будет принимать слова высказывания в предложении и запускать этот метод.Поэтому, если я говорю «погода», запускается метод «Погода», а затем он должен снова принимать высказывание, а когда я говорю «название города», он должен искать названия городов из файла JSON и находить его в расшифровке (то есть «Выражение»), а затем получатьпогода по городу.Он ответил речью в ответе о том, какая погода должна идти на круги своя (например, снова принимать высказывания).Когда я говорю «Отель», он должен использовать гостиничный метод, в том числе и по городам.В файле JSON есть 3 города, и есть файл отдельных городов их соответствующих ресторанов или отелей.

Проблема в том, что когда я говорю «Предложение», он вызывает метод, но когда я говорю это снова, он снова запускается при первоначальном триггере.,Но я этого не хочу.

Мой код # [START speech_transcribe_streaming_mic] из future import import

import re
import sys

from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types
import pyaudio
from six.moves import queue
import pyowm
import json
from gtts import gTTS
import os
from threading import Thread

# Audio recording parameters
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms

# OWM API KEY
owm = pyowm.OWM('#')
with open('city.json') as f, open('delhi_rest.json') as d, open('surat_rest.json') as s, open('pune_rest.json') as p:
    data = json.load(f)
    data1 = json.load(d)
    data2 = json.load(s)
    data3 = json.load(p)

language = 'en'


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

            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):
    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(exit|quit)\b', transcript, re.I):
                print('Exiting..')
                break

            num_chars_printed = 0
##        return transcript
def users ():
##        responses = main()
##        transcript = listen_print_loop(responses)
        print("hey: " + transcript)
##        listen_print_loop(responses)
        hotel = re.search(r'\b(Hotel)\b', transcript, re.I)
        # print(hotel)
        hotel1 = bin(bool(hotel))[2]
##            print((bin(bool(hotel))))
        weather = re.search(r'\b(weather)\b', transcript, re.I)
        # print(weather)
        weather1 = bin(bool(weather))[2]
##            print((bin(bool(weather))))
        food = re.search(r'\b(Dinner|Restaurants|Lunch|Food)\b', transcript, re.I)
        # print(food)

        food1 = bin(bool(food))[2]
##            print((bin(bool(food))))
        dat = [hotel1, weather1, food1]
        print(dat)

        def act_foo():
            for ht in data1:
                gf = ht.get('name')
                print(gf)

        def act_wea():
            print("Which City?")
            for items in data:
                my1 = items.get('name') 
##                listen_print_loop(responses)
    ##            if re.search(r'\b(Surat|pune|delhi)\b', transcript, re.I):
                if my1 in transcript:
                    my2 = items.get('id')
                    observation = owm.weather_at_id(my2)
                    w = observation.get_weather()
                    status = w.get_detailed_status()
                    print("Weather status is " + status)
                    mytext = "Weather status is " + status
                    myobj = gTTS(text=mytext, lang=language, slow=False)
                    myobj.save("welcome.mp3")
                    os.system("mpg321 welcome.mp3")
                    break

        def act_hot():
            print("Hotels")
            print("abcd")
        dict = {
            "['1', '0', '0']": act_hot,
            "['0', '1', '0']": act_wea,
            "['0', '0', '1']": act_foo
        }
        print("abcdef")
        if str(dat) in dict:
            x = dict.get(str(dat))
            x()

def main():

    language_code = 'en-US'  # a BCP-47 language tag

    client = speech.SpeechClient()
    config = types.RecognitionConfig(
        encoding=enums.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.
        listen_print_loop(responses)

if __name__ == '__main__':
    Thread1 = Thread(target=main())
    Thread2 = Thread(target= users())
    Thread1.start()
    Thread2.start()

# [END speech_transcribe_streaming_mic]

Пожалуйста, дайте решение вболее простой способ.Заранее спасибо.

...