Make Python Talk Mark H Liu download
Make Python Talk Mark H Liu download
https://ebookmeta.com/product/make-python-talk-mark-h-liu/
https://ebookmeta.com/product/make-python-talk-1st-edition-mark-
liu/
https://ebookmeta.com/product/make-python-talk-build-apps-with-
voice-control-and-speech-recognition-1st-edition-mark-liu/
https://ebookmeta.com/product/lets-talk-python-young-coders-
build-software-meap-v06-pavel-anni/
https://ebookmeta.com/product/killer-fame-1st-edition-mary-stone-
stacy-o-hare/
Atlas of Lip and Nose Plastic and Cosmetic Surgery
Jianhua Liu (Editor)
https://ebookmeta.com/product/atlas-of-lip-and-nose-plastic-and-
cosmetic-surgery-jianhua-liu-editor/
https://ebookmeta.com/product/grumpy-girl-and-amaryllis-sunshine-
guy-grumpy-girl-romance-dirty-hoe-love-book-5-1st-edition-brynn-
hale/
https://ebookmeta.com/product/natural-language-processing-with-
transformers-building-language-applications-with-hugging-
face-1st-edition-tunstall/
https://ebookmeta.com/product/spectrums-of-amyotrophic-lateral-
sclerosis-heterogeneity-pathogenesis-and-therapeutic-
directions-1st-edition/
https://ebookmeta.com/product/russian-imperialism-revisited-from-
disengagement-to-hegemony-1st-edition-domitilla-sagramoso/
Narcocapitalism Life in the Age of Anaesthesia Theory
Redux 1st Edition Laurent De Sutter
https://ebookmeta.com/product/narcocapitalism-life-in-the-age-of-
anaesthesia-theory-redux-1st-edition-laurent-de-sutter/
R L Y
A
E ESS
A C C
N O S TA R C H P R E S S
E A R LY A C C E S S P R O G R A M :
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 earlyaccess@nostarch.com. 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!
M A K E P Y T H O N TA L K
MARK LIU
Early Access edition, 3/30/21
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.
CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Part I: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 1: Install Python via Anaconda and Spyder . . . . . . . . .
Chapter 2: Python Refresher . . . . . . . . . . . . . . . . . . . . . . . . . .
Part II: Learning to Talk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 3: Speech Recognition . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 4: Make Python Talk . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 5: Speaking Applications . . . . . . . . . . . . . . . . . . . . 17
Chapter 6: Web Scraping Podcasts, Radios, and Videos . . . . 39
Chapter 7: Building a Virtual Personal Assistant . . . . . . . . . . 61
Chapter 8: Know-it-all VPA . . . . . . . . . . . . . . . . . . . . . . . . . 83
Part III: Interactive Games . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 9: Graphics and Animation with the turtle Module . . . 95
Chapter 10: Tic-Tac-Toe . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Chapter 11: Connect Four . . . . . . . . . . . . . . . . . . . . . . . . 133
Chapter 12: guess-the-word Game . . . . . . . . . . . . . . . . . . 153
Chapter 13: Smart Games: Adding Intelligence . . . . . . . . . 167
Part IV: Going Further . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 14: Financial Applications . . . . . . . . . . . . . . . . . . 195
Chapter 15: Stock Market Watch . . . . . . . . . . . . . . . . . . . 219
Chapter 16: Use Other Languages: Translator
Chapter 17: Ultimate VPA
Appendix A: Useful Speech Modules
Appendix B: Answers to End of Chapter Exercises
Index
4
M A K E P Y T H O N TA L K
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.
NE W SKILL S
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.
2 Chapter 4
Make Python Talk (Early Access) © 2021 by Mark Liu
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
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.
If you are using Linux, run the following two commands on a terminal:
Once you’re finished, with your virtual environment activated, run the
following command in a terminal:
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
import os
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.
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
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
6 Chapter 4
Make Python Talk (Early Access) © 2021 by Mark Liu
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):
Repeat After Me
We’ll start with a simple script that hears what you say aloud and repeats it
in a human voice. This script serves two purposes. First, you’ll learn how the
script takes your voice inputs, and which words are easiest for the script to
understand—some uncommon words won’t be understood. Second, you’ll
learn how to put both the speech-recognition and text-to-speech features
in the same script, so you can communicate with the computer through
human voices only.
We’ll also make the script portable cross-platform. The script will auto-
matically choose the pyttsx3 module if you are using Windows and the gTTS
module otherwise.
Start a new script, name it repeat_me.py, and enter the code in Listing 4-3.
Make sure to save it in your chapter folder. You’ll also need to copy your
mysr.py file from Chapter 3 and paste it into the same folder, as we’ll need
voice_to_text() from that script.
# Make sure you put mysr.py in the same folder as this script
from mysr import voice_to_text
import platform 1
if platform.system() == "Windows":
import pyttsx3
engine = pyttsx3.init()
else:
import os
while True:
print('Python is listening...')
inp = voice_to_text() 2
if inp == "stop listening": 3
print(f'You just said {inp}; goodbye!')
if platform.system() == "Windows":
else:
print(f'You just said {inp}')
if platform.system() == "Windows": 4
engine.say(f'You just said {inp}')
engine.runAndWait()
else:
os.system(f'gtts-cli --nocheck "You just said {inp}" | mpg123 -q -')
continue
WARNING Remember to put mysr.py in the same folder as Listing 4-3. Otherwise, the speech-
recognition feature won’t work! Yes, I’ve said this before, but it bears repeating until it
sinks in.
Python is listening...
You just said hello
Python is listening...
You just said how are you
Python is listening...
You just said stop listening; goodbye!
NOTE If you pause often while the script stands by, the script may say, “You just said” in a
human voice again and again when you are not speaking. To avoid that, you can
modify repeat_me.py by removing the You just said part ( 4 in Listing 4-3).
8 Chapter 4
Make Python Talk (Early Access) © 2021 by Mark Liu
import pyttsx3
engine = pyttsx3.init()
1 voices = engine.getProperty('voices')
2 for voice in voices:
print(voice)
3 rate = engine.getProperty("rate")
print("the default speed of the speech is", rate)
vol = engine.getProperty("volume")
print("the default volume of the speech is", vol)
<Voice id=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
name=Microsoft David Desktop - English (United States)
languages=[]
gender=None
age=None>
<Voice id=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0
name=Microsoft Zira Desktop - English (United States)
languages=[]
gender=None
age=None>
the default speed of the speech is 200
the default volume of the speech is 1.0
Here you can see the two voices available to the pyttsx3 module. The
first voice is named David with a male voice tone; the second voice is named
Zira with a female voice tone. The default voice tone is David, hence the
male voice you hear in test_pyttsx3.py.
The default speech speed is 200 words per minute. The default volume
is set at 1. You’ll learn how to adjust the speed, volume, and ID in the pyttsx3
module in Windows next.
import pyttsx3
engine = pyttsx3.init()
voice_id = 1
1 voices = engine.getProperty('voices')
2 engine.setProperty('voice', voices[voice_id].id)
3 engine.setProperty('rate', 150)
4 engine.setProperty('volume', 1.2)
5 engine.say("This is a test of my speech id, speed, and volume.")
engine.runAndWait()
Let’s choose the second voice ID, which has a female voice. At 1, the
script obtains the voice objects available in the text-to-speech engine and
saves them in a list called voices. We choose the second object in the list voices
by giving the index [1] 2, which has a female voice tone. The setProperty()
function takes two arguments: the property to set, and the value to set it to.
We set the value to voices[voiceID].id to choose the id value of the female
voice object in Windows, which is HKEY_LOCAL_MACHINE\SOFTWARE\
Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_ZIRA_11.0. If you want to
change to the male voice in Windows, you can use voices[0].id instead.
Here we set the speech speed to 150 words per minute 3. Most of us
speak at the rate of about 125 words per minute in our daily lives. For faster
speech, set it to a number greater than 125, and for slower speech, set it to a
number below 125.
We set the volume to 1.2 4, which is louder than the default value of
1. You can set this to higher or lower than 1 based on your preference and
speakers.
At 5, the script converts the text in say() into speech by using the
adjusted properties. Try running this script multiple times with different
combinations of parameters until you find the best combination for you.
You can always come back to this script and adjust.
10 Chapter 4
Make Python Talk (Early Access) © 2021 by Mark Liu
import os
The script is the same as test_gtts.py you’ve created before except that it
adds the --slow option. This changes the voice output to slower than normal.
If you run this script in Mac or Linux, you’ll hear the computer saying,
“Hello, how are you?” in a slow pace.
Since the default setting for the speed is slow=False, and that’s what we
prefer, we won’t customize the gTTS module.
Create mysay
You’ll create a local module mysay and save it in the same folder as any script
that uses the text-to-speech feature. That way, you can save space in the main
script. This module has adjusted the properties for speed, volume, and gen-
der of the speech set in pyttsx3_adjust.py if you are using Windows. If you are
using Mac or Linux, the local module mysay will use the default properties
in the gTTS module. You can modify these parameters based on your own
preferences.
Enter the code in Listing 4-6 and save it as mysay.py in your chapter folder.