YY LL RR AA SS EE SS EE CC CC AA NO S TARCH PRESS E ARLY ACCESS PROGR AM: FEEDBACK W ELCOME! Welcome to the Early Access edition of the as yet unpublished Make Python Talk by Mark Liu! As a prepublication title, this book may be incomplete and some chapters may not have been proofread. Our goal is always to make the best books possible, and we look forward to hearing your thoughts. If you have any comments or questions, email us at [email protected]. If you have specific feedback for us, please include the page number, book title, and edition date in your note, and we’ll be sure to review it. We appreciate your help and support! We’ll email you as new chapters become available. In the meantime, enjoy! MAKE PY THON TALK MARK LIU Early Access edition, 3/30/21 Copyright © 2021 by Mark Liu. ISBN 13: 978-1-7185-0156-0 (print) ISBN 13: 978-1-7185-0157-7 (ebook) Publisher: William Pollock Executive Editor: Barbara Yien Production Editor: Paula Williamson Developmental Editor: Liz Chadwick Cover and Interior Design: Octopod Studios Cover Illustrator: Gina Redman Technical Reviewer: Noah Spahn Copyeditor: Sharon Wilkey Compositor: Jeff Lytle, Happenstance Type-O-Rama Proofreader: Paula Fleming No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trade- marked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any informa- tion storage or retrieval system, without the prior written permission of the copyright owner and the publisher. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it. 4 Make Python Talk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 5 CONTENTS Speaking Applications . . . . . . . . . . . . . . . . . . . . . . . . . . 17 6 Web Scraping Podcasts, Radios, and Videos . . . . . . . . . . . 39 7 Building a Virtual Personal Assistant . . . . . . . . . . . . . . . . . 61 8 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Know-it-all VPA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Part I: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 Chapter 1: Install Python via Anaconda and Spyder . . . . . . . . . . 9 Chapter 2: Python Refresher . . . . . . . . . . . . . . . . . . . . . . . . . . . Graphics and Animation with the turtle Module . . . . . . . . . Part II: Learning to Talk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Chapter 3: Speech Recognition . . . . . . . . . . . . . . . . . . . . . . . . 10 Chapter 4: Make Python Talk . . . . . . . . . . . . . . . . . . . . . . . . .1 Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Chapter 5: Speaking Applications . . . . . . . . . . . . . . . . . . . .17 115 Chapter 6: Web Scraping Podcasts, Radios, and Videos . . . . .39 11 Chapter 7: Building a Virtual Personal Assistant . . . . . . . . . . .61 Connect Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Chapter 8: Know-it-all VPA . . . . . . . . . . . . . . . . . . . . . . . . . .83 133 Part III: Interactive Games . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Chapter 9: Graphics and Animation with the turtle Module . . .95 guess-the-word Game . . . . . . . . . . . . . . . . . . . . . . . . . . . Chapter 10: Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . . . . . .115 153 Chapter 11: Connect Four . . . . . . . . . . . . . . . . . . . . . . . .133 13 Chapter 12: guess-the-word Game . . . . . . . . . . . . . . . . . . .153 Smart Games: Adding Intelligence . . . . . . . . . . . . . . . . . . Chapter 13: Smart Games: Adding Intelligence . . . . . . . . .167 167 Part IV: Going Further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Chapter 14: Financial Applications . . . . . . . . . . . . . . . . . .195 Financial Applications . . . . . . . . . . . . . . . . . . . . . . . . . . Chapter 15: Stock Market Watch . . . . . . . . . . . . . . . . . . .219 195 Chapter 16: Use Other Languages: Translator 15 Chapter 17: Ultimate VPA Stock Market Watch . . . . . . . . . . . . . . . . . . . . . . . . . . . . Appendix A: Useful Speech Modules 219 Appendix B: Answers to End of Chapter Exercises Index The chapters in red are included in this Early Access PDF. Make Python Talk (Early Access) © 2021 by Mark Liu 4 MAKE PY THON TALK In this chapter, you’ll learn how to make Python talk back to you in a human voice. You’ll first install the text-to-speech mod- ule based on your operating system, and then teach Python to speak aloud whatever you enter on your computer. You’ll also add the speech-recognition feature you learned in Chapter 3 and get Python to repeat your own speech. Finally, you’ll build a real- world application to use voice inputs to ask Python to calculate the area of a rectangle and tell you the answer in a human voice. To save space, you’ll put all text-to-speech-related code in a self-made module. Once you know how to do that, you can import the module into any script that needs the text-to-speech feature. Make Python Talk (Early Access) © 2021 by Mark Liu You’ll also learn how to ask Python to read a long text file such as a news article aloud. Before you begin, set up the folder /mpt/ch04/ for this chapter. NEW SKILLS • Installing speech-related modules depending on your operating system • Adjusting properties of your text-to-speech module • Learning how to create a module that is portable cross-platform • Combining the text-to-speech module with speech recognition so a com- puter can repeat what you said • Making the computer solve a problem and answer you in a human voice Install the Text-to-Speech Module Python has two commonly used text-to-speech modules: pyttsx3 and gTTS. If you use Windows, you’ll install pyttsx3 and use it throughout the book. In the Windows operating system, the pyttsx3 module works offline, has a human-like voice, and lets you adjust the speech properties—namely, the speed, volume, and gender of the voice output. However, the pyttsx3 module works differently in Mac and Linux. The voice sounds robotic, and the speech properties are not easily adjustable. Therefore, you’ll install gTTS if you use Mac or Linux. The gTTS module requires an internet connection since it uses the Google Translate text-to- speech application programming interface (API). Further, gTTS does not play the sound directly. It saves the voice as an audio file or file-like object. You’ll have to use your own audio player to hear the voice. The voice gen- erated by gTTS is very human-like. In Chapter 2, you built a virtual environment called chatting for speech recognition. You’ll install the pyttsx3 or gTTS module in the same virtual environment so your script will have both the speech-recognition and text- to-speech features. Set Up If you are using Windows, go to the “Install pyttsx3 in Windows” section and skip the “Install gTTS in Mac or Linux” section. Otherwise, skip the “Install pyttsx3 in Windows” section and go to the “Install gTTS in Mac or Linux” section. Install pyttsx3 in Windows The pyttsx3 module is not in the Python standard library, so you’ll need to install it via pip. 2 Chapter 4 Make Python Talk (Early Access) © 2021 by Mark Liu If you haven’t already set up your chatting virtual environment, go back to Chapter 2 now and follow the instructions to do so. Then activate the virtual environment chatting in the Anaconda prompt by executing the following: conda activate chatting With your chatting virtual environment activated, enter this: pip install pyttsx3 Follow the instructions onscreen to finish the installation. Install gTTS in Mac or Linux The gTTS module is not in the Python standard library, so you’ll need to install it via pip. If you haven’t already set up your chatting virtual environment, go back to Chapter 2 now and follow the instructions to do so. Then activate the vir- tual environment chatting in a terminal by executing the following: conda activate chatting With your chatting virtual environment activated in your terminal, enter this: pip install gtts Follow the instructions onscreen to finish the installation. Test Your Text-to-Speech Module Before beginning, you’ll check that your text-to-speech module is properly installed and working. Based on your operating system, skip the sections that don’t apply to you. Run a Sample Script in Windows With your virtual environment activated and Spyder open, copy the script test_pyttsx3.py into your editor and save it in your chapter folder. If you pre- fer, you can download the file from the book’s resources through https:// www.nostarch.com/makepythontalk/. import pyttsx3 1 engine = pyttsx3.init() 2 engine.say("hello, how are you?") engine.runAndWait() First import the pyttsx3 module to the script. Then use init() to initiate a text-to-speech engine in the pyttsx3 module and call it engine 1. The say() function in the pyttsx3 module converts the text to a speech signal, and Make Python Talk 3 Make Python Talk (Early Access) © 2021 by Mark Liu prepares to send it to the speaker 2. The runAndWait() function then sends the actual speech signal to the speaker so you can hear the sound. The runAndWait() function also keeps the engine running so that when you want to convert text to speech later in the script, you don’t need to initiate the engine again. Run test_pyttsx3.py line by line by using the F9 key to help you under- stand how each line of code functions. NOTE The say() function in the pyttsx3 module only converts the text to a speech signal and prepares to send it to the speaker. It does not do the actual speaking. To hear the sound, use runAndWait(), which sends the speech signal to the speaker. If the module is correctly installed, when you finish running the whole script, you should hear a voice saying, “Hello, how are you?” If not, recheck the instructions and make sure that the speaker on your computer is work- ing properly at the right volume. I’ll discuss later in this chapter how to cus- tomize the speed, volume, and the voice gender associated with the pyttsx3 module. Run a Sample Script in Mac or Linux We’ll use the gtts-cli tool (cli stands for command line) to convert text to speech, instead of converting text to an audio file, and then play it. The gtts-cli tool is faster than the alternative method. Once you install the gTTS module, the gtts-cli tool is available in the command line in your virtual environment. The gtts-cli tool converts the text to a file-like object, and you have to choose which audio player to play it. I find that the mpg123 player works well. First, you need to install the mpg123 player on your computer. If you are using Mac, run the following command on a terminal: brew install mpg123 If you are using Linux, run the following two commands on a terminal: sudo apt-get update sudo apt-get install mpg123 Once you’re finished, with your virtual environment activated, run the following command in a terminal: gtts-cli --nocheck "hello, how are you?" | mpg123 -q - If you have correctly installed everything, you should hear a voice saying, “Hello, how are you?” If not, recheck the instructions and make sure that the speaker on your computer is working properly at the right volume. Further, since you have installed the gTTS module in your virtual environment, you have to run the preceding command with your virtual environment acti- vated. Otherwise, it won’t work. 4 Chapter 4 Make Python Talk (Early Access) © 2021 by Mark Liu The nocheck option in this command is to speed up execution. The q flag instructs the module not to display copyright and version messages, even in an interactive mode. Make sure you don’t miss the hyphen at the end of the command. Next, you’ll use the os module in Python to execute commands in a subshell. Copy the test_gtts.py script into your Spyder editor and save it in your chapter folder. The script is also available at the book’s resources through https://www.nostarch.com/makepythontalk. import os os.system('gtts-cli --nocheck "hello, how are you?" | mpg123 -q -') First import the os module to the script. Then use system()to execute a command in a subshell to achieve the same effect of running the command in a terminal. As a result, the gtts-cli tool is used to convert text to a file-like object. After that, the mpg123 player plays the sound object so you can hear a human voice. NOTE You don’t need to explicitly import the gTTS module in test_gtts.py because you use the gtts-cli tool in the command line, even though the gTTS module is used. If you’ve done everything correctly, you should hear a voice saying, “Hello, how are you?” Convert Text to Voice in Windows Now let’s practice converting written text input into a human voice in Windows. With your virtual environment activated and Spyder open, copy the script tts_windows.py, as shown in Listing 4-1, into your editor and save and run it. import pyttsx3 engine = pyttsx3.init() 1 while True: 2 inp = input("What do you want to covert to speech?\n") 3 if inp == "done": print(f"You just typed in {inp}, goodbye!") engine.say(f"You just typed in {inp}, goodbye!") engine.runAndWait() break 4 else: print(f"You just typed in {inp}") engine.say(f"You just typed in {inp}") engine.runAndWait() 5 continue Listing 4-1: Converting text to voice in Windows Make Python Talk 5 Make Python Talk (Early Access) © 2021 by Mark Liu After importing the pyttsx3 module and initiating a text-to-speech engine, start an infinite loop to take user text input 1. In each iteration, the script asks for text input at the IPython console 2. If you want to stop the script, enter done 3, and the script will print and say in a human voice, “You just typed in done; goodbye!” After that, the loop stops, and the script quits running. If the text input is not done, the else branch runs 4, and the script speaks your text input out loud in a human voice. After that, the script goes to the next iteration and takes your text input again 5. The following is sample output from the script (user input is in bold): What do you want to covert to speech? Python is great! You just typed in Python is great! What do you want to covert to speech? Hello, world! You just typed in Hello, world! What do you want to covert to speech? done You just typed in done; goodbye! Convert Text to Voice in Mac or Linux Now we’ll practice converting written text input into a human voice in Mac or Linux. With your virtual environment activated and Spyder open, copy the script tts_mac_linux.py (Listing 4-2) into your editor, and save and run it. import os while True: 1 inp = input("What do you want to covert to speech?\n") 2 if inp == "done": 3 print(f"You just typed in {inp}, goodbye!") os.system(f'gtts-cli --nocheck "You just typed in {inp}, goodbye!" | mpg123 -q -') break else: 4 print(f"You just typed in {inp}") os.system(f'gtts-cli --nocheck "You just typed in {inp}" | mpg123 -q -') continue 5 Listing 4-2: Converting text to voice in Mac and Linux After importing the os module so you can run commands in a subshell, start an infinite loop to take user text input 1. In each iteration, the script asks for text input at the IPython console 2. If you want to stop the script, enter done 3, and the script will print and say in a human voice, “You just typed in done; goodbye!” After that, the loop stops, and the script quits running. 6 Chapter 4