[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nenv/\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# dotenv\n.env\n\n# virtualenv\n.venv\nvenv/\nENV/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Real Python\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Speech Recognition with Python\n\nThis repository contains resources from [The Ultimate Guide to Speech Recognition with Python](https://realpython.com/python-speech-recognition/) tutorial on Real Python.\n\nAudio files for the examples in the *Working With Audio Files* section of the post can be found in the `audio_files` directory. To download them, use the green \"Clone or download\" button at the top right corner of this page.\n\nThe `guessing_game.py` file contains the full source code for the \"Guess a Word\" game example.\n\n> **NOTE**: You will need to install the [SpeechRecognition](https://github.com/Uberi/speech_recognition) and [PyAudio](https://people.csail.mit.edu/hubert/pyaudio/) packages in order to run the example. Please see the [tutorial](https://realpython.com/python-speech-recognition/) for step-by-step instructions.\n\nYou can test your SpeechRecognition and PyAudio installation by downloading `guessing_game.py` and typing the following into a Python REPL session:\n\n```pycon\n>>> import speech_recognition as sr\n>>> from guessing_game.py import recognize_speech_from_mic\n>>> r = sr.Recognizer()\n>>> m = sr.Microphone()\n>>> recognize_speech_from_mic(r, m)  # speak after running this line\n{'success': True, 'error': None, 'transcription': 'hello'}\n```\n\nOf course, your output will vary depending on what you said after running `recognize_speech_from_mic(r, m)`.\n"
  },
  {
    "path": "guessing_game.py",
    "content": "import random\nimport time\n\nimport speech_recognition as sr\n\n\ndef recognize_speech_from_mic(recognizer, microphone):\n    \"\"\"Transcribe speech from recorded from `microphone`.\n\n    Returns a dictionary with three keys:\n    \"success\": a boolean indicating whether or not the API request was\n               successful\n    \"error\":   `None` if no error occured, otherwise a string containing\n               an error message if the API could not be reached or\n               speech was unrecognizable\n    \"transcription\": `None` if speech could not be transcribed,\n               otherwise a string containing the transcribed text\n    \"\"\"\n    # check that recognizer and microphone arguments are appropriate type\n    if not isinstance(recognizer, sr.Recognizer):\n        raise TypeError(\"`recognizer` must be `Recognizer` instance\")\n\n    if not isinstance(microphone, sr.Microphone):\n        raise TypeError(\"`microphone` must be `Microphone` instance\")\n\n    # adjust the recognizer sensitivity to ambient noise and record audio\n    # from the microphone\n    with microphone as source:\n        recognizer.adjust_for_ambient_noise(source)\n        audio = recognizer.listen(source)\n\n    # set up the response object\n    response = {\n        \"success\": True,\n        \"error\": None,\n        \"transcription\": None\n    }\n\n    # try recognizing the speech in the recording\n    # if a RequestError or UnknownValueError exception is caught,\n    #     update the response object accordingly\n    try:\n        response[\"transcription\"] = recognizer.recognize_google(audio)\n    except sr.RequestError:\n        # API was unreachable or unresponsive\n        response[\"success\"] = False\n        response[\"error\"] = \"API unavailable\"\n    except sr.UnknownValueError:\n        # speech was unintelligible\n        response[\"error\"] = \"Unable to recognize speech\"\n\n    return response\n\n\nif __name__ == \"__main__\":\n    # set the list of words, maxnumber of guesses, and prompt limit\n    WORDS = [\"apple\", \"banana\", \"grape\", \"orange\", \"mango\", \"lemon\"]\n    NUM_GUESSES = 3\n    PROMPT_LIMIT = 5\n\n    # create recognizer and mic instances\n    recognizer = sr.Recognizer()\n    microphone = sr.Microphone()\n\n    # get a random word from the list\n    word = random.choice(WORDS)\n\n    # format the instructions string\n    instructions = (\n        \"I'm thinking of one of these words:\\n\"\n        \"{words}\\n\"\n        \"You have {n} tries to guess which one.\\n\"\n    ).format(words=', '.join(WORDS), n=NUM_GUESSES)\n\n    # show instructions and wait 3 seconds before starting the game\n    print(instructions)\n    time.sleep(3)\n\n    for i in range(NUM_GUESSES):\n        # get the guess from the user\n        # if a transcription is returned, break out of the loop and\n        #     continue\n        # if no transcription returned and API request failed, break\n        #     loop and continue\n        # if API request succeeded but no transcription was returned,\n        #     re-prompt the user to say their guess again. Do this up\n        #     to PROMPT_LIMIT times\n        for j in range(PROMPT_LIMIT):\n            print('Guess {}. Speak!'.format(i+1))\n            guess = recognize_speech_from_mic(recognizer, microphone)\n            if guess[\"transcription\"]:\n                break\n            if not guess[\"success\"]:\n                break\n            print(\"I didn't catch that. What did you say?\\n\")\n\n        # if there was an error, stop the game\n        if guess[\"error\"]:\n            print(\"ERROR: {}\".format(guess[\"error\"]))\n            break\n\n        # show the user the transcription\n        print(\"You said: {}\".format(guess[\"transcription\"]))\n\n        # determine if guess is correct and if any attempts remain\n        guess_is_correct = guess[\"transcription\"].lower() == word.lower()\n        user_has_more_attempts = i < NUM_GUESSES - 1\n\n        # determine if the user has won the game\n        # if not, repeat the loop if user has more attempts\n        # if no attempts left, the user loses the game\n        if guess_is_correct:\n            print(\"Correct! You win!\".format(word))\n            break\n        elif user_has_more_attempts:\n            print(\"Incorrect. Try again.\\n\")\n        else:\n            print(\"Sorry, you lose!\\nI was thinking of '{}'.\".format(word))\n            break\n"
  }
]