Created
June 22, 2019 05:55
-
-
Save admond1994/5e502d4f6b8723bf05b222e1dfd4de04 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| def recognize_speech_from_mic(recognizer, microphone): | |
| """Transcribe speech from recorded from `microphone`. | |
| Returns a dictionary with three keys: | |
| "success": a boolean indicating whether or not the API request was | |
| successful | |
| "error": `None` if no error occured, otherwise a string containing | |
| an error message if the API could not be reached or | |
| speech was unrecognizable | |
| "transcription": `None` if speech could not be transcribed, | |
| otherwise a string containing the transcribed text | |
| """ | |
| # check that recognizer and microphone arguments are appropriate type | |
| if not isinstance(recognizer, sr.Recognizer): | |
| raise TypeError("`recognizer` must be `Recognizer` instance") | |
| if not isinstance(microphone, sr.Microphone): | |
| raise TypeError("`microphone` must be `Microphone` instance") | |
| # adjust the recognizer sensitivity to ambient noise and record audio | |
| # from the microphone | |
| with microphone as source: | |
| recognizer.adjust_for_ambient_noise(source) # # analyze the audio source for 1 second | |
| audio = recognizer.listen(source) | |
| # set up the response object | |
| response = { | |
| "success": True, | |
| "error": None, | |
| "transcription": None | |
| } | |
| # try recognizing the speech in the recording | |
| # if a RequestError or UnknownValueError exception is caught, | |
| # update the response object accordingly | |
| try: | |
| response["transcription"] = recognizer.recognize_google(audio) | |
| except sr.RequestError: | |
| # API was unreachable or unresponsive | |
| response["success"] = False | |
| response["error"] = "API unavailable/unresponsive" | |
| except sr.UnknownValueError: | |
| # speech was unintelligible | |
| response["error"] = "Unable to recognize speech" | |
| return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment