def path(operation,file_names,folder): script_dir = os.path.dirname(folder) if file_names == []: rel_path="" else: rel_path = file_names[0] abs_file_path = os.path.join(script_dir,rel_path) #checking path validity if abs_file_path == "/" : tts.convert_text_n_speak("Sorry but Path is invalid") #checking file path exists or not elif os.path.exists(abs_file_path) : if operation==1: open_file(abs_file_path) elif operation == 3: delete_file(abs_file_path) elif operation==4: rename_file(script_dir,file_names[0],file_names[1]) elif operation == 6: list_files(script_dir) else: if operation == 2: create_file(abs_file_path) else: tts.convert_text_n_speak("Sorry file not found")
def refine_path(path): path = "/" + path if path.find('home') != -1: #getting user name to get home directory path out = sp.run(['echo $USER'], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) user = out.stdout.decode().replace("\n", "") path = path.replace("home", "home/" + user) elif path.find('current', 0) != -1: #getting current directory path out = sp.run(['pwd'], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) curr_dir = out.stdout.decode().replace("\n", "") path = path.replace("/current", curr_dir) #checking dir location exixts or not if not os.path.isdir(path): tts.convert_text_n_speak( "Sorry Location is invalid please check and try again") return print(path) return path
def search_google(filtered_query): result = 0 # keywords to remove remv_keywords = [ 'search', 'google', 'on', 'about', 'the', 'find', 'ok', 'do', 'a' ] # final list of words to be searched final_key = [] # append words other than remv_keywords to final_key for word in filtered_query: if word in remv_keywords: pass else: final_key.append(word) # if no keyword given ask for keyword if final_key == []: tts.convert_text_n_speak("What should i search") user_input = sr.get_audio_to_text() user_input = user_input.lower().strip().split() result = search_google(user_input) # to avoid ruuning 2 times if result == 0: # string of search words search_words = str() for word in final_key: search_words = search_words + ' ' + word print('searching for ' + search_words) webbrowser.open_new_tab('https://www.google.com/search?q=' + search_words) tts.convert_text_n_speak("Search results ready") result = 1 return result
def remove_dir(filtered_query): abs_path = get_dir_path(filtered_query) #checking directory exists or not if not os.path.isdir(abs_path): tts.convert_text_n_speak("Please Check Directory Does Not Exists") return tts.convert_text_n_speak("Are you sure? You want to remove directory ?") user_input = sr.get_audio_to_text() user_input = user_input.lower().strip().split() if "yes" in user_input: #creating command create_dir_cmd = 'rm -r ' + abs_path #creating dir out = sp.run([create_dir_cmd], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) if out.returncode == 0: tts.convert_text_n_speak("Directory Successfully Removed") else: tts.convert_text_n_speak( "Unable to Remove directory. Please try again later") sleep(5) else: tts.convert_text_n_speak("Aage se dhayan rakhna")
def get_dest_path(filtered_query, abs_path): dir_name_index = -1 desti_path = "" if len(filtered_query) == 1: dir_name_index = 0 elif "to" in filtered_query: dir_name_index = filtered_query.index("to") + 1 if dir_name_index == -1: tts.convert_text_n_speak("Please Specify new directory name") user_input = sr.get_audio_to_text() if user_input != None: user_input_split = user_input.lower().strip().split() #calling function to create path desti_path = get_dest_path(user_input_split, abs_path) else: splash_index = abs_path.rfind('/') desti_path = abs_path[0:splash_index + 1] + filtered_query[dir_name_index] print(desti_path) return desti_path
def get_dir_name(filtered_query): if len(filtered_query) == 1: dir_name = filtered_query[0] else: split_words = ['in', 'of', 'under'] dir_name = "" name_index = -1 if "name" in filtered_query: name_index = filtered_query.index("name") elif "named" in filtered_query: name_index = filtered_query.index("named") elif "directory" in filtered_query: name_index = filtered_query.index("directory") elif "folder" in filtered_query: name_index = filtered_query.index("folder") #storing dir name if name_index + 1 < len(filtered_query): dir_name = filtered_query[name_index + 1] #dir name not given if dir_name in split_words or name_index == -1: tts.convert_text_n_speak("Please tell directory name") user_input = sr.get_audio_to_text() if user_input != None: user_input_split = user_input.lower().strip().split() #calling function to create path dir_name = get_dir_name(user_input_split) return dir_name
def dir_path(filtered_query): path = "" split_words = ['in', 'of', 'under', 'from'] #removing folder or directory word in query for word in filtered_query: if word == "folder" or word == "directory": filtered_query.remove(word) #creating path by parsing list from start_index i.e. index of in/of/under for word in filtered_query: if word in split_words: dir_index = filtered_query.index(word) + 1 if dir_index < len(filtered_query): dir_name = filtered_query[dir_index] path = dir_name + "/" + path #directory path not given if path == "" or path == None: tts.convert_text_n_speak("Please tell directory location") user_input = sr.get_audio_to_text() if user_input != None: user_input_split = user_input.lower().strip().split() #calling function to create path path = dir_path(user_input_split) return path
def get_audio_to_text(): audio = listen_from_microphone() text_frm_audio = "" print("Converting to text") #passing audio to recongnizer #recognizer method for recognizing speech from audio source #using google web speech api - requires internet conn./ try: text_frm_audio = r.recognize_google(audio) print("You said : ", text_frm_audio) except sr.RequestError: #Api Unreachable tts.convert_text_n_speak("Please Check internet Connection") return except sr.UnknownValueError: #Audio Can Not be Detected tts.convert_text_n_speak("Audio is Not Recognizable") if text_frm_audio == "" or text_frm_audio == None: text_frm_audio = get_audio_to_text() return text_frm_audio #get_audio_to_text()
def execute_install_query(filtered_query): #filtering python library query if "python" in filtered_query: print("Installing") indx = filtered_query.index('library') library_name = filtered_query[indx + 1] #install library cmd_output = ce.execute_cmd('pip3 install ' + library_name) if cmd_output.returncode != 0: tts.convert_text_n_speak("Sorry Library Not Found") else: tts.convert_text_n_speak("Installed " + library_name + " Library") #installing ubuntu packages else: indx = filtered_query.index('install') pckg_name = filtered_query[indx + 1] #install library tts.convert_text_n_speak("Please Enter Password") cmd_output = ce.execute_cmd('sudo apt install ' + pckg_name) if cmd_output.returncode != 0: tts.convert_text_n_speak("Unable to install service") else: tts.convert_text_n_speak("Installed " + pckg_name + " Library")
def rename_file(folder,file1,file2): path1 = os.path.join(folder,file1) f1 = open(path1,'r') data = f1.read() path2 = os.path.join(folder,file2) f2 = open(path2,'w') f2.write(data) os.remove(path1) tts.convert_text_n_speak("file is renamed check it once")
def rename_dir(filtered_query): abs_path = get_dir_path(filtered_query) #checking directory exists or not if not os.path.isdir(abs_path): tts.convert_text_n_speak("Directory Does Not Exists. Please Check ") return desti_path = get_dest_path(filtered_query, abs_path) if os.path.isdir(desti_path): tts.convert_text_n_speak( "Directory With same name already exists. Please Check ") return #creating command create_dir_cmd = 'mv ' + abs_path + ' ' + desti_path #creating dir out = sp.run([create_dir_cmd], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) if out.returncode == 0: print(out.stdout.decode()) tts.convert_text_n_speak("Directory Renamed Successfully") else: tts.convert_text_n_speak( "Unable to rename directory. Please try again later") sleep(10)
def play_youtube(filtered_query): result = 0 # split user_query to words video_keywords = filtered_query # final keywords to search final_key = [] # keywords that won't be used for searching remv_keywords = [ 'youtube', 'from', 'of', 'for', 'video', 'play', 'search', 'about' ] # appending keyword to final_key list rejecting remv_keywords for word in video_keywords: if word in remv_keywords: pass else: final_key.append(word) #checking video name given or not if final_key == []: tts.convert_text_n_speak("Which video you want to play") user_input = sr.get_audio_to_text() user_input = user_input.lower().strip().split() result = play_youtube(user_input) # making string of keywords to search if result == 0: search_words = str() for word in final_key: search_words = search_words + ' ' + word query_string = urllib.parse.urlencode({"search_query": search_words}) html_content = urllib.request.urlopen( "http://www.youtube.com/results?" + query_string) search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode()) # open link in tab webbrowser webbrowser.open_new_tab("http://www.youtube.com/watch?v=" + search_results[0]) tts.convert_text_n_speak("Video Opened. Enjoy your video") result = 1 return result
def delete_file(path): tts.convert_text_n_speak("are u sure to delete file") input_text = sr.get_audio_to_text() if input_text.find("yes")!=-1: os.remove(path) tts.convert_text_n_speak("Ok fine!!file deleted ,check it once") else: tts.convert_text_n_speak("aage se dhyan rakhna")
def execute_directory_query(filtered_query): if len(filtered_query) < 2: tts.convert_text_n_speak( "Sorry your query is incomplete. please check") return #create a directory elif "create" in filtered_query or "make" in filtered_query: create_dir(filtered_query) #remove a directory elif "remove" in filtered_query or "delete" in filtered_query: remove_dir(filtered_query) #list content of a directory elif "list" in filtered_query or "list all" in filtered_query: listall_dir(filtered_query) #list content of a directory elif "rename" in filtered_query: rename_dir(filtered_query) #list content of a directory elif "copy" in filtered_query: pass # copy_dir(filtered_query) else: tts.convert_text_n_speak( "Sorry your query is incomplete. please check") return # query = input("Directory query : ") # filtered_query = query.lower().strip().split() # execute_directory_query(filtered_query)
def copy_dir(filtered_query): abs_path = get_dir_path(filtered_query) #checking directory exists or not if not os.path.isdir(abs_path): tts.convert_text_n_speak("Please Check Directory Does Not Exists") return #creating command create_dir_cmd = 'mv ' + abs_path + desti_path #creating dir out = sp.run([create_dir_cmd], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) if out.returncode == 0: print(out.stdout.decode()) tts.convert_text_n_speak("Directory Content Listed") else: tts.convert_text_n_speak( "Unable to list directory content. Please try again later") sleep(10)
def create_dir(filtered_query): abs_path = get_dir_path(filtered_query) #checking directory already exists or not if os.path.isdir(abs_path): tts.convert_text_n_speak( "Directory Already Exists. Check before creating") return #creating command create_dir_cmd = 'mkdir ' + abs_path #creating dir out = sp.run([create_dir_cmd], shell=True, stdout=sp.PIPE, stderr=sp.PIPE) if out.returncode == 0: tts.convert_text_n_speak("Directory created") else: tts.convert_text_n_speak( "Unable to Create directory. Please try again later") sleep(5)
def create_file(path): f=open(path,'a') os.system("gedit "+path) tts.convert_text_n_speak("file created")
def call_file(list_text,new_list,file_names,valid_file_op): folder="" count=0 index = 0 index1=0 length = len(list_text) entered = 0 value = 0 current = 0 c = 0 list_text1 = "" try: if new_list == 1: new_list = 0 for i in list_text: count+=1 if i=="open" or i=="create" or i=="close" or i=="delete" or i=="rename" or i=="list": index = list_text.index(i) valid_file_op.append(i) del i elif i=="copy": copy_op.call_copy(list_text) elif i=="file": index1 = list_text.index(i) if list_text[-1]=="file": tts.convert_text_n_speak("please give the file name sir!!") file_name = sr.get_audio_to_text() #file_name = input("enter file") file_names.append(file_name) else: file_name = list_text[list_text.index("file")+1] file_names.append(file_name) list_text.remove("file") #to check whether folder name is given or not if "folder" not in list_text and "directory" not in list_text: tts.convert_text_n_speak("what is the desired location of the file!!") list_text1 = sr.get_audio_to_text() #list_text1 = input("enter location") list_text = list_text1.strip().split() length = len(list_text) new_list = 1 count = 0 call_file(list_text,new_list,file_names,valid_file_op) else: pass elif i=="folder" or i=="directory": index1 = list_text.index(i) if list_text[index1-1]=="home": entered = 1 del i #list_text.remove(i) elif list_text[index1-1]=="current": current = 1 del i #list_text.remove(i) elif list_text[index1-1]!="home" and list_text[index1-1]!="current" and i!=list_text[-1]: folder = list_text[index1+1]+"/"+folder #del i list_text.remove(i) else: #pass c=0 if count == length: break else: #continue c=0 # out of for loop if current == 1: folder="./"+folder elif entered == 1: #to fetch user name output=sp.run(['echo $USER'],shell=True,stdout=sp.PIPE) user=output.stdout.decode().replace('\n','') folder = "/home/" + user +"/" + folder else: folder="/"+folder for i in valid_file_op: if i == "open": path(1,file_names,folder) elif i == "create": path(2,file_names,folder) elif i == "delete": path(3,file_names,folder) elif i == "rename": path(4,file_names,folder) elif i == "copy": path(5,file_names,folders) elif i=="list": path(6,[],folder) except IOError: tts.convert_text_n_speak("something might be missing or maybe you don't have appropriate permissions please check your input once")
def list_files(folder_name): tts.convert_text_n_speak("see the list of files below") os.system("cd "+folder_name+";ls -l")
#!/usr/bin/env python3 import SpeechRego as sr import tts import subprocess as sp import execute_commands #intro message tts.convert_text_n_speak("Welcome") tts.convert_text_n_speak("What You Want to be done") #getting text of user audio while True: user_query = sr.get_audio_to_text() # program exit keywords exit_keyword = ['quit','exit','cancel','close'] #checking query is empty or not if user_query != None : # if query has exit keywords, close the application if user_query in exit_keyword : tts.convert_text_n_speak('exiting') break; elif user_query.find('command')>=0 or user_query.find('directory')>=0 or user_query.find('file')>=0 : execute_commands.execute_commands(user_query): else: cmd_output = "" try : #executing command cmd_output = sp.run([user_query],check=True,shell=True,stdout=sp.PIPE,) except sp.CalledProcessError :
def open_file(path): print("open entered") os.system("gedit "+path) tts.convert_text_n_speak("file opened")
def execute_commands(filtered_query): insplit = [] #Invalid words which will be removed invalid_words = [ 'a', 'an', 'the', 'is', 'am', 'are', 'this', 'that', 'do', 'please', 'would', 'you', 'of', 'me', 'could', 'show', 'present', 'my', 'what', 'who', 'me', 'my', 'tell', 'hey', 'all', 'in', 'under', 'then', 'will', 'would', 'for', 'there', 'command', 'to', 'find', 'my', 'run', 'execute', 'tell', 'year' ] connectionObject = mariadb.connect(host='127.0.0.1', user='******', password='******', database='testdb', charset='utf8mb4') try: #creating a cursor object cursorObject = connectionObject.cursor() #creating list after removing inappropriate words for my_val in filtered_query: if my_val not in invalid_words: insplit.append(my_val) #converting list to string insplit_str = ' '.join(insplit) #to check whether user has given the command for creating a directory or file if (insplit_str.startswith('make') | insplit_str.startswith('create')): pass # if('directory' in insplit_str): # path=insplit_str.split() # #print(path) # pathvar=path[2:] # str='/'.join(pathvar) # command="mkdir /"+str # #print(command) # proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) # (out, err) = proc.communicate() # print(out.decode()) # elif('file' in insplit_str): # path=insplit_str.split() # pathvar=path[2:] # str='/'.join(pathvar) # command ="touch /"+str # #print(command) # proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) # (out, err) = proc.communicate() # print(out.decode()) # elif(insplit_str.startswith('remove') | insplit_str.startswith('delete')): # if('directory' in insplit_str): # path=insplit_str.split() # pathvar=path[2:] # str='/'.join(pathvar) # command="rm -rvf /"+str # #print(command) # proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) # (out, err) = proc.communicate() # print(out.decode()) # elif('file' in insplit_str): # path=insplit_str.split() # pathvar=path[2:] # str='/'.join(pathvar) # command="rm -rvf /"+str # #print(command) # proc = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True) # (out, err) = proc.communicate() # print(out.decode()) #for calendar command elif (insplit_str.startswith('calendar')): #calendar command with year cal_query = insplit_str.strip().split() attri = "cal" for i in range(1, len(cal_query)): attri = attri + " " + cal_query[i] os.system(attri) time.sleep(5) else: #SQL Query var = '"' + insplit_str + '"' sqlQuery = "select command from commands1 where user_input=" + var #print(sqlQuery) #executing sql query cursorObject.execute(sqlQuery) #fetching data from sql - returning list rows = cursorObject.fetchall() # checking query fetched or not if len(rows) != 0: #fetching command print("fetching commands") inp = rows[0][0] #os.system(inp) # s=''.join(val) proc = subprocess.Popen([inp], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() print(out.decode()) time.sleep(5) #print(var12) else: tts.convert_text_n_speak( "Sorry your query is incomplete PLEASE CHECK") time.sleep(5) return except Exception as e: #Exception Caught print("Exception Occured ", e) finally: #CLosing the connection connectionObject.close() return
def Service(user_query): print('in service module') # service modes modes = ['stop','start','restart','status'] # execute service command to get all services present proc = sp.Popen(['service','--status-all'], stdout=sp.PIPE, stderr=sp.PIPE) # get stdout and error if occured (out,err) = proc.communicate() # get list of services from stdout all_services = out.decode().replace(' [ - ] ','').replace('\n','').replace(' [ + ] ','').split(' ') all_services.pop(0) #---------------------------------------------------------------------------------------------------------------------- # for each service available for serv in all_services: #----------------------------------------------------------------------------------------------------------------------------------- # if apache is found in query if 'apache' in user_query: # for each mode in modes for mode in modes: # if mode is in query if mode in user_query: # execute command in mode found proc = sp.Popen(['service','apache2',mode],stdout=sp.PIPE,stderr=sp.PIPE) # for start and restart if mode=='start' or mode=='restart': tts.convert_text_n_speak('apache started') return # for stopping service elif mode=='stop': tts.convert_text_n_speak('apache stopped') return # for status of serice else: (out,err)=proc.communicate() # get where is string active running msg = out.decode().find('active (running)') # if active runn is found speak if msg>0: tts.convert_text_n_speak('apache is active running now') return # if not found service inactive --> give option to start else: tts.convert_text_n_speak("apache is inactive") tts.convert_text_n_speak("do you wish to start the service") # get a reply reply = sr.get_audio_to_text() # if negative answer if 'no' in reply: return # if affirmative else: tts.convert_text_n_speak('apache service started') # start the service proc = sp.Popen(['service','apache2','start'],stdout=sp.PIPE,stderr=sp.PIPE) return # if there isn't any mode in the query else: pass #------------------------------------------------------------------------------------------------------------------------------- # FOR TELNET OR XIN # if telnet in user query elif 'telnet' in user_query: # for each mode in modes check if it is present in query for mode in modes: if mode in user_query: # if mode found in query exceute the mode for that service i.e telnet proc = sp.Popen(['service','xinetd',mode],stdout=sp.PIPE,stderr=sp.PIPE) if mode=='start' or mode=='restart': tts.convert_text_n_speak('telnet started') return tts.convert_text_n_speak('telnet stopped') return else: (out,err)=proc.communicate() msg = out.decode().find('active (running)') if msg>0: tts.convert_text_n_speak('telnet is active running now') return else: tts.convert_text_n_speak("telnet is inactive") tts.convert_text_n_speak("do you wish to start the service") reply = sr.get_audio_to_text() if 'no' in reply: return else: tts.convert_text_n_speak('telnet service started') proc = sp.Popen(['service','xinetd','start'],stdout=sp.PIPE,stderr=sp.PIPE) return else: pass #------------------------------------------------------------------------------------------------------------------------------ elif 'nfs' in user_query: for mode in modes: if mode in user_query: proc = sp.Popen(['service','nfs-kernel-server',mode],stdout=sp.PIPE,stderr=sp.PIPE) if mode=='start' or mode=='restart': tts.convert_text_n_speak('nfs started') return elif mode=='stop': tts.convert_text_n_speak('nfs stopped') return else: (out,err)=proc.communicate() msg = out.decode().find('active (running)') if msg>0: tts.convert_text_n_speak('nfs is active running now') return else: tts.convert_text_n_speak("nfs is inactive") tts.convert_text_n_speak("do you wish to start the service") reply = sr.get_audio_to_text() if 'no' in reply: return else: tts.convert_text_n_speak('nfs service started') proc = sp.Popen(['service','nfs-kernel-server','start'],stdout=sp.PIPE,stderr=sp.PIPE) return else: pass #-------------------------------------------------------------------------------------------------------------------- # a service is found in user query elif serv in user_query: # modes checked if t is in user query for mode in modes: if mode in user_query: # apply mode on service proc = sp.Popen(['service',serv,mode],stdout=sp.PIPE,stderr=sp.PIPE) # for strat and restart if mode=='start' or mode=='restart': tts.convert_text_n_speak(serv+' started') return # for stop elif mode=='stop': tts.convert_text_n_speak(serv+' stopped') return else: # for status (out,err)=proc.communicate() # find if active running in result i.e out msg = out.decode().find('active (running)') # if active running found in out if msg>0: tts.convert_text_n_speak(serv+' is active running now') return # if not found, service is inactive else: tts.convert_text_n_speak(serv+" is inactive") tts.convert_text_n_speak("do you wish to start the service") # get answer if user wants to start service or not reply = sr.get_audio_to_text() if 'no' in reply: return else: tts.convert_text_n_speak(serv+' service started') proc = sp.Popen(['service',serv,'start'],stdout=sp.PIPE,stderr=sp.PIPE) return else: pass # if service is not found in user query elif serv not in user_query: # if we have reached the last element of all_services and no match in user query if serv==all_services[-1]: # service not found tts.convert_text_n_speak('Sorry, this service is not installed') return # if we are not at the last element then continue else: continue;