GTTS module error, ImportError: cannot import name gTTS - python

I am trying to make a Voice assistant in python using this code
import os
from gtts import gTTs
import time
import playsound
import speech_recognition as sr
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
def get_audio():
r = sr.Recognizer()
with sr.Microphone() as source:
audio = r.listen(source)
said = ""
try:
said = r.recognize_google(audio)
print(said)
except Exception as e:
print("Exception: " + str(e))
return said
text = get_audio()
if "who are you" in text:
speak(" I am Friday the virtual assistant")
And when i run it, it shows this error ImportError: cannot import name gTTS
Any help would be amazing :)
Edit:I have changed it to gTTS and still get ImportError: cannot import name gTTS

Try replacing
from gtts import gTTs
with
from gtts import gTTS
(Note the capital S)

I also got this problem once because i named my python file as gtts.py
so i changed the name of the file to something else and it stopped giving error.

First you have to install the gtts module with this command by going to the terminal and type following line:
pip install gTTS
After you install this, import like this:
from gtts import gTTS

I got the same error. Just make sure you are using the right python Interpreter.

Related

Python smart voice assistant with using a JSON file

I was trying to create a voice assistant using python... but my code is showing some weird texts when I run it... down below is my code
from email.mime import audio
from logging.config import listen
import re
from neuralintents import GenericAssistant
import speech_recognition
import sys
import pyttsx3 as tts
recognizer = speech_recognition.Recognizer()
speaker = tts.init()
speaker.setProperty('rate',150)
def create_note():
global recognizer
speaker.say("What do you want to say?")
speaker.runAndWait()
done=False
while not done:
try:
with speech_recognition.Microphone() as mic:
recognizer.adjust_for_ambient_noise(mic, duration=0.2)
audio= recognizer.listen(mic)
note = recognizer.recognize_google(audio)
note = note.lower()
speaker.say("choose a file name")
speaker.runAndWait
recognizer.adjust_for_ambient_noise(mic, duration=.2)
audio = listen(mic)
filename = recognizer.recognize_google(audio)
filename = filename.lower()
with open(filename,'w' ) as f:
f.write(note)
done= True
speaker.say={f"I saved the note {filename}"}
speaker.runAndWait()
except speech_recognition.UnknownValueError:
recognizer = speech_recognition.Recognizer()
speaker.say("I dont got that, please say it again")
speaker.runAndWait()
mappings = {'greeting': create_note}
assitant = GenericAssistant('intents.json',intent_methods=mappings)
assitant.train_model()
I expect it to get the input from the mic then go through a JSON file and say the next thing according to the JSON file....
here is the contents of the JSON file
JSON FILE

Google's text-to-speech fails to connect

I am getting an error
this is the code i wrote
import speech_recognition as sr
from gtts import gTTS
import os
import time
import playsound
def speak(text):
tts = gTTS(text=text, lang="en")
filename = "voice.mp3"
tts.save(filename)
playsound.playsound(filename)
speak("hello Aneeqa")
this is the error
File "C:\Users\Ben\AppData\Local\Programs\Python\Python310\lib\site-packages\gtts\tts.py", line 281, in stream
raise gTTSError(tts=self)
gtts.tts.gTTSError: Failed to connect. Probable cause: Unknown
Process finished with exit code 1

Python Speech Recognition: AttributeError: module 'speech_recognition' has no attribute 'record'

I'm getting this error 'AttributeError: module 'speech_recognition' has no attribute 'record'' in the below code. It is not because my filename is Speech_Recognition, i've tried that bug fix. Any ideas?
# -*- coding: utf-8 -*-
import speech_recognition as sr
import pyaudio as pa
import time as t
mic = sr.Microphone()
inp = sr.AudioFile('data.wav')
with inp as source:
audio = sr.record(source)
You need to add another variable:
r = sr.Recognizer()
Then change sr.record(source) to r.record(source)
I hope this helped!

Overwrite pre-existing .mp3 file in Python using gtts

I have a constraint with my syntax. I just tried python some time ago and I started it from AI. I make a bot like Jarvis to help me like opening google or youtube. From the tutorial available in Pythonspot.com it shows for Ubuntu tutorial but I use Windows. And there are some tools or plugins that do not work in windows is mpg321. I have found a replacement with mixer.music to play the sound of the AI. This works but I have constraints on the second sound, ie i make the first sound with audio.mp3 and it works then when my second voice uses the same filename ie audio.mp3 and i have constraints like this
Traceback (most recent call last):
File "D:\#AI Projects\Jarvis\Jarvis.py", line 71, in
jarvis(data)
File "D:\#AI Projects\Jarvis\Jarvis.py", line 53, in jarvis speak(ctime())
File "D:\#AI Projects\Jarvis\Jarvis.py", line 17, in speak tts.save("audio.mp3")
File "C:\Users\inialdan\AppData\Local\Programs\Python\Python36\lib\site-packages\gtts\tts.py",
line 110, in save
with open(savefile, 'wb') as f: PermissionError: [Errno 13] Permission denied: 'audio.mp3'
This is my code
#!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from time import ctime
import time
import os
import subprocess
from gtts import gTTS
from pygame import mixer
def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
tts.save("audio.mp3")
mixer.init()
mixer.music.load('D:/#AI Projects/Jarvis/audio.mp3')
mixer.music.play()
def recordAudio():
r = sr.Recognizer()
with sr.Microphone() as source:
print("Try to say something!")
audio = r.listen(source)
data = ""
try:
data = r.recognize_google(audio)
print("You said : " + data)
except sr.UnknownValueError:
print("I'm Sorry, i couldn't understand what you mean ...")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
return data
def jarvis(data):
CHROME = os.path.join('C:\\', 'Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe')
if "jarvis" in data:
speak("Yes, sir ?")
if "what is your name" in data:
speak("You can call me, Jarvis")
if "where do you leave" in data:
speak("In your heart.")
if "how are you" in data:
speak("I am fine")
if "what time is it" in data:
speak(ctime())
if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on Aldan, I will show you where " + location + " is.")
os.system('taskkill /im chrome.exe')
subprocess.call([CHROME, "https://www.google.nl/maps/place/" + location + "/&"])
if "open" in data:
data = data.split(" ")
application = data[1]
speak("Hold on Aldan, I will show you " + application)
os.system('taskkill /im chrome.exe')
subprocess.call([CHROME, "https://www." + application + ".com"])
time.sleep(2)
speak("Hi Aldan, How may I assist you?")
while 1:
data = recordAudio()
jarvis(data)
I have tried it with os.remove (); to remove the audio.mp3 and rewrite it. but still failed
I have modified Speak method with the help of TemporaryFile.Click on the icon to check the Code
from googletrans import Translator
import pygame, time
import tempfile
from gtts import gTTS
from pygame import mixer
from tempfile import TemporaryFile
def speak(text, lang='en'):
"""Text to speech. For funp."""
try:
translator = Translator()
tts = gTTS(text=translator.translate(text, dest=lang).text, lang=lang)
mixer.init()
sf = TemporaryFile()
tts.write_to_fp(sf)
sf.seek(0)
mixer.music.load(sf)
mixer.music.play()
except Exception:
raise
Just create a second def that removes the filename and run that command after your speak()
def complete():
os.remove('audio.mp3')
speak("blah blah")
complete()
I did this, it worked. You may have to guess the length of the sound. For mine, 2 sec is long enough.
voice = gtts.gTTS(item)
voice.save("temp.mp3")
sound = SoundLoader.load("temp.mp3")
sound.play()
time.sleep(2)
sound.stop()
os.remove("temp.mp3")

Python gTTS not accepting strings within variables

I am writing a python script to scan a photo which contains text with google vision OCR, then use Google gTTS to speak the text. Here is the code:
#BookrBasic
from os import system
from time import sleep
from pygame import mixer
from gtts import gTTS
import subprocess
def tts(speech):
tts = gTTS(text=speech, lang='en')
tts.save("/tmp/text.mp3")
subprocess.Popen(['mpg123', '-q', '/tmp/text.mp3']).wait()
def ocr(file):
out = system('python3 ~/bookrbasic/ocr.py <KEY GOES HERE> ' + file)
return out
text = ocr("~/bookrbasic/photos/canada4.jpg")
tts(text)
This is the error I recieve:
Traceback (most recent call last):
File "BookrBasic.py", line 20, in <module>
tts(text)
File "BookrBasic.py", line 11, in tts
tts = gTTS(text=speech, lang='en')
File "/usr/local/lib/python2.7/dist-packages/gtts/tts.py", line 72, in __init__
raise Exception('No text to speak')
Exception: No text to speak
Does anyone know what the issue is here?
Thanks in advance.
Never mind, I managed to fix it by writing to a file in tmp.
Here is the new code, in case anyone is having a similar issue:
#BookrBasic
import os
from os import system
from time import sleep
from pygame import mixer
from gtts import gTTS
import subprocess
def tts(speech):
tts = gTTS(text=speech, lang='en-uk')
os.mkfifio('/tmp/fifo')
tts.save("/tmp/text.mp3")
subprocess.Popen(['mpg123', '-q', '/tmp/text.mp3']).wait()
def ocr(file):
system('python3 ~/bookrbasic/ocr.py <KEY GOES HERE> ' + file + ' > /tmp/text.txt')
with open ("/tmp/text.txt", "r") as myfile:
out=myfile.read()
return out
text = ocr("~/bookrbasic/photos/canada4.jpg")
tts(text)

Categories