I am attempting to write to a text file. It just seems to fail every time. I can write .write("test") but writing the google transcription output to file seems to fail.
Any advice would be greatly appreciated.
import speech_recognition as sr
from os import path
from pprint import pprint
audio_file = path.join(path.dirname(path.realpath(__file__)), "RobertP.wav")
r = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
audio = r.record(source)
try:
txt = r.recognize_google(audio, show_all=True)
pprint (txt)
except:
print("Didn't work.")
try:
f = open("tester.txt", "w+")
f.write(txt)
f.close()
except:
print("Couldn't write to file")```
It Looks like txt is not a string. You can try to convert it to a string with str(txt).
btw:
It's better to remove the try/except for testing reasons to get the error. After the program works you can add it again,.
Related
I tried to use the following code to recognize a 5 min audio
import speech_recognition as sr
from os import path
from pydub import AudioSegment
import wavio
from scipy.io import wavfile
test_file = open("test.txt", "w+")
sound = AudioSegment.from_mp3("001.mp3")
sound.export("001.wav", format="wav")
AUDIO_FILE = "001.wav"
r = sr.Recognizer()
with sr.AudioFile(AUDIO_FILE) as source:
audio = r.listen(source)
try:
text = r.recognize_google(audio)
print(text)
test_file.write(text+". ")
except:
print('Run again')
But it only return the very first couple words: "listening diagnostic pretest page 143", do you guys know why it didn't recognize the whole audio?
How can I convert sound from website to a text? When I click the button in a website is play a sound but my problem is how can I convert it to a text without using microphone just the website and the python.
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile('my.wav') as source:
audio_text = r.listen(source)
try:
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
print(text)
except:
print('Sorry.. run again...')
Here is my code but I don't have a wav file just the voice coming from the website what I trying to convert.
Example of what I trying to make
when I click the button in the website it plays hello and the python will get the sound from the website and print it.
Try downloading the file first, I don't know the location or format of your audio file so this is a guess:
EDIT: added a url to a real audio file and it works, it fails with poor quality audio though
import requests
import speech_recognition as sr
def download(url, path):
response = requests.get(url) # get the response of the url
with open(path, 'wb') as file: # create the file
file.write(response.content) # write response contents to the file
def transcribe(path):
r = sr.Recognizer()
with sr.AudioFile(path) as source:
audio_text = r.record(source)
text = r.recognize_google(audio_text)
print('Converting audio transcripts into text ...')
return text
audio_url = 'https://google.github.io/tacotron/publications/parrotron/audio/norm_vctk/03_norm_input.wav'
audio_path = './speech.wav'
download(audio_url, audio_path)
audio_text = transcribe(audio_path)
print(audio_text)
Output
Converting audio transcripts into text ...
this is a huge confidence boost
speech to text in python using audio file.
This is answer for this question.
You have install pyaudio and SpeechRecognition.
and audio file format should be in WAV file.
Its code for speech to text (input from audio file).
import speech_recognition as sr
r = sr.Recognizer()
audio = 'trial.wav'
with sr.AudioFile(audio) as source:
audio = r.record(source)
print ('Done!')
try:
text = r.recognize_google(audio)
print (text)
except Exception as e:
print (e)
If you want different languages to be converted. You can use below code.
import speech_recognition as sr
r = sr.Recognizer()
with sr.AudioFile('Audio.wav') as source:
audio = r.listen(source)
try:
text = (r.recognize_google(audio, language="IN_HI"))
print('working on...')
print(text)
except:
print('Sorry.. run again..')
I am trying to convert an Excel spreadsheet to PDF using Python and the comtypes package using this code:
import os
import comtypes.client
FORMAT_PDF = 17
SOURCE_DIR = 'C:/Users/IEUser/Documents/jscript/test/resources/root3'
TARGET_DIR = 'C:/Users/IEUser/Documents/jscript'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'spreadsheet1.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'spreadsheet1.pdf')
doc = app.Workbooks.Open(infile)
doc.SaveAs(outfile, FileFormat=FORMAT_PDF)
doc.Close()
app.Quit()
This script above runs fine and the pdf file is created, but when I try to open it I get the error "The file cannot be opened - there is a problem with the file format" (but after closing this error dialog it is actually possible to preview the pdf file). I have tried a similar script to convert Word documents to pdfs and this worked just fine.
Any ideas on how I can resolve this problem with the file format error?
Found a solution - this seems to be working:
import os
import comtypes.client
SOURCE_DIR = 'C:/Users/IEUser/Documents/jscript/test/resources/root3'
TARGET_DIR = 'C:/Users/IEUser/Documents/jscript'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'spreadsheet1.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'spreadsheet1.pdf')
doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()
app.Quit()
This link may also be helpful as an inspiration regarding the arguments to the ExportAsFixedFormatfunction: Document.ExportAsFixedFormat Method (although some of the values of arguments have to be modified a bit).
You need to describe ExportAsFixedFormat(0,outputfile) to save workbook in pdf format. The solution from http://thequickblog.com/convert-an-excel-filexlsx-to-pdf-python/ works for me.
from win32com import client
import win32api
input_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample.xlsx'
#give your file name with valid path
output_file = r'C:\Users\thequickblog\Desktop\Python session 2\tqb_sample_output.pdf'
#give valid output file name and path
app = client.DispatchEx("Excel.Application")
app.Interactive = False
app.Visible = False
Workbook = app.Workbooks.Open(input_file)
try:
Workbook.ActiveSheet.ExportAsFixedFormat(0, output_file)
except Exception as e:
print("Failed to convert in PDF format.Please confirm environment meets all the requirements and try again")
print(str(e))
finally:
Workbook.Close()
app.Exit()
I want to create a python script which finds an expression in a text.
If it succeeds, then print 'expression found'.
My text file is named "file_id_ascii"; it comes from a link named "clinical_file_link".
import csv
import sys
import io
file_id_ascii =
io.open(clinical_file_link, 'r',
encoding='us-ascii', errors='ignore')
acc = 'http://tcga.nci/bcr/xml/clinical/acc/'
if acc in file_id_ascii:
print('expression found')
That code doesn't work...what's wrong?
if 'http://tcga.nci/bcr/xml/clinical/acc/' \
in open('clinical_file_link.txt').read():
print "true"
... works if your file has small content
It doesn't work because you are not parsing the XML.
Check this thread for more info about parsing XML.
If it is indeed a text file you might edit it like this:
if acc in open(clinical_file_link.txt).read():
print('expression FOUND')
EDIT: This solution wont work if files are big. Try this one:
with open('clinical_file_link.txt') as f:
found = False
for line in f:
if acc in line:
print('found')
found = True
if not found:
print('The string cannot be found!')