Our script which uses the following libraries
import os
import sys
from random import sample as rand_sample
import PySimpleGUI as sg
from gtts import gTTS
from Levenshtein import ratio
from cryptography.fernet import Fernet
import platform
import webbrowser
from hashlib import sha1
from getpass import getuser
from socket import gethostname
import clipboard
import wavio
import sounddevice as sd
import soundfile as sf
import speech_recognition as sr
import wave
from playsound import playsound
from difflib import get_close_matches
import json
import urllib.request
from ssl import _create_unverified_context
class audio():
def __init__(mic,path):
mic.fs=44100
mic.path=path
def recordAudio(mic,time):
recording=sd.rec(int(time*mic.fs),samplerate=mic.fs,channels=1)
sd.wait()
return recording
def save(mic,filename,recording):
wavio.write(mic.path+filename,recording, mic.fs, sampwidth=2)
def play(mic,filename):
data,fs = sf.read(mic.path+filename,dtype='float32')
sd.play(data,fs)
status=sd.wait()
def getText(mic,filename): #use google speech recongition to convert
# print (mic,filename)
r = sr.Recognizer()
hellow=sr.AudioFile(mic.path+filename)
with hellow as source:
r.adjust_for_ambient_noise(source, duration = 1)
audio = r.record(source)
try:
s = r.recognize_google(audio)
return(s)
except:
return ('error reading speech...')
return ""
Can access microphone when run the app bundle via terminal (Permission is granted for it screenshot attached)
however when we package it using pyinstaller using this command
pyinstaller --noupx --onedir --onefile --windowed interview.spec interview.py
It is successfully converted into an app and we can launch it with double click. But it cannot access micriphone, nor does it asks for permission. Do we have to add some specific python snippet to ask for permission? Looking forward to your suggestions and help as i am clueless in this.
System:
macOS Big Sur
Version 11.5.2
In the end just ended up writing a script and putting an icon on it, so user can double click on it and start using the app. Though in Big Sur you have to do chmod 755 to it in almost every new pc it is copied to.
#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"
./interview.app/Contents/MacOS/interview
Related
I am a PHP developer and was tasked with writing a Python script. I am lost.
Short summary:
My client wants to log which directory and file, on which URL was visited by which IP
My code:
import sys
import os
import io
import os.path
import socket
import requests
directory = os.getcwd()
ip = os.environ["REMOTE_ADDR"]
hostname = socket.gethostname()
i = socket.gethostbyname(hostname)
If I may ask two questions:
How do I run Python on Cpanel? I have uploaded the file example.py and navigated to the file, but the page only displays the code.
On the above code (in online code testers), I get an error: KeyError: 'REMOTE_ADDR'. What am I doing wrong
I'm trying to write a program that can analyse Mass Spectrometry .mzml files for my Chemistry project at university. I'm new to programming. I have some code that allows the user to browse a file, but the code only prints the file path.
import Tkinter
import tkFileDialog
def main():
Tkinter.Tk().withdraw()
in_path = tkFileDialog.askopenfilename(filetypes=[("mzml file","*.mzML")])
print in_path
if __name__ == "__main__":
main()
How would I change it so that the file chosen is imported into the code and is able to be read so that I can take information from it (Mass spectra, chromatograms and the like)?
filepath is the file-browser file. I want to import the file into something like this using PyOpenMS package:
import pyopenms
from pyopenms import *
import numpy as np
import filepath
filepath.main()
exp = pyopenms.MSExperiment()
pyopenms.MzMLFile().load('**in_path**', exp)
I know that trying to load in_path is wrong, but I'm not sure what to put!
I want to make WAVE files by using gTTS module.
I downloaded gTTS module from https://pypi.python.org/pypi/gTTS`
I could make some files by it and stream the sounds by clicking these files.
But I want to know what kind of files can gTTS save?
Here is the sample code:
import tempfile
from gtts import gTTS
tts = gTTS(text='hello', lang='en', slow=True)
tts.save("hello.wav")
f = tempfile.TemporaryFile()
tts.write_to_fp(f)
f.close()
When I used the soundfile with my code, I couldn't make it.
from PySide import QtGui
from PySide import QtCore
import sys
import os
class HelloSpeaker(QtGui.QPushButton):
def __init__(self,parent=None):
super(HelloSpeaker,self).__init__(parent=None)
self.setText("Stream")
self.connect(self,QtCore.SIGNAL("clicked()"),self.play_sound)
def play_sound(self):
sound = QtGui.QSound(os.getcwd()+"hello.wav")
sound.play(os.getcwd()+"hello.wav")
def main():
try:
QtGui.QApplication([])
except Exception as e:
print(28,e)
hello = HelloSpeaker()
hello.show()
sys.exit(QtGui.QApplication.exec_())
if __name__ == "__main__":
main()
Yes, I found out some QSound-questions in stack overflow.
QSound don't work because of some unknown reasons.
For example:
QSound::play("soundpath") call works but a QSound object doesn't
Playing sound with Pyqt4 and QSound
QT5 QSound does not play all wave files
Other persons are bothered.
But I don't ascribed to QSound and I doubt that gTTS can't make .wav files.
because
import wave
wf = wave.open("hello.wav", "rb")
result:
wave.Error: file does not start with RIFF id
I heard this error shows this file is not a wave file.
So I wonder that gTTS don't make ".wav" files.
(But I can play it by ITunes , other players.)
Can gTTS make "mp3" files only?
environment:
python 3.6.3 pyside1.2.4
gTTS only saves the bytes directly without doing any conversion, and these bytes are encoded in mp3, you can verify it by checking the source code:
....
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=InsecureRequestWarning)
r = requests.get(self.GOOGLE_TTS_URL,
params=payload,
headers=headers,
proxies=urllib.request.getproxies(),
verify=False)
if self.debug:
print("Headers: {}".format(r.request.headers))
print("Request url: {}".format(r.request.url))
print("Response: {}, Redirects: {}".format(r.status_code, r.history))
r.raise_for_status()
for chunk in r.iter_content(chunk_size=1024): # write the bytes directly
fp.write(chunk)
...
below is the code for downloading youtube files providing URL, but at present the URL is static, I'm trying to make it dynamic so that user can put URL at runtime. and secondly, I'm also trying to set the path where to save, file by the user but, somehow not able to do
(I'm working on python3 idle with windows)
from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://youtu.be/zhWDdy_5v2w'])
print("DONE!")
This is how it should work:
from __future__ import unicode_literals
import sys
import youtube_dl
import urllib
import shutil
ydl_opts = {'outtmpl': '~/Documents/file_name'}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(sys.argv[1:])
print("DONE!")
Usage: youtube_script.py youtube_url
You can use it like this . Though I have not tested the code but it should work. If i correctly understand, you mean the user can set the url when starting the python script ?, then this is how it should be done or you can take the input in a string and then provide it to the ydl.download function.
I have a python script that takes the (latex source) content of a google doc and creates a pdf.
This is the function I use for the pdf:
# -*- coding: utf-8 -*-
#!/usr/bin/python
"""One of the main activiating files of IMPS - this downloads all the files in a directory, creates the input.tex file and archives them a tar file
TODO
Before we send to stackoverflow we should make sure that everthing is in a function and that the If __main__ trigger is working
I'd also like to have doc strings for all of the methods
"""
import os
import glob
import tarfile
import time
import datetime
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import urlparse
import argparse
import re
def generate_pdf(filename,destination=""):
"""
Genertates the pdf from string
from http://stackoverflow.com/q/19683123/170243
"""
import subprocess
import shutil
current = os.getcwd()
this_dir=os.path.dirname(os.path.realpath(__file__))
os.chdir(this_dir+"/latex")
proc=subprocess.Popen(['pdflatex',filename+'.tex'],stdout=subprocess.PIPE)
# subprocess.Popen(['pdflatex',tex])
temp=proc.communicate()
#Have to do it twice so that the contents pages are right
proc=subprocess.Popen(['pdflatex',filename+'.tex'],stdout=subprocess.PIPE)
temp=proc.communicate()
shutil.copy(filename+'.pdf',"../../live/"+destination+filename+ str(datetime.datetime.now()).replace(".", "-").replace(":", "_") + ".pdf")
trace_file = open("../../live/"+destination+"trace.txt", "w")
print >>trace_file, temp[0]
print >>trace_file, temp[1]
trace_file.close()
os.chdir(current)
Everything runs fine if the latex has NO errors, but if there is a problem, the function hands and nothing gets done. What I want is that problems are noted and exported into the trace. Any ideas what's going wrong?
When it encounters errors, pdflatex asks the user about how to proceed, so your script "hangs" because it is expecting input. Use pdflatex -interaction=nonstopmode -halt-on-error. See this TeX StackExchange question.
I think what you are missing is that you need to also need to setup a pipe for STDERR. This will let you see the error messages from pdflatex. You could also try explicitly setting the buffer size to zero when calling Popen.
self.child = subprocess.Popen(command
,bufsize=0
,stdout=subprocess.PIPE
,stderr=subprocess.PIPE)