Python gTTS not accepting strings within variables - python

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)

Related

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

i tried to make video editor which takes videos from pc using moviepy python but i am facing some issues and i am new to this

def open_file():
b_text.set("Loading")
files = askopenfile(initialdir = ".",parent=root ,title="choose a video",filetype=[("Video Files","*.mp4")])
if files:
print("File was loaded")
files.without_audio().preview()
This is the error i am facing
Traceback (most recent call last):
File "C:\Users\felix\anaconda3\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "c:/Users/felix/Desktop/video editor/new.py", line 27, in open_file
b=Button(root,textvariable=b_text,relief=GROOVE,bg="#232323",fg="white", command=open_file)
AttributeError: '_io.TextIOWrapper' object has no attribute 'without_audio'
You must execute VideoFileClip before previewing.
The method askopenfile selects a file.
Execute clip = VideoFileClip(file.name) for creating VideoFileClip object.
Then you can execute clip.without_audio().preview().
For more details see: MoviePy – Previewing a Video Clip.
When executing the code, I was getting an error message:
clip.preview requires Pygame installed
I has to install pygame.
Here is a code sample for selecting and previewing a video file:
from tkinter.filedialog import askopenfile
from moviepy.editor import *
file = askopenfile(initialdir = ".", title="choose a video", filetype=[("Video Files","*.mp4")])
if file:
print("File was loaded")
# https://www.geeksforgeeks.org/moviepy-previewing-a-video-clip/
# Loading video file
clip = VideoFileClip(file.name)
# previewing the clip at fps = 10
clip.without_audio().preview(fps=10)
Note:
Since the example is "stand alone" application, I had to remove the parent argument (but you should keep the parent=root argument).

GTTS module error, ImportError: cannot import name gTTS

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.

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")

Converting rtf to pdf using python

I am new to the python language and I am given a task to convert rtf to pdf using python. I googled and found some code- (not exactly rtf to pdf) but I tried working on it and changed it according to my requirement. But I am not able to solve it.
I have used the below code:
import sys
import os
import comtypes.client
#import win32com.client
rtfFormatPDF = 17
in_file = os.path.abspath(sys.argv[1])
out_file = os.path.abspath(sys.argv[2])
rtf= comtypes.client.CreateObject('Rtf.Application')
rtf.Visible = True
doc = rtf.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=rtfFormatPDF)
doc.Close()
rtf.Quit()
But its throwing the below error
Traceback (most recent call last):
File "C:/Python34/Lib/idlelib/rtf_to_pdf.py", line 12, in <module>
word = comtypes.client.CreateObject('Rtf.Application')
File "C:\Python34\lib\site-packages\comtypes\client\__init__.py", line 227, in CreateObject
clsid = comtypes.GUID.from_progid(progid)
File "C:\Python34\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
_CLSIDFromProgID(str(progid), byref(inst))
File "_ctypes/callproc.c", line 920, in GetResult
OSError: [WinError -2147221005] Invalid class string
Can anyone help me with this?
I would really appreciate if someone can find the better and fast way of doing it. I have around 200,000 files to convert.
Anisha
I used Marks's advice and changed it back to Word.Application and my source pointing to rtf files. Works perfectly! - the process was slow but still faster than the JAVA application which my team was using. I have attached the final code in my question.
Final Code:
Got it done using the code which works with Word application :
import sys
import os,os.path
import comtypes.client
wdFormatPDF = 17
input_dir = 'input directory'
output_dir = 'output directory'
for subdir, dirs, files in os.walk(input_dir):
for file in files:
in_file = os.path.join(subdir, file)
output_file = file.split('.')[0]
out_file = output_dir+output_file+'.pdf'
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
If you have Libre Office in your system, you got the best solution.
import os
os.system('soffice --headless --convert-to pdf filename.rtf')
# os.system('libreoffice --headless -convert-to pdf filename.rtf')
# os.system('libreoffice6.3 --headless -convert-to pdf filename.rtf')
Commands may vary to different versions and platforms. But this would be the best solution ever I had.

Categories