Python Text to Speech in Macintosh - python

Are there any libraries in Python that does or allows Text To Speech Conversion using Mac Lion's built in text to speech engine?
I did google but most are windows based. I tried pyttx.
I tried to run
import pyttsx
engine = pyttsx.init()
engine.say('Sally sells seashells by the seashore.')
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()
But I get these errors
File "/Users/manabchetia/Documents/Codes/Speech.py", line 2, in <module>
engine = pyttsx.init()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyttsx-1.0.egg/pyttsx/__init__.py", line 39, in init
eng = Engine(driverName, debug)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyttsx-1.0.egg/pyttsx/engine.py", line 45, in __init__
self.proxy = driver.DriverProxy(weakref.proxy(self), driverName, debug)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyttsx-1.0.egg/pyttsx/driver.py", line 64, in __init__
self._module = __import__(name, globals(), locals(), [driverName])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyttsx-1.0.egg/pyttsx/drivers/nsss.py", line 18, in <module>
ImportError: No module named Foundation
How do I solve these errors?

Wouldn't it be much simpler to do this?
from os import system
system('say Hello world!')
You can enter man say to see other things you can do with the say command.
However, if you want some more advanced features, importing AppKit would also be a possibility, although some Cocoa/Objective C knowledge is needed.
from AppKit import NSSpeechSynthesizer
speechSynthesizer = NSSpeechSynthesizer.alloc().initWithVoice_("com.apple.speech.synthesis.voice.Bruce")
speechSynthesizer.startSpeakingString_('Hi! Nice to meet you!')
If you would like to see more things you can do with NSSpeechSynthesizer take a look at Apple's documentation: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSSpeechSynthesizer_Class/Reference/Reference.html

If you are targeting Mac OS X as your platform - PyObjC and NSSpeechSynthesizer is your best bet.
Here is a quick example for you
#!/usr/bin/env python
from AppKit import NSSpeechSynthesizer
import time
import sys
if len(sys.argv) < 2:
text = raw_input('type text to speak> ')
else:
text = sys.argv[1]
nssp = NSSpeechSynthesizer
ve = nssp.alloc().init()
for voice in nssp.availableVoices():
ve.setVoice_(voice)
print voice
ve.startSpeakingString_(text)
while not ve.isSpeaking():
time.sleep(0.1)
while ve.isSpeaking():
time.sleep(0.1)
Please note that AppKit module is part of PyObjC bridge and should be already installed on your Mac. No need to install it if you are using OS provided python (/usr/bin/python)

This might work:
import subprocess
subprocess.call(["say","Hello World! (MESSAGE)"])

Related

Chatterbot : AttributeError: module 'time' has no attribute 'clock'

I am trying to create a chatbot, but since latest version of chatterbot was not getting installed on my pc so I installed chatterbot by using pip install chatterbot==1.0.4 and the following error is showing up.
How do I resolve this?
Below is the code:
from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
bot = ChatBot("My Bot")
convo = [
'hello',
'hi there',
'what is your name?',
'My name is BOT, I am created my a hooman ',
'how are you',
'i am doing great these days',
'thank you',
'in which city you live',
'i live in kalyan',
'in which languages do you speak',
'i mostly talk in english'
]
trainer=ListTrainer(bot)
trainer.train(convo)
print("Talk to Bot")
while True:
query=input()
if query=='exit':
break
answer=bot.get_response
print("bot : ", answer)
output :
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
PS E:\GIT VS CODE\Py> & D:/Python/python.exe "e:/GIT VS CODE/Py/chatbot.py"
Traceback (most recent call last):
File "e:\GIT VS CODE\Py\chatbot.py", line 4, in <module>
bot = ChatBot("My Bot")
File "D:\Python\lib\site-packages\chatterbot\chatterbot.py", line 34, in __init__
self.storage = utils.initialize_class(storage_adapter, **kwargs)
File "D:\Python\lib\site-packages\chatterbot\utils.py", line 54, in initialize_class
return Class(*args, **kwargs)
File "D:\Python\lib\site-packages\chatterbot\storage\sql_storage.py", line 22, in __init__
from sqlalchemy import create_engine
File "D:\Python\lib\site-packages\sqlalchemy\__init__.py", line 8, in <module>
from . import util as _util # noqa
File "D:\Python\lib\site-packages\sqlalchemy\util\__init__.py", line 14, in <module>
from ._collections import coerce_generator_arg # noqa
File "D:\Python\lib\site-packages\sqlalchemy\util\_collections.py", line 16, in <module>
from .compat import binary_types
File "D:\Python\lib\site-packages\sqlalchemy\util\compat.py", line 264, in <module> time_func = time.clock
AttributeError: module 'time' has no attribute 'clock'
I agree with #Glycerine's answer, well, if you don't want to downgrade your python version, I have another solution for you.
Open the file <Python-folder>\Lib\site-packages\sqlalchemy\util\compat.py
Go to line 264 which states:
if win32 or jython:
time_func = time.clock
else:
time_func = time.time
Change it to:
if win32 or jython:
#time_func = time.clock
pass
else:
time_func = time.time
Simply here we are avoiding the use of timer.clock method and the time_func object because I saw that this object is just created for nothing and does nothing. It is just created and left untouched.
I don't know why even this exists when it is of no use. But this should work for you.
Hope it helped!
What version of python are you running? time.clock has been removed for py 3.8+
Solutions include downgrading python or altering the source it seems:
AttributeError: module 'time' has no attribute 'clock' in Python 3.8
From the Python 3.8 doc:
The function time.clock() has been removed, after having been deprecated since Python 3.3: use time.perf_counter() or time.process_time() instead, depending on your requirements, to have well-defined behavior. (Contributed by Matthias Bussonnier in bpo-36895.)
Solution for - AttributeError: module 'time' has no attribute 'clock'
In Response to your comment: I'm assuming the chatterbox devs will fix this eventually but yes, downgrading to Python 3.7 will fix this: https://docs.python.org/3.7/library/time.html#time.clock
Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.
Im not an expert, but have you tried 'import time' in the top of your code. Worked for me when I was using time.sleep() in my pythoncode

pdfdump in python not working using scapy

#!/bin/bash/python3
from scapy3k.all import *``
import subprocess
import os
def ifac111():
pkts = sniff(filter="tcp", iface="tun0", count=100)
inp = input('want to see a \'pdfdump?\' \n Y/N--> ')
fag = pkts.summary()
print('-' * 60)
what_df = pkts.show()
print("^^^ Here you got {} packets {}.".format("100", "scanned"))
print("The {} ones are {} and second ones are just {} command".format("first", "summary", "show" ))
print(inp)
if inp == 'Y':
pkts[0].pdfdump()
else:
print("got ya \f hex0")
while 1 > 0:
SSS = input('enter your command\'s here:-> \t ') #\t moves 4 spaces
if SSS == 'packets':
ifac111()
elif SSS == 'nworkscan':
os.system('sudo nmap localhost/24')
elif SSS == 'Virusscan':
os.system('sudo chkrootkit')
elif SSS == 'clear':
subprocess.call('clear')
when i run the pdfdump i get this error
Traceback (most recent call last):
File "scapy2.py", line 27, in <module>
ifac111()
File "scapy2.py", line 16, in ifac111
pkts[0].pdfdump()
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 418, in pdfdump
canvas = self.canvas_dump(**kargs)
File "/usr/local/lib/python3.6/dist-packages/scapy3k/packet.py", line 428, in canvas_dump
canvas = pyx.canvas.canvas()
NameError: name 'pyx' is not defined
sorry if the question is stupid I'm new with coding and been trying to do some research with no result I used ICMP instead of TCP also before on my old os but its not working after changing to parrot os and when I run pdfdump I get that error above
This is a bug in scapy3k.packet indeed - it tries to import pyx and silently continue if there's any import error, which leads to your problem:
try:
import pyx
except ImportError:
pass
You should fill a bug report in the project's github - the package should properly declare it's dependencies on 3rd part packages so they get installed alongside, and it should definitly not silence the fact that a required import failed.
In the meantime you can try installing pyx yourself - it might just work, or it might break elsewhere depending on versions compat.
You should use scapy instead of scapy3k, it contains those fixes and a better interception of PyX
FTR:
scapy3k = fork based on scapy 2.2.0 which used to be the only one supporting python 3
scapy (from secdev) = the original one, up-to-date that also works with python 3 since scapy 2.4.0+
Hard to believe this issue is still around after 3yrs. This is to inform anyone else who lands here wanting to know how to fix this problem.
It is due to "Intended" lazy import placed on the installation as it would require GB/s of downloaded files to support the TeX backend. Thus, this is an intentional error by the scapy project itself.
You need to install MikTeX and LiveTex as it is not evident.
LiveTex can be downloaded from here

NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH environment variable

I am working on a project that requires me to tag tokens using nltk and python. So I wanted to use this. But came up with a few problems.
I went through a lot of other already asked questions and other forums but I was still unable to get a soultion to this problem.
The problem is when I try to execute the following:
from nltk.tag import StanfordPOSTagger
st = StanfordPOSTagger('english-bidirectional-distsim.tagger')
I get the following:
Traceback (most recent call last):
`File "<pyshell#13>", line 1, in <module>
st = StanfordPOSTagger('english-bidirectional-distsim.tagger')`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nltk-3.1-py3.5.egg\nltk\tag\stanford.py", line 131, in __init__
super(StanfordPOSTagger, self).__init__(*args, **kwargs)`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nltk-3.1-py3.5.egg\nltk\tag\stanford.py", line 53, in __init__
verbose=verbose)`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nltk-3.1-py3.5.egg\nltk\internals.py", line 652, in find_jar
searchpath, url, verbose, is_regex))`
`File "C:\Users\MY3\AppData\Local\Programs\Python\Python35-32\lib\site-packages\nltk-3.1-py3.5.egg\nltk\internals.py", line 647, in find_jar_iter
raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div))`
LookupError:
===========================================================================
NLTK was unable to find stanford-postagger.jar! Set the CLASSPATH
environment variable.
===========================================================================
I already set the
CLASSPATH - C:\Users\MY3\Desktop\nltk\stanford\stanford-postagger.jar
I tried it as C:\Users\MY3\Desktop\nltk\stanford as well..
STANFORD_MODELS - C:\Users\MY3\Desktop\nltk\stanford\models\
I tried doing this as well..in vain
File "C:\Python27\lib\site-packages\nltk\tag\stanford.py", line 45, in __init__
env_vars=('STANFORD_MODELS',), verbose=verbose)
but it doesn't solve the problem either. Please Help me in solving this issue.
I use Windows 8, python 3.5 and nltk 3.1
Update
The original answer was written for Stanford POS Tagger Version 3.6.0, Date 2015-12-09
There is a new Version (3.7.0, released 2016-10-31). Here's the code for the newer version:
from nltk.tag import StanfordPOSTagger
from nltk import word_tokenize
# Add the jar and model via their path (instead of setting environment variables):
jar = 'your_path/stanford-postagger-full-2016-10-31/stanford-postagger.jar'
model = 'your_path/stanford-postagger-full-2016-10-31/models/english-left3words-distsim.tagger'
pos_tagger = StanfordPOSTagger(model, jar, encoding='utf8')
text = pos_tagger.tag(word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
Original answer
I had the same problem (but using OS X and PyCharm), finally got it to work. Here's what I've pieced together from the StanfordPOSTagger Documentation and alvas' work on the issue (big thanks!):
from nltk.internals import find_jars_within_path
from nltk.tag import StanfordPOSTagger
from nltk import word_tokenize
# Alternatively to setting the CLASSPATH add the jar and model via their path:
jar = '/Users/nischi/PycharmProjects/stanford-postagger-full-2015-12-09/stanford-postagger.jar'
model = '/Users/nischi/PycharmProjects/stanford-postagger-full-2015-12-09/models/english-left3words-distsim.tagger'
pos_tagger = StanfordPOSTagger(model, jar)
# Add other jars from Stanford directory
stanford_dir = pos_tagger._stanford_jar.rpartition('/')[0]
stanford_jars = find_jars_within_path(stanford_dir)
pos_tagger._stanford_jar = ':'.join(stanford_jars)
text = pos_tagger.tag(word_tokenize("What's the airspeed of an unladen swallow ?"))
print(text)
Hope this helps.
I use Jupyter Notebook with Pycharm.
I tried the Run Configuration in Pycharm to set env variable, but not work.
So I use os.environ to set it in the code:
import os
os.environ["CLASSPATH"] = "/yourPath/stanford-parser-full-2018-10-17:yourPath/stanford-postagger-full-2018-10-16:yourPath/stanford-ner-2018-10-16"
os.environ["STANFORD_MODELS"] = "yourPath/stanford-postagger-full-2018-10-16/models:yourPath/stanford-ner-2018-10-16/classifiers"
stanford_tagger = StanfordPOSTagger('english-bidirectional-distsim.tagger')
Hope it will help!

keyring module is not included while packaging with py2exe

I am making an app using python 2.7 on windows and keyring-3.2.1 . In my python code on eclipse, I used
import keyring
keyring.set_password("service","jsonkey",json_res)
json_res= keyring.get_password("service","jsonkey")
is working fine as I am storing json response in keyring. But, when I converted python code into exe by using py2exe, it shows import error keyring while making dist. Please suggest how to include keyring in py2exe.
Traceback (most recent call last):
File "APP.py", line 8, in <module>
File "keyring\__init__.pyc", line 12, in <module>
File "keyring\core.pyc", line 15, in <module>
File "keyring\util\platform_.pyc", line 4, in <module>
File "keyring\util\platform.pyc", line 29, in <module>
AttributeError: 'module' object has no attribute 'system'
platform_.py code is :
from __future__ import absolute_import
import os
import platform
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
platform.py code is:
import os
import sys
# While we support Python 2.4, use a convoluted technique to import
# platform from the stdlib.
# With Python 2.5 or later, just do "from __future__ import absolute_import"
# and "import platform"
exec('__import__("platform", globals=dict())')
platform = sys.modules['platform']
def _data_root_Windows():
try:
root = os.environ['LOCALAPPDATA']
except KeyError:
# Windows XP
root = os.path.join(os.environ['USERPROFILE'], 'Local Settings')
return os.path.join(root, 'Python Keyring')
def _data_root_Linux():
"""
Use freedesktop.org Base Dir Specfication to determine storage
location.
"""
fallback = os.path.expanduser('~/.local/share')
root = os.environ.get('XDG_DATA_HOME', None) or fallback
return os.path.join(root, 'python_keyring')
# by default, use Unix convention
data_root = globals().get('_data_root_' + platform.system(), _data_root_Linux)
The issue you're reporting is due to an environment that contains invalid modules, perhaps from an improper installation of one version of keyring over another. You will want to ensure that you've removed remnants of the older version of keyring. In particular, make sure there's no file called keyring\util\platform.* in your site-packages.
After doing that, however, you'll encounter another problem. Keyring loads its backend modules programmatically, so py2exe won't detect them.
To work around that, you'll want to add a 'packages' declaration to your py2exe options to specifically include the keyring.backends package. I invoked the following setup.py script with Python 2.7 to convert 'app.py' (which imports keyring) to an exe:
from distutils.core import setup
import py2exe
setup(
console=['app.py'],
options=dict(py2exe=dict(
packages='keyring.backends',
)),
)
The resulting app.exe will import and invoke keyring.

How to convert text to speech in python

I would like to now how to convert text to speech in python.
In .NET i used
Dim SAPI
Msg = 'Hi this is a test'
SAPI = CreateObject("sapi.spvoice")
SAPI.Speak(Msg)
You can achieve it by pyttsx module. it uses default MS speech recognition system.
import pyttsx
engine = pyttsx.init()
engine.say("Your Message")
engine.runAndWait()
I know its real late to answer here, But I thought I would post here since I have solution based on TTS conversion using SAPI in python, which was OP's original question.
This may be useful for anyone else looking for solution using SAPI in python.
from win32com.client import constants, Dispatch
Msg = "Hi this is a test"
speaker = Dispatch("SAPI.SpVoice") #Create SAPI SpVoice Object
speaker.Speak(Msg) #Process TTS
del speaker #Delete speaker object and free up memory
import pyttsx3
speaker=pyttsx3.init()
speaker.say("Your message")
speaker.runAndWait()
# pip install pywin32
# pip install pyttsx3
import pyttsx3
pyttsx3.speak('Hello Woeld')
You can do it by using the gTTS module. It converts the text to speech.
The second module you have to use is playsound to play the converted text.
from gtts import gTTS #pip install gtts
import playsound #pip install playsound
import os
my_aud = gTTS("hello how are you") #converts the text into speech
my_aud.save('demo.mp3') #save the file with .mp3 extension
playsound('demo.mp3') #to play it
os.remove('demo.mp3')
Here is Male's and Female's voices function created by myself.
Just define a file name and save it.
Now you can import it into another file and reuse it again and again.
pip install pyttsx3
import pyttsx3
def femaleVoice(text):
print("Program : "+text)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[-1].id)
engine.say(text)
engine.runAndWait()
def maleVoice(text):
print("Program : "+text)
pyttsx3.speak(text)
femaleVoice("There we go.")#Text
maleVoice("There we go.")
If you want access to a ton of voices. We have over 500.
Here's a snippet
python
import apiaudio
import os
apiaudio.api_key = os.environ['APIKEY']
first_track = apiaudio.Orchestrator.create_audio(scriptText="Hello World my first audio track",
voice="Ryan",
soundTemplate="jakarta")
print(first_track)
You just need a FREE api key. Have a look at http://www.api.audio

Categories