python类UnknownValueError()的实例源码

testme.py 文件源码 项目:xarvis 作者: satwikkansal 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def callback(recognizer, audio):
    # received audio data, now we'll recognize it using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
brain.py 文件源码 项目:Jarvis 作者: m4n3dw0lf 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def Listen(self):
        with sr.Microphone() as source:
            self.audio = self.rec.listen(source)
        try:
            self.result = self.rec.recognize_google(self.audio)
            print self.result
            return self.result
        except sr.UnknownValueError:
                    print("Google Speech Recognition could not understand audio")
            except sr.RequestError:
                    self.Say("Could not request results from Google Speech Recognition service master, check our internet connection.")
persia.py 文件源码 项目:Persia 作者: rjcf18 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def initiate_Persia(self):
        """
        Initializes Persia and starts the listening loop
        """

        # starts the recognizer
        r = sr.Recognizer()

        with sr.Microphone() as source:

            while True:
                logger.debug("Awaiting user input.")
                audio = r.listen(source)

                logger.debug("Interpreting user input.")

                # Speech recognition using Google Speech Recognition
                try:
                    result = r.recognize_google(audio)
                    #result = r.recognize_sphinx(audio)

                    self.handle_action(result)

                except sr.UnknownValueError:
                    logger.debug("Could not understand audio")
                    #Persia.speak("I'm sorry, but I couldn't understand what you said.")
                except sr.RequestError as e:
                    logger.warn("Could not request results from Google Speech Recognition service: %s", e)
                except Exception as e:
                    logger.error("Could not process text: %s", e)
transcribe.py 文件源码 项目:audio-tagging-toolkit 作者: hipstas 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def transcribe(inputfile,outputfile='',to_txt=True):
    wav_source=True
    if inputfile.lower()[-4:]!='.wav':     # Creates a temporary WAV
        wav_source=False                         # if input is MP3
        temp_filename=inputfile.split('/')[-1]+'_temp.wav'
        wav_path='/var/tmp/'+temp_filename   # Pathname for temp WAV
        subprocess.call(['ffmpeg', '-y', '-i', inputfile, wav_path]) # '-y' option overwrites existing file if present
    else:
        wav_path=inputfile
    transcript=''
    r = sr.Recognizer()
    with sr.AudioFile(wav_path) as source:
        audio = r.record(source)    # read the entire audio file
    try:                            # recognize speech using Sphinx
        print('Processing ...')
        transcript=r.recognize_sphinx(audio)
    except sr.UnknownValueError:
        print("Sphinx error: No speech detected.")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
    if wav_source==False:
        os.remove(wav_path)       # deleting temp WAV
    if to_txt==True:
        if outputfile=='':
            outputfile=inputfile[:-4]+'.pocketsphinx.txt'
        with open(outputfile, 'w') as fo:
            fo.write(transcript)
        return transcript
    else:
        return transcript
speech_recognition_90.py 文件源码 项目:xiaokai-bot 作者: CCZU-DEV 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _recognize_bing(wav_path, api_key, language='zh-CN'):
    r = sr.Recognizer()
    with sr.AudioFile(wav_path) as source:
        audio = r.record(source)
    try:
        text = r.recognize_bing(audio, key=api_key, language=language)
        return text
    except (sr.UnknownValueError, sr.RequestError):
        return None
pandora.py 文件源码 项目:pandora 作者: ryzokuken 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def listen(recognizer, message='Say Something'):
    with speech_recognition.Microphone() as source:
        print(message)
        audio = recognizer.listen(source)
    try:
        return recognizer.recognize_google(audio).lower()
    except speech_recognition.UnknownValueError:
        try:
            return recognizer.recognize_sphinx(audio).lower()
        except speech_recognition.UnknownValueError:
            print("Pandora could not understand audio")
        except speech_recognition.RequestError as e:
            print("Sphinx error; {0}".format(e))
    except speech_recognition.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
main.py 文件源码 项目:SearchAndWatch 作者: aysedilekk 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def sound_to_text():
    NEWS = []
    for i in range(int(length / 8)):

        WAV_FILE = path.join(path.dirname(path.realpath(__file__)), 'nlp_' + str(i) + '.wav')

        # use "english.wav" as the audio source
        r = sr.Recognizer()
        with sr.WavFile(WAV_FILE) as source:
            audio = r.record(source)  # read the entire WAV file
        # recognize speech using Google Speech Recognition
        try:
            # for testing purposes, we're just using the default API key
            # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
            # instead of `r.recognize_google(audio)`
            print(i, ". part: ", r.recognize_google(audio,language="tr"))

            NEWS.append(r.recognize_google(audio,language="tr"))

        except sr.UnknownValueError:
            # print("Google Speech Recognition could not understand audio")
            pass
        except sr.RequestError as e:
            # print("Could not request results from Google Speech Recognition service; {0}".format(e))
            pass

    return NEWS
xrecognize.py 文件源码 项目:CodeLabs 作者: TheIoTLearningInitiative 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def recognize(self):
        if self.engine == 'google':
            try:
                from pprint import pprint
                print("Google Speech Recognition")
                return self.r.recognize_google(self.audio, show_all=False)
            except sr.UnknownValueError:
                print("Google Speech Recognition could not understand audio")
            except sr.RequestError as e:
                print("Could not request results from Google Speech Recognition service; {0}".format(e))
        if self.engine == 'witai':
            WIT_AI_KEY = "7LUFYD6ZZKLYSI652C75J4UZWTIMJIPX"
            try:
                print("Wit.ai")
                return self.r.recognize_wit(self.audio, key=WIT_AI_KEY)
            except sr.UnknownValueError:
                print("Wit.ai could not understand audio")
            except sr.RequestError as e:
                print("Could not request results from Wit.ai service; {0}".format(e))
        if self.engine == 'sphinx':
            try:
                print("Sphinx")
                return self.r.recognize_sphinx(self.audio)
            except sr.UnknownValueError:
                print("Sphinx could not understand audio")
            except sr.RequestError as e:
                print("Sphinx error; {0}".format(e))
        return None
background_listen.py 文件源码 项目:Pyggy 作者: korymath 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def callback(recognizer, audio):
    # received audio data, now we'll recognize it using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        print("Google Speech Recognition thinks you said " + recognizer.recognize_google(audio))
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
jarvis.py 文件源码 项目:awesome-hacking-via-python 作者: shashi12533 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def callback(r,audio):
    try:
        s=r.recognize_google(audio)
        print(s)
        brain(s)
    except sr.UnknownValueError:
        print("~~~~~~~~~~~~~~~~~~~")
    except sr.RequestError as e:
        print('Internet Error......!')
main.py 文件源码 项目:Onyx 作者: OnyxProject 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def detected_callback(self):
        self.detector.terminate()
        play_wav(onyx.__path__[0] + "/client/speech/resources/ding.wav")

        r = sr.Recognizer()

        with sr.Microphone() as source:
            print("Say something!")
            audio = r.listen(source, timeout=1, phrase_time_limit=5)

        try:
            result = stt.execute(audio, language=self.lang)
            print("You said: " + result)

            def create_ws():
                def onConnected(event=None):
                    print ("Sending message...")
                    payload = {
                            'utterances': [result]
                    }
                    ws.emit(Message('recognizer_loop:utterance', payload))
                    t.close()
                    #self.detector.start(self.detected_callback)


                ws = WebsocketClient()
                ws.on('connected', onConnected)
                # This will block until the client gets closed
                ws.run_forever()

            t = threading.Thread(target=create_ws)
            t.start()
            time.sleep(2)
            self.detector.start(self.detected_callback)


        except sr.UnknownValueError:
            print("Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Speech Recognition service; {0}".format(e))
main.py 文件源码 项目:furbymt 作者: starfys 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def get_command():
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)
    # recognize speech using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        tts_result = r.recognize_google(audio)
        print('Got ' + tts_result)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
        return None
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
        return None
    #Read keys from json
    with open('keys.json','r') as keys_file:
        keys = json.load(keys_file)
    apiai_client_token = keys['apiai_client_token']
    #Create a session
    session = requests.Session()
    session.headers.update({"Authorization":"Bearer {}".format(apiai_client_token),
                        "Content-Type":"application/json; charset=utf-8"})
    #API.ai
    API_BASE_URL="https://api.api.ai/v1/"
    #Make a request
    return session.get(API_BASE_URL+"query", params={"query": tts_result,"v":"20170204","sessionId":"furby","lang":"en"}).json()["result"]
ears.py 文件源码 项目:alan 作者: camtaylor 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def ears():
  # obtain audio from the microphone
  r = sr.Recognizer()
  with sr.Microphone() as source:
    audio = r.listen(source)
  # recognize speech using Google Speech Recognition
  try:
    return r.recognize_google(audio)
  except sr.UnknownValueError:
    return ears() 
  except sr.RequestError as e:
    return "I do not understand; {0}".format(e)
audioInput.py 文件源码 项目:Nancy-VA--MacOS 作者: itz-azhar 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def listen():
        speak('Listening!')
        with speech_recognition.Microphone() as source:
            recognizer.adjust_for_ambient_noise(source)
            audio = recognizer.listen(source)
        try:
            return recognizer.recognize_google(audio)
        except speech_recognition.UnknownValueError:
            notify(message="Could not understand audio")
        except speech_recognition.RequestError as e:
            notify(message="Connection Problem")
        return ""
realtimerecognize.py 文件源码 项目:audiolearning 作者: jingwang3235 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def listen_translate():
    while(True):
        # obtain audio from the microphone
        r = sr.Recognizer()
        with sr.Microphone(sample_rate=8000) as source:
            print("Say something!")
    #         print(5),
    #         time.sleep(1)
    #         print(4),
    #         time.sleep(1)
    #         print(3),
    #         time.sleep(1)
    #         print(2),
    #         time.sleep(1)  
    #         print(1),     
    #         time.sleep(1)  
            audio = r.listen(source)#,timeout=5,phrase_time_limit=0.05

    #     r = sr.Recognizer()
    #     with sr.AudioFile('./english.wav') as source:
    #         audio = r.record(source)  # read the entire audio file

        # write audio to a WAV file    ``
with open("microphone-results.wav", "wb") as f:
        f.write(audio.get_wav_data())

    # recognize speech using Sphinx
    try:
        print("Sphinx thinks you said :" + r.recognize_sphinx(audio))
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))

```

realtimerecognize.py 文件源码 项目:audiolearning 作者: jingwang3235 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def translate(r,audio):    
    try:
        s=time.time()
        print(str(len(audiolist))+" Sphinx thinks you said :" + r.recognize_sphinx(audio))
        print time.time()-s
    except sr.UnknownValueError:
        print("Sphinx could not understand audio")
    except sr.RequestError as e:
        print("Sphinx error; {0}".format(e))
realtimerecognize.py 文件源码 项目:audiolearning 作者: jingwang3235 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def play_audio():

        r = sr.Recognizer()        

        with sr.AudioFile('./english.wav') as source:
            audio = r.record(source)  # read the entire audio file    
            print audio  

        # recognize speech using Sphinx
        try:
            print("Sphinx thinks you said :" + r.recognize_sphinx(audio))
        except sr.UnknownValueError:
            print("Sphinx could not understand audio")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))
properties.py 文件源码 项目:Lab-Assistant 作者: SPARC-Auburn 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def processcommand(self, usermsg, source):
        """
        Processes command from user and deals with wake word detection
        Returns True if Response was when assistant is awoken
        :param usermsg: The message that the user inputted
        :param source: Microphone audio source
        """
        print ("< " + usermsg)
        wake_words = ["hey", "ok", "okay", "yo", "you", "hi"]
        awake = False
        for word in wake_words:
            if self.userCommand == word + " " + self.name:
                awake = True
        if awake:
            self.playsound("start.mp3")
            self.speak("Yes?")
            print ("\tWaiting for command..")
            response_heard = False
            while not response_heard:
                print ("\tThreshold: " + str(self.r.energy_threshold))
                print ("\tWaiting for command...")
                try:
                    audio = self.r.listen(source, timeout=5)
                    print("...")
                    self.playsound("end.mp3")
                    try:
                        self.userCommand = self.r.recognize_google(audio)
                        self.userCommand = self.userCommand.lower()
                        response_heard = True
                        print ("< " + self.userCommand)
                    except sr.UnknownValueError:
                        print("\tUnknown Value from Google, or nothing heard")
                    except sr.RequestError as e:
                        print("\tCould not request results from Google Speech Recognition service; {0}".format(e))
                    except Exception as e:
                        print (str(e))
                except Exception:
                    print ("\tHeard nothing")
                    pass
            return True
        else:
            for word in wake_words:
                if self.userCommand.__contains__(word + " " + self.name):
                    print ("\tGetting command..")
                    self.userCommand = self.userCommand.split(word + " " + self.name + " ")[1]
                    return True
            return False
asus.py 文件源码 项目:Face-Recognition-for-Mobile-Robot 作者: gagolucasm 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def callback(self,data):
        i=0
    rg=spr.Recognizer()
        try:
            frame = self.bridge.imgmsg_to_cv2(data, "bgr8")
            frame = libs.resize(frame, width=600)
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            (rects, i, facess) = et.track(gray, i)
            for rect in rects:
                cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (0, 255, 0), 2)
            if facess != []:
                for face in facess:
                    pred, conf = recognizer.predict(face)
                    if conf < 120:
                        print "Reconozco a Lucas con una confianza de {}".format(conf)
            self.num=self.num+1
            if self.num==10:
                            self.engine.say('Hi ')
                self.engine.say( list(dictid.keys())[list(dictid.values()).index(pred)])
                self.engine.runAndWait()
                with spr.Microphone() as source:
                    rg.adjust_for_ambient_noise(source)
                    print 'Escuchando'
                    audio=rg.listen(source)
                    try:
                        respuesta= rg.recognize_sphinx(audio)
                        print respuesta
                        if respuesta!='no':
                            self.engine.say('OKEY ')
                            self.engine.say('Getting')
                            self.engine.say('new')
                            self.engine.say('data')
                            self.engine.runAndWait()
                    except spr.UnknownValueError:
                        print 'error'

                    else:
                        print "Desconocido"
            cv2.imshow("Tracking", frame)
            cv2.waitKey(1)
        except CvBridgeError as e:
            print(e)
controller.py 文件源码 项目:furbymt 作者: starfys 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_command():
    with sr.Microphone() as source:
        print("Say something!")
        audio = r.listen(source)
    # recognize speech using Google Speech Recognition
    try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        tts_result = r.recognize_google(audio)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
        exit()
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))
        exit()
    #Read keys from json
    with open('keys.json','r') as keys_file:
        keys = json.load(keys_file)
    apiai_client_token = keys['apiai_client_token']
    #Create a session
    session = requests.Session()
    session.headers.update({"Authorization":"Bearer {}".format(apiai_client_token),
                        "Content-Type":"application/json; charset=utf-8"})
    #API.ai
    API_BASE_URL="https://api.api.ai/v1/"
    #Make a request
    return session.get(API_BASE_URL+"query", params={"query": tts_result,"v":"20170204","sessionId":"furby","lang":"en"}).json()["result"]

#bee_movie, 
#get_date, 
#get_forecast, 
#get_fortune, 
#prompt_name (for get lucky number), 
#get_stallman, 
#torture, 
#get_time, 
#prompt_question (for wolfram query)
#
# joke
# dad joke
# love
# music


问题


面经


文章

微信
公众号

扫码关注公众号