コード例 #1
0
ファイル: test_winshell.py プロジェクト: Jatz/winshell
 def test_versions(self):
     recycle_bin = winshell.recycle_bin()
     versions = recycle_bin.versions(self.tempfile)
     versions_info = set()
     for version in versions:
         versions_info.add((b("").join(version.contents()), version.stat()[2]))
     self.assertEqual(self.deleted_files, versions_info)
コード例 #2
0
ファイル: test_winshell.py プロジェクト: Jatz/winshell
 def test_iter(self):
     for item in winshell.recycle_bin():
         if item.original_filename().lower() == self.tempfile:
             break
     else:
         raise RuntimeError("%s not found in recycle_bin" % self.tempfile)
     self.assertIsInstance(item, winshell.ShellRecycledItem)
     self.assertEqualCI(item.original_filename(), self.tempfile)
コード例 #3
0
ファイル: test_winshell.py プロジェクト: Jatz/winshell
 def test_undelete(self):
     self.assertFalse(os.path.exists(self.tempfile))
     recycle_bin = winshell.recycle_bin()
     newest = sorted(recycle_bin.versions(self.tempfile), key=lambda item: item.recycle_date())[-1]
     newest_contents = b("").join(newest.contents())
     recycle_bin.undelete(self.tempfile)
     self.assertTrue(os.path.exists(self.tempfile))
     self.assertEquals(open(self.tempfile, "rb").read(), newest_contents)
コード例 #4
0
        def submittion():
            global location

            location = location_entry.get()

            if len(location) == 0:
                messagebox.showinfo("Entry Error!",
                                    "Please Enter A Valid Location!")
            else:
                user_proof = username_get()

                response = google_images_download.googleimagesdownload()

                arguments = {
                    "keywords": location + " beautiful city images",
                    "limit": 5,
                    "print_urls": False,
                    "silent_mode": True,
                    "format": "png",
                    "no_directory": True,
                    "output_directory":
                    "C:/Users/aayus/Desktop/PROJECTS/LOGIN",
                    "save_source": "paths",
                    "exact_size": "320,160"
                }
                paths = response.download(arguments)

                with open("paths.txt", "r") as f:
                    splits = f.read()
                    content = splits.split("//")
                    loc1 = content[1]
                    loc2 = content[3]
                    loc3 = content[5]
                    loc4 = content[7]
                    loc5 = content[9]

                    req = loc1.split("\t")
                    req2 = loc2.split("\t")
                    req3 = loc3.split("\t")
                    req4 = loc4.split("\t")
                    req5 = loc5.split("\t")

                    filepath1 = req[0]
                    filepath2 = req2[0]
                    filepath3 = req3[0]
                    filepath4 = req4[0]
                    filepath5 = req5[0]

                    f.close()

                filepaths = [
                    filepath1, filepath2, filepath3, filepath4, filepath5
                ]

                val = randint(0, 4)

                display = filepaths[val]

                location_pic = PhotoImage(file=display)
                pic_label = Label(wnd, image=location_pic)
                pic_label.config(image=location_pic)
                pic_label.grid(row=2, column=1)

                try:
                    os.remove(filepath1)
                    os.remove(filepath2)
                    os.remove(filepath3)
                    os.remove(filepath4)
                    os.remove(filepath5)

                    os.remove('paths.txt')
                    winshell.recycle_bin().empty(confirm=False,
                                                 show_progress=False,
                                                 sound=False)
                    print("Removed")
                except:
                    print("Files don't exist.")

                wnd.update()
                wnd.mainloop()
コード例 #5
0
ファイル: prg.py プロジェクト: aritradey97/Python-prg
    def OnEnter(self, event):
        put = self.txt.GetValue()
        put = put.lower()
        link = put.split()
        if put == '':
            r = sr.Recognizer()
            with sr.Microphone() as src:
                audio = r.listen(src)
            try:
                put = r.recognize_google(audio)
                put = put.lower()
                link = put.split()
                self.txt.SetValue(put)

            except sr.UnknownValueError:
                print("Google Speech Recognition could not understand audio")
            except sr.RequestError as e:
                print(
                    "Could not request results from Google STT; {0}".format(e))
            except:
                print("Unknown exception occurred!")

        # Open a webpage
        if put.startswith('open '):
            try:
                speak.Speak("opening " + link[1])
                webbrowser.open('http://www.' + link[1] + '.com')
            except:
                print('Sorry, No Internet Connection!')
        # Play Song on Youtube
        elif put.startswith('play '):
            try:
                link = '+'.join(link[1:])
                say = link.replace('+', ' ')
                url = 'https://www.youtube.com/results?search_query=' + link
                source_code = requests.get(url, headers=headers, timeout=15)
                plain_text = source_code.text
                soup = BeautifulSoup(plain_text, "html.parser")
                songs = soup.findAll('div', {'class': 'yt-lockup-video'})
                song = songs[0].contents[0].contents[0].contents[0]
                hit = song['href']
                speak.Speak("playing " + say)
                webbrowser.open('https://www.youtube.com' + hit)
            except:
                print('Sorry, No internet connection!')
        # Google Search
        elif put.startswith('search '):
            try:
                link = '+'.join(link[1:])
                say = link.replace('+', ' ')
                # print(link)
                speak.Speak("searching on google for " + say)
                webbrowser.open('https://www.google.co.in/search?q=' + link)
            except:
                print('Sorry, No internet connection!')
        # Empty Recycle bin
        elif put.startswith('empty '):
            try:
                winshell.recycle_bin().empty(confirm=False,
                                             show_progress=False,
                                             sound=True)
                print("Recycle Bin Empty!!")
            except:
                print("Unknown Error")
        # News
        elif put.startswith('science '):
            try:
                jsonObj = urlopen(
                    '''https://newsapi.org/v1/articles?source=new-scientist&sortBy=top&apiKey=your_API_here'''
                )
                data = json.load(jsonObj)
                i = 1
                speak.Speak('''Here are some top science
                             news from new scientist''')
                print(
                    '''             ================NEW SCIENTIST=============
                      ''' + '\n')
                for item in data['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except:
                print('Sorry, No internet connection')
        elif put.startswith('headlines '):
            try:
                jsonObj = urlopen(
                    '''https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=your_API_here'''
                )
                data = json.load(jsonObj)
                i = 1
                speak.Speak('here are some top news from the times of india')
                print(
                    '''             ===============TIMES OF INDIA============'''
                    + '\n')
                for item in data['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    i += 1
            except Exception as e:
                print(str(e))
        # Lock the device
        elif put.startswith('lock '):
            try:
                speak.Speak("locking the device")
                ctypes.windll.user32.LockWorkStation()
            except Exception as e:
                print(str(e))
        # Play videos in boredom
        elif put.endswith('bored'):
            try:
                speak.Speak('''Sir, I\'m playing a dance video.
                            Hope you like it''')
                song = random.choice(videos)
                os.startfile(song)
            except Exception as e:
                print(str(e))
        # Other Cases
        else:
            try:
                # wolframalpha
                client = wolframalpha.Client(app_id)
                res = client.query(put)
                ans = next(res.results).text
                print(ans)
                speak.Speak(ans)
            except:
                # wikipedia
                put = put.split()
                put = ' '.join(put[2:])
                #print(put)
                print(wikipedia.summary(put))
                speak.Speak('Searched wikipedia for ' + put)
コード例 #6
0
def start():
    clear = lambda: os.system('cls')
    speak("Loading your assistant")
    print("Loading your assistant")
    WishMe()

    while True:
        speak("Tell Me, How can I help you?")
        print("Tell Me, How can I help you?")
        statement=TakeCommand().lower()
        
        if statement==0 or statement=='':
            continue

        if "bye" in statement or "stop" in statement:
            quiet()
            break
            
        if 'youtube' in statement:
            webbrowser.open("youtube.com")
            speak("here is your YouTube")

        elif 'google' in statement:
            webbrowser.open("google.com")
            speak("here is your Google")
        
        elif 'time' in statement:
            strTime =  datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"the time is {strTime}")
        
        elif 'date' in statement:
            strTime =  datetime.datetime.now().strftime('%Y-%m-%d')
            speak(f"the date is {strTime}")

        # masti with assistant

        elif 'how are you' in statement:
            speak("I am good sir, tell me about you")
            if 'fine' in statement or 'good' in statement:
                speak("its good to know that")
        
        elif 'made you' in statement or 'created you' in statement or 'is your invertor' in statement:
            speak("I have been created by Kritika")

        elif 'joke' in statement:
            speak(pyjokes.get_joke())

        elif 'reason of your existence' in statement or 'why are you created' in statement or 'why you came to world' in statement:
            speak("I have been created as an minor project by Kritika")


        elif "weather" in statement:
            weather()

        elif 'search' in statement or 'play' in statement:
            statement = statement.replace("search","")
            statement = statement.replace("play", "")
            webbrowser.open(statement)
            time.sleep(10)
        
        elif "camera" in statement or "take a photo" in statement:
            click_img()

        elif 'news' in statement:
            news()

        elif 'ask' in statement:
            speak('I can answer to computational and geographical questions and what question do you want to ask now')
            question=TakeCommand()
            app_id="GGAAPU-P7HPQJT5Y2"
            client = wolframalpha.Client('GGAAPU-P7HPQJT5Y2')
            res = client.query(question)
            print(type(res))
            answer = next(res.results).text
            speak(answer)
            print(answer)

        elif "calculate" in statement:   
            app_id = "GGAAPU-P7HPQJT5Y2"
            client = wolframalpha.Client(app_id)
            indx = statement.lower().split().index('calculate') 
            statement = statement.split()[indx + 1:] 
            res = client.query(' '.join(statement)) 
            answer = next(res.results).text
            print("The answer is " + answer) 
            speak("The answer is " + answer)

        elif "restart" in statement:
            speak("Restarting")
            subprocess.call(['shutdown','/r'])

        elif "hibernate" in statement or 'sleep' in statement:			
            speak("Hibernating")
            subprocess.call(['shutdown','/h'])

        elif 'log off' in statement or 'signout' in statement:
            speak("Make sure all the application are closed before sign-out")
            time.sleep(5)
            subprocess.call(["shutdown", "/l"])

        elif 'shutdown system' in statement:
                speak("Hold on! The pc is shutting down")
                subprocess.call('shutdown / p /f')

        elif 'empty recycle bin' in statement:
            winshell.recycle_bin().empty(empty(confirm=True, show_progress=True, sound=True))	
            speak("Recycle bin recycled")

        elif "don't listen" in statement or "stop listening" in statement:
            speak("for how much time you don't want to listen me")
            a=int(TakeCommand())
            time.sleep(a)
            print(a)

        elif "where is" in statement or 'locate' in statement:
            statement=statement.replace("where is","")
            location=statement
            speak("user asked to locate")
            speak(location)
            webbrowser.open("https://www.google.nl / maps / place/"+location+"")

        else:
            speak("opening")
            webbrowser.open(statement)
            time.sleep(5)
コード例 #7
0
                    i += 1
            except Exception as e:

                print(str(e))

        elif 'lock window' in query:
            speak("locking the device")
            ctypes.windll.user32.LockWorkStation()

        elif 'shutdown system' in query:
            speak("Hold On a Sec ! Your system is on its way to shut down")
            subprocess.call('shutdown / p /f')

        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=True)
            speak("Recycle Bin Recycled")

        elif "don't listen" in query or "stop listening" in query:
            speak(
                "for how much time you want to stop jarvis from listening commands"
            )
            a = int(takeCommand())
            time.sleep(a)
            print(a)

        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
コード例 #8
0
def run_romeo(time=None):
    clear = lambda: os.system('cls')
    # This Function will clean any
    # command before execution of this python file
    clear()
    command = take_command()
    print(command)
    name = "romeo 1.0"
    if 'play ' in command or 'playing ' in command:
        try:
            song = command.replace('play', '')
            talk('playing ' + song)
            pywhatkit.playonyt(song)
        except Exception as e:
            print(e)
            talk(f"unable to find this {song}  in youtube")


    elif 'time' in command or 'what time is it ' in command:
        time = datetime.datetime.now().strftime('%I:%M:%p')  # I is the formate of the time and p is the am or pm
        print(time)
        talk('current time is ' + time)
    elif 'tell me about ' in command:
        try:
            person = command.replace('tell me about', '')
            info = wikipedia.summary(person, 2)
            # print(info)
            talk(f'according to wikipedia {info}')
        except Exception as e:
            print(e)
            talk(f"unable to find this  wikipedia{info} ")


    elif 'joke' in command:
        talk(' here you go')
        talk(pyjokes.get_joke())
    elif 'what is the date ' in command or 'date' in command:
        date = datetime.date.today()
        talk(date)

    elif '.com' in command or '.org' in command or '.net' in command or ' search' in command:
        try:
            web = command.replace('.com', '').replace('.org', '').replace('.net', '').replace('search', '').replace(
                'romeo', '')
            talk(web)
            print(web)
            # talk(command)
            webbrowser.open_new_tab(web)

            # webbrowser.open("youtube.com")
        except Exception as e:
            print(e)
            talk(f"unable to search {web} ")
    elif 'my audio music' in command or "start my audio music" in command:
        talk("why not sir ,Here you go with music")
        # music_dir = "G:\\Song"
        music_dir = "C:\\Users\\Public\\Music"
        songs = os.listdir(music_dir)
        print(songs)
        random = os.startfile(os.path.join(music_dir, songs[1]))

    elif 'how are you' in command:
        talk("I am fine, Thank you")
        talk("How are you, Sir")

    elif 'fine' in command or "good" in command:
        talk("It's good to know that your fine")

    elif "change my name to" in command:
        query = command.replace("change my name to", "")
        name = command

    elif "change name" in command:
        talk("What would you like to call me, Sir ")
        name = take_command()
        talk("Thanks for naming me")


    elif "who made you" in command or "who created you" in command:
        talk("it is greate to know you that I have been created by my boss.")
    elif "why you came to world" in command:
        talk("Thanks to my boss. further It's a secret ")

    elif 'open microsoft office' in command:
        talk("opening Power Point presentation")
        power = r"C:\\Program Files (x86)\\Microsoft Office\\Office15"
        os.startfile(power)
    elif 'what is love' in command or 'tell me about  love' in command:
        talk("It is 7th sense that destroy all other senses..it's a crazy things is not it my friend")

    elif "who are you" in command:
        talk(f"I am your virtual assistant {name}")


    elif "can you hear me" in command or "are you there" in command:
        talk('yes sir ,please tell me how can i help you ,do you need anything sir')

    elif 'open bluestack' in command:
        appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
        os.startfile(appli)
    elif 'empty recycle bin' in command:
        winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
        talk("Recycle Bin Recycled")

    elif "don't listen" in command or "stop listening" in command:
        try:
            talk("for how much time you want to stop jarvis from listening commands")
            a = int(take_command())
            time.sleep(a)
            print(a)
        except Exception:
            talk("i don't listen you ")
    elif "where is" in command or "romeo where is" in command or " romeo search where is" in command:
       try: 
            query = command.replace("where is", "").replace("romeo where is", " ").replace("romeo search where is", " ")
            location = query
            talk("User asked to Locate")
            talk(location)
            webbrowser.open("https://www.google.com/maps/place/" + location + "")
       except Exception:
           talk('not found this place')

    elif "weather" in command:

        # Google Open weather website
        # to get API of Open weather
        api_key = "api key"
        # base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
        talk(" City name ")
        print("City name : ")
        city_name = take_command()
        # complete_url = base_url + "appid =" + api_key + "&q =" + city_name
        complete_url = f"https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={api_key}"
        response = requests.get(complete_url)
        x = response.json()

        if x["cod"] != "404":
            y = x["main"]
            current_temperature = y["temp"]
            current_pressure = y["pressure"]
            current_humidiy = y["humidity"]
            z = x["weather"]
            weather_description = z[0]["description"]
            print(" Temperature (in kelvin unit) = " + str(
                current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(
                current_pressure) + "\n humidity (in percentage) = " + str(
                current_humidiy) + "\n description = " + str(weather_description))
        else:
            talk(" City Not Found ")

    elif 'open code' in command:
        codePath = "/Applications/PyCharm CE.app"  # that's the code path.
        os.startfile(codePath)


    elif "calculate" in command or 'i want to know ' in command:

        try:
            # command = command.replace('calculate', '').replace('how to', '').replace('i want to know', '')
            query = command.replace('calculate', '').replace('i want to know', '')
            app_id = "Wolframalpha api id"
            # client = wolframalpha.Client(app_id)
            client = wolframalpha.Client('app_id')
            question = query
            res = client.query(question)
            answer = next(res.results).text
            print("The answer is " + answer)
            talk("The answer is " + answer)
        except Exception as e:
            print(e)
            talk('sorry sir i am not able to do this,please try again')

    elif "camera" in command or "take a photo" in command:
        try:
            ec.capture(0, "robo camera", "img.jpg")
        except Exception:
            talk('photos are not taken')

  

    elif 'email to gm' in command:
        try:

            talk('What is the subject?')

            subject = take_command()
            talk('What should I say in message?')

            message = take_command()
            content = 'Subject: {}\n\n{}'.format(subject, message)
            to = "*****@*****.**"
            sendEmail(to, content)
            talk("Email has been sent!")
        except Exception as e:
            print(e)
            talk("Sorry my friend. I am not able to send this email")



    elif 'send a mail' in command:
        try:
            talk("What should I say?")
            content = take_command()
            talk("whome should i send")
            to = input()
            sendEmail(to, content)
            talk("Email has been sent !")
        except Exception as e:
            print(e)
            talk("I am not able to send this email")
    elif "write a note" in command:
        try:
            talk("What should i write, sir")
            note = take_command()
            file = open('jarvis.txt', 'w')
            talk("Sir, Should i include date and time")
            snfm = take_command()
            if 'yes' in snfm or 'sure' in snfm:
                strTime = datetime.datetime.now().strftime("% H:% M:% S")
                file.write(strTime)
                file.write(" :- ")
                file.write(note)
            else:
                file.write(note)
        except Exception:
            talk('i am not able to write this note sir')

    # elif "what is" in command or "who is" in command:
    #
    #     # Use the same API key
    #     # that we have generated earlier
    #     client = wolframalpha.Client("API_ID")
    #     res = client.query(command)
    #
    #     try:
    #         print(next(res.results).text)
    #         talk(next(res.results).text)
    #     except StopIteration:
    #         print("No results")
    elif 'why are you answer so slow' in command or 'tell me why are you so slow' in command:
        talk('sir this is not my fault .your internet connection is so slow now')
    elif 'exit' in command:
        try:
            talk("Thanks for giving me your time")
            exit()
        except Exception as e:
            print(e)
            talk('i am not able to exit sir ..something doing wrong')

    elif 'what is the temperature in' in command:
        try:
            search=command.replace('what is the temperature in','')
            url = f'https://www.google.com/search?q={search}'
            r = requests.get(url)
            data = BeautifulSoup(r.text, 'html.parser')
            temp = data.find("div", class_='BNeawe').text
            talk(f'current {search} is {temp}')

        except Exception as e:
            print(e)
            talk('i am not able to find this place temperature ')
コード例 #9
0
def sendEmail(to, content): 
    server = smtplib.SMTP('smtp.gmail.com', 587) 
    server.ehlo() 
    server.starttls() 
      
    # Enable low security in gmail 
    server.login('your email id', 'your email passowrd') 
    server.sendmail('your email id', to, content) 
    server.close() 
    if __name__ == '__main__': 
    clear = lambda: os.system('cls') 
      
    # This Function will clean any 
    # command before execution of this python file 
    clear() 
    wishMe() 
    usrname() 
      
    while True: 
          
        query = takeCommand().lower() 
          
        # All the commands said by user will be  
        # stored here in 'query' and will be 
        # converted to lower case for easily  
        # recognition of command 
        if 'wikipedia' in query: 
            speak('Searching Wikipedia...') 
            query = query.replace("wikipedia", "") 
            results = wikipedia.summary(query, sentences = 3) 
            speak("According to Wikipedia") 
            print(results) 
            speak(results) 
  
        elif 'open youtube' in query: 
            speak("Here you go to Youtube\n") 
            webbrowser.open("youtube.com") 
  
        elif 'open google' in query: 
            speak("Here you go to Google\n") 
            webbrowser.open("google.com") 
  
        elif 'open stackoverflow' in query: 
            speak("Here you go to Stack Over flow.Happy coding") 
            webbrowser.open("stackoverflow.com")    
  
        elif 'play music' in query or "play song" in query: 
            speak("Here you go with music") 
            # music_dir = "G:\\Song" 
            music_dir = "C:\\Users\\GAURAV\\Music"
            songs = os.listdir(music_dir) 
            print(songs)     
            random = os.startfile(os.path.join(music_dir, songs[1])) 
  
        elif 'the time' in query: 
            strTime = datetime.datetime.now().strftime("% H:% M:% S")     
            speak(f"Sir, the time is {strTime}") 
  
        elif 'open opera' in query: 
            codePath = r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe"
            os.startfile(codePath) 
  
        elif 'email to gaurav' in query: 
            try: 
                speak("What should I say?") 
                content = takeCommand() 
                to = "Receiver email address"    
                sendEmail(to, content) 
                speak("Email has been sent !") 
            except Exception as e: 
                print(e) 
                speak("I am not able to send this email") 
  
        elif 'send a mail' in query: 
            try: 
                speak("What should I say?") 
                content = takeCommand() 
                speak("whome should i send") 
                to = input()     
                sendEmail(to, content) 
                speak("Email has been sent !") 
            except Exception as e: 
                print(e) 
                speak("I am not able to send this email") 
  
        elif 'how are you' in query: 
            speak("I am fine, Thank you") 
            speak("How are you, Sir") 
  
        elif 'fine' in query or "good" in query: 
            speak("It's good to know that your fine") 
  
        elif "change my name to" in query: 
            query = query.replace("change my name to", "") 
            assname = query 
  
        elif "change name" in query: 
            speak("What would you like to call me, Sir ") 
            assname = takeCommand() 
            speak("Thanks for naming me") 
  
        elif "what's your name" in query or "What is your name" in query: 
            speak("My friends call me") 
            speak(assname) 
            print("My friends call me", assname) 
  
        elif 'exit' in query: 
            speak("Thanks for giving me your time") 
            exit() 
  
        elif "who made you" in query or "who created you" in query:  
            speak("I have been created by Gaurav.") 
              
        elif 'joke' in query: 
            speak(pyjokes.get_joke()) 
              
        elif "calculate" in query:  
              
            app_id = "Wolframalpha api id" 
            client = wolframalpha.Client(app_id) 
            indx = query.lower().split().index('calculate')  
            query = query.split()[indx + 1:]  
            res = client.query(' '.join(query))  
            answer = next(res.results).text 
            print("The answer is " + answer)  
            speak("The answer is " + answer)  
  
        elif 'search' in query or 'play' in query: 
              
            query = query.replace("search", "")  
            query = query.replace("play", "")           
            webbrowser.open(query)  
  
        elif "who i am" in query: 
            speak("If you talk then definately your human.") 
  
        elif "why you came to world" in query: 
            speak("Thanks to Gaurav. further It's a secret") 
  
        elif 'power point presentation' in query: 
            speak("opening Power Point presentation") 
            power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
            os.startfile(power) 
  
        elif 'is love' in query: 
            speak("It is 7th sense that destroy all other senses") 
  
        elif "who are you" in query: 
            speak("I am your virtual assistant created by Gaurav") 
  
        elif 'reason for you' in query: 
            speak("I was created as a Minor project by Mister Gaurav ") 
  
        elif 'change background' in query: 
            ctypes.windll.user32.SystemParametersInfoW(20,  
                                                       0,  
                                                       "Location of wallpaper", 
                                                       0) 
            speak("Background changed succesfully") 
  
        elif 'open bluestack' in query: 
            appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
            os.startfile(appli) 
  
        elif 'news' in query: 
              
            try:  
                jsonObj = urlopen('''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\''') 
                data = json.load(jsonObj) 
                i = 1
                  
                speak('here are some top news from the times of india') 
                print('''=============== TIMES OF INDIA ============'''+ '\n') 
                  
                for item in data['articles']: 
                      
                    print(str(i) + '. ' + item['title'] + '\n') 
                    print(item['description'] + '\n') 
                    speak(str(i) + '. ' + item['title'] + '\n') 
                    i += 1
            except Exception as e: 
                  
                print(str(e)) 
  
          
        elif 'lock window' in query: 
                speak("locking the device") 
                ctypes.windll.user32.LockWorkStation() 
  
        elif 'shutdown system' in query: 
                speak("Hold On a Sec ! Your system is on its way to shut down") 
                subprocess.call('shutdown / p /f') 
                  
        elif 'empty recycle bin' in query: 
            winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True) 
            speak("Recycle Bin Recycled") 
  
        elif "don't listen" in query or "stop listening" in query: 
            speak("for how much time you want to stop jarvis from listening commands") 
            a = int(takeCommand()) 
            time.sleep(a) 
            print(a) 
  
        elif "where is" in query: 
            query = query.replace("where is", "") 
            location = query 
            speak("User asked to Locate") 
            speak(location) 
            webbrowser.open("https://www.google.nl / maps / place/" + location + "") 
  
        elif "camera" in query or "take a photo" in query: 
            ec.capture(0, "Jarvis Camera ", "img.jpg") 
  
        elif "restart" in query: 
            subprocess.call(["shutdown", "/r"]) 
              
        elif "hibernate" in query or "sleep" in query: 
            speak("Hibernating") 
            subprocess.call("shutdown / h") 
  
        elif "log off" in query or "sign out" in query: 
            speak("Make sure all the application are closed before sign-out") 
            time.sleep(5) 
            subprocess.call(["shutdown", "/l"]) 
  
        elif "write a note" in query: 
            speak("What should i write, sir") 
            note = takeCommand() 
            file = open('jarvis.txt', 'w') 
            speak("Sir, Should i include date and time") 
            snfm = takeCommand() 
            if 'yes' in snfm or 'sure' in snfm: 
                strTime = datetime.datetime.now().strftime("% H:% M:% S") 
                file.write(strTime) 
                file.write(" :- ") 
                file.write(note) 
            else: 
                file.write(note) 
          
        elif "show note" in query: 
            speak("Showing Notes") 
            file = open("jarvis.txt", "r")  
            print(file.read()) 
            speak(file.read(6)) 
  
        elif "update assistant" in query: 
            speak("After downloading file please replace this file with the downloaded one") 
            url = '# url after uploading file'
            r = requests.get(url, stream = True) 
              
            with open("Voice.py", "wb") as Pypdf: 
                  
                total_length = int(r.headers.get('content-length')) 
                  
                for ch in progress.bar(r.iter_content(chunk_size = 2391975), 
                                       expected_size =(total_length / 1024) + 1): 
                    if ch: 
                      Pypdf.write(ch) 
                      
        # NPPR9-FWDCX-D2C8J-H872K-2YT43 
        elif "jarvis" in query: 
              
            wishMe() 
            speak("Jarvis 1 point o in your service Mister") 
            speak(assname) 
  
        elif "weather" in query: 
              
            # Google Open weather website 
            # to get API of Open weather  
            api_key = "Api key" 
            base_url = "http://api.openweathermap.org / data / 2.5 / weather?"
            speak(" City name ") 
            print("City name : ") 
            city_name = takeCommand() 
            complete_url = base_url + "appid =" + api_key + "&q =" + city_name 
            response = requests.get(complete_url)  
            x = response.json()  
              
            if x["cod"] != "404":  
                y = x["main"]  
                current_temperature = y["temp"]  
                current_pressure = y["pressure"]  
                current_humidiy = y["humidity"]  
                z = x["weather"]  
                weather_description = z[0]["description"]  
                print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description))  
              
            else:  
                speak(" City Not Found ") 
              
        elif "send message " in query: 
                # You need to create an account on Twilio to use this service 
                account_sid = 'Account Sid key'
                auth_token = 'Auth token'
                client = Client(account_sid, auth_token) 
  
                message = client.messages \ 
                                .create( 
                                    body = takeCommand(), 
                                    from_='Sender No', 
                                    to ='Receiver No'
                                ) 
  
                print(message.sid) 
  
        elif "wikipedia" in query: 
            webbrowser.open("wikipedia.com") 
  
        elif "Good Morning" in query: 
            speak("A warm" +query) 
            speak("How are you Mister") 
            speak(assname) 
  
        # most asked question from google Assistant 
        elif "will you be my gf" in query or "will you be my bf" in query:    
            speak("I'm not sure about, may be you should give me some time") 
  
        elif "how are you" in query: 
            speak("I'm fine, glad you me that") 
  
        elif "i love you" in query: 
            speak("It's hard to understand") 
  
        elif "what is" in query or "who is" in query: 
              
            # Use the same API key  
            # that we have generated earlier 
            client = wolframalpha.Client("API_ID") 
            res = client.query(query) 
              
            try: 
                print (next(res.results).text) 
                speak (next(res.results).text) 
            except StopIteration: 
                print ("No results") 
コード例 #10
0
def speaking():
    speak("How can I help you? ")
    while True:
        query=takeCommand(y).lower()
        print(query)
        if  'open youtube' in query:
            speak("Here you go to Youtube\n")
            webbrowser.open("youtube.com")
        elif 'open google' in query:
            speak("Here you go to Google\n")
            webbrowser.open("google.com")   
        elif 'open stackoverflow' in query:
            speak("Here you go to Stack Over flow.Happy coding")
            webbrowser.open("stackoverflow.com") 
        elif "wikipedia" in query:
            webbrowser.open("wikipedia.com")
        elif 'search for' in query:
            x=re.search('search for',query)
            speak("This is what I found sir!")
            print(x)
            query=query[x.start()+10:]
            print(query)
            for j in search(query,tld="co.in",num=1, stop=1):
                print(j)
                webbrowser.open(j)
        elif 'news' in query:
            webbrowser.open("https://timesofindia.indiatimes.com/india") 
            speak('here are some top news from the times of india')
            print('''=============== TIMES OF INDIA ============'''+ '\n')
# STORY
        elif 'tell me a story' in query:
            speak("Reading a story book")
            content=takeCommand(y)
            speakstory()
# PLAY MOVIE
        elif 'play movie' in query:
            speak("Playing your playlist sir")
            music_dir = "D:\\User Data\\Movies\\Shaadi Mein Zaroor Aana 2017"
            songs = os.listdir(music_dir)
            print(songs) 
            random=os.startfile(os.path.join(music_dir, songs[0]))

# MAIL
        elif 'send a mail' in query or 'send an email' in query or 'mail' in query:
            try:
                speak("What should I say?")
                content = takeCommand(y)
                speak("To whom should i send? Can you please type the email.")
                #to = input("Enter the email here: ") 
                sleep(10)
                to = user_input()
                sendEmail(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")   
# WHATSAPP
        elif 'whatsapp' in query:
            try:
                speak("To whom should i send? Can you please type in the name.")
                #to = input('Name: ')
                to = user_input()
                speak("What should i send? Can you please type in the message.")
                #content = input("Enter the message: ") 
                content = user_input()
                speak('You will have to scan for whatsapp web. ')
                whatsapp(to, content)
                speak("Message has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this message") 
# RANDOM Qs
        elif "Good Morning" in query:
            speak("A warm" +query)
            speak("How are you Mister")

        elif "will you be my gf" in query or "will you be my bf" in query: 
            speak("I'm not sure about, may be you should give me some time")

        elif "how are you" in query:
            speak("I'm fine, glad you me that")

        elif "i love you" in query:
            speak("It's hard to understand")

        elif 'the time' in query:
            strTime = datetime.datetime.now()
            speak(f"Sir, the time is {strTime}")

        elif 'jarvis' in query:
            speak("Jarvis 1 point o in your service Mister")

        elif 'how are you' in query:
            speak("I am fine, Thank you")
            speak("How are you, Sir")

        elif 'fine' in query or "good" in query:
            speak("It's good to know that your fine")

        elif "what's your name" in query or "What is your name" in query:
            speak("My friends call me Jarvis")

        elif "who made you" in query or "who created you" in query: 
            speak("I have been created by Vaishnavi.")
            
        elif 'joke' in query:
            speak(pyjokes.get_joke())

        elif "who am I" in query:
            speak("If you talk then definately your human.")

        elif "why did you came to this world" in query:
            speak("Thanks to TLE. further It's a secret")
        elif 'is love' in query:
            speak("It is 7th sense that destroy all other senses")
        elif "who are you" in query:
            speak("I am a virtual assistant created by Vaishnavi")
#EMPTY BIN
        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True)
            speak("Recycle Bin Recycled")
#DONT LISTEN
        elif "don't listen" in query or "stop listening" in query:
            speak("for how much time you want to stop jarvis from listening commands")
            a = int(takeCommand(y))
            sleep(a)
            print(a)
# LOCATION
        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
            speak(location)
            webbrowser.open("https://www.google.com/maps/place/"+ location +"")
# NOTES
        elif "write a note" in query:
            speak("What should i write, sir")
            note = takeCommand(y)
            file = open('jarvis.txt', 'w')
            speak("Sir, Should i include date and time")
            snfm = takeCommand(y)
            if 'yes' in snfm or 'sure' in snfm:
                strTime = datetime.datetime.now()
                file.write(strTime)
                file.write(" :- ")
                file.write(note)
            else:
                file.write(note)        
        elif "show the note" in query:
            speak("Showing Notes")
            file = open("jarvis.txt", "r") 
            print(file.read())
            speak(file.read(6))
# EXIT      
        elif 'exit' in query or 'quit' in query:
            speak('Thank you for your time')
            exit()
コード例 #11
0
ファイル: test_winshell.py プロジェクト: Jatz/winshell
 def test_empty(self):
     recycle_bin = winshell.recycle_bin()
     recycle_bin.empty(confirm=False, show_progress=False, sound=False)
     self.assertFalse(list(recycle_bin))
コード例 #12
0
    def setupUi(self, MainWindow, c):
        self.currentItem = None
        self.currentItemCheck = False
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1200, 700)
        MainWindow.setMinimumSize(QtCore.QSize(1200, 700))
        MainWindow.setMaximumSize(QtCore.QSize(1200, 700))
        MainWindow.setStyleSheet("")
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
        self.tableWidget.setGeometry(QtCore.QRect(0, 99, 900, 581))
        self.tableWidget.setObjectName("tableWidget")
        #         self.tableWidget.setColumnCount(1)
        # #         self.tableWidget.setRowCount(1)
        #-----------------------------------columns------------------
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setVerticalHeaderItem(0, item)
        #-----------------------------------rows-------------------
        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setHorizontalHeaderItem(0, item)
        #---------------------------------------------------------

        item = QtWidgets.QTableWidgetItem()
        self.tableWidget.setItem(0, 0, item)
        self.tableWidget.horizontalHeader().setVisible(False)
        self.tableWidget.horizontalHeader().setDefaultSectionSize(220)
        self.tableWidget.verticalHeader().setVisible(False)
        self.tableWidget.verticalHeader().setDefaultSectionSize(150)
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 1200, 100))
        self.label.setStyleSheet(
            "background-image: url(:/header/images/Untitled-1.png);")
        self.label.setText("")
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(900, 269, 300, 411))
        self.label_2.setStyleSheet(
            "\n"
            "background-color: rgb(212, 212, 212); font: 63 10pt \"Segoe UI Semibold\";"
        )
        self.label_2.setObjectName("label_2")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(940, 120, 200, 50))
        self.pushButton.setStyleSheet(
            "background-image: url(:/header/images/btn-1_3.png);")
        self.pushButton.setText("")
        self.pushButton.setCheckable(False)
        self.pushButton.setAutoDefault(False)
        self.pushButton.setDefault(False)
        self.pushButton.setFlat(True)
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(940, 190, 200, 50))
        self.pushButton_2.setStyleSheet(
            "background-image: url(:/Buttons/images/btn-2_2.png);")
        self.pushButton_2.setText("")
        self.pushButton_2.setFlat(True)
        self.pushButton_2.setObjectName("pushButton_2")
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setGeometry(QtCore.QRect(310, 700, 118, 3))
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setGeometry(QtCore.QRect(900, 260, 301, 16))
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")

        self.pushButton_2.clicked.connect(self.RestoreButton)
        self.pushButton.clicked.connect(self.DeleteButton)

        #------------------------------------------------------
        # self.verticalLayoutWidget.hide()
        # self.verticalLayoutWidget_2.hide()
        self.tableWidget.cellClicked.connect(self.cellClicked)
        self.tableWidget.cellDoubleClicked.connect(self.cellDClicked)
        #-----------------------------------------------------
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1200, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        self.label_2.setWordWrap(True)
        self.tableWidget.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)

        if c == True:
            #---------------------------------------------------------Listing all the files from Trash---------------------

            r = list(winshell.recycle_bin())
            self.sizeOfList = len(r)
            if self.sizeOfList >= 4:
                self.tableWidget.setColumnCount(4)
                self.tableWidget.setRowCount(math.ceil(self.sizeOfList / 4))

            else:
                self.tableWidget.setColumnCount(self.sizeOfList)
                self.tableWidget.setRowCount(1)

            class DeletedObject:
                def __init__(self, obj, typeOfObj, name, sahiPath, size, addOn,
                             row, col):
                    self.obj = obj
                    self.typeOfObj = typeOfObj
                    self.name = name
                    self.sahiPath = sahiPath
                    self.size = size
                    self.addOn = addOn
                    self.row = row
                    self.col = col

            self.dictOfObjs = {}
            row = 0
            col = 0

            for i, v in enumerate(r):
                addOn = []
                col = i % 4
                if i != 0 and col == 0:
                    row += 1
                total = v.original_filename().split('\\')
                okPath = "\\\\".join(total)
                v.undelete()
                if os.path.isdir(okPath):
                    typee = "Folder"
                    size = self.get_dir_size(okPath)
                    addOn.append([
                        file for file in os.listdir(okPath)
                        if os.path.isdir(okPath + "\\" + file)
                    ])
                    addOn.append([
                        file for file in os.listdir(okPath)
                        if os.path.isfile(okPath + "\\" + file)
                    ])

                    self.FolderCreator(total[-1], row, col)
                elif os.path.isfile(okPath):
                    typee = "File"
                    size = os.path.getsize(okPath)
                    self.FileCreator(total[-1], row, col)
                winshell.delete_file(okPath)
                self.dictOfObjs[i] = DeletedObject(v, typee, total[-1], okPath,
                                                   size, addOn, row, col)

                # item = QTableWidgetItem(str(total[-1]+"|"+typee))
                # item.setFlags(item.flags() ^ Qt.ItemIsEditable)
                # self.tableWidget.setItem(row,col,item )
        elif c == False:
            if self.sizeOfList >= 4:
                self.tableWidget.setColumnCount(4)
                self.tableWidget.setRowCount(math.ceil(self.sizeOfList / 4))

            else:
                self.tableWidget.setColumnCount(self.sizeOfList)
                self.tableWidget.setRowCount(1)
            for k, v in self.dictOfObjs.items():
                if v.typeOfObj == "File":
                    self.FileCreator(v.name, v.row, v.col)
                elif v.typeOfObj == "Folder":
                    self.FolderCreator(v.name, v.row, v.col)
コード例 #13
0
def play():
    btn2['state'] = 'disabled'
    btn0['state'] = 'disabled'
    btn1.configure(bg='green')
    wishme()
    while True:
        btn1.configure(bg='dark blue')
        query = takeCommand().lower()
        if 'exit' in query:
            var.set("Bye sir")
            speak("Bye sir")
            btn1.configure(bg='#5C85FB')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            window.update()
            break

#general conversation

        elif 'hello' in query:
            var.set('Hello Sir')
            window.update()
            speak("Hello Sir")

        elif 'thank you' in query:
            var.set("Welcome Sir")
            window.update()
            speak("Welcome Sir")

        elif ('old are you' in query) or ('version' in query):
            var.set("Version 0.1.1 ")
            window.update()
            speak("I am a newbie sir ! Version 0.1.1")

        elif 'your name' in query:
            var.set("Myself SAIRA")
            window.update()
            speak("Myself SAIRA")

        elif 'who made you' in query:
            var.set("My Creator is Anubhav Singh")
            window.update()
            speak("My Creator is Anubhav Singh")

        elif 'sleep' in query:
            var.set('Sleeping...............')
            window.update()
            speak("OK Anubhav!! time to sleep have a good day")
            quit()

#System date and time
        elif 'time' in query:
            strtime = datetime.datetime.now().strftime("%I %M %S %p")
            var.set("Sir the time is %s" % strtime)
            window.update()
            speak("Sir the time is %s" % strtime)

        elif 'date' in query:
            strdate = datetime.datetime.today().strftime("%d %m %y")
            var.set("Sir today's date is %s" % strdate)
            window.update()
            speak("Sir today's date is %s" % strdate)

#open system folders and softwares

        elif 'open movies' in query:
            var.set("Opening Movies")
            window.update()
            speak("Opening Movies")
            os.startfile("D:\\Movies")

        elif 'open software' in query:
            var.set("Opening Software")
            window.update()
            speak("Opening Software")
            os.startfile("D:\\Software")

        elif 'series' in query:
            var.set("Opening OTD Series")
            window.update()
            speak("Opening OTD Series")
            os.startfile("E:\\OTD")

        elif 'code' in query:
            var.set("Opening V S Code")
            window.update()
            speak("Opening V S Code")
            os.startfile(
                "C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            )

        elif 'open youtube' in query:
            var.set('opening Youtube')
            window.update()
            speak('opening Youtube')
            webbrowser.open("youtube.com")

        elif 'open google' in query:
            var.set('opening google')
            window.update()
            speak('opening google')
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            var.set('opening stackoverflow')
            window.update()
            speak('opening stackoverflow')
            webbrowser.open('stackoverflow.com')

        elif 'open github' in query:
            var.set('opening github')
            window.update()
            speak('opening github')
            webbrowser.open('https://github.com/anubhavv1998')

        elif 'open media player' in query:
            var.set("opening VLC media Player")
            window.update()
            speak("opening V L C media player")
            os.startfile("C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe")

        elif 'open python' in query:
            var.set("Opening Python")
            window.update()
            speak("Opening Python")
            os.startfile(
                "C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python39\\python.exe"
            )

        elif 'open chrome' in query:
            var.set("Opening Google Chrome")
            window.update()
            speak("Opening Google Chrome")
            os.startfile(
                "C:\\Users\\Lenovo\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe"
            )

        elif 'open sublime' in query:
            var.set('Opening Sublime')
            window.update()
            speak('opening Sublime')
            os.startfile("C:\\Program Files\\Sublime Text 3\\sublime_text.exe")

        elif 'open anaconda' in query:
            var.set('Opening Anaconda')
            window.update()
            speak('opening anaconda')
            os.startfile("C:\\Users\\Lenovo\\anaconda3\\python.exe")

        elif 'news' in query:
            var.set('Opening news')
            window.update()
            news = webbrowser.open_new_tab(
                "https://timesofindia.indiatimes.com/home/headlines")
            speak(
                'Here are some headlines from the Times of India,Happy reading'
            )
            time.sleep(6)

#random module

        elif ('play music' in query) or ('music' in query):
            var.set('Here are your favorites')
            window.update()
            speak('Here are your favorites')
            music_dir = 'C:\\Users\\Lenovo\\Music\\Audio'
            songs = os.listdir(music_dir)
            n = random.randint(0, 71)
            os.startfile(os.path.join(music_dir, songs[n]))

#Wikipedia module

        elif 'wikipedia' in query:
            if 'open wikipedia' in query:
                webbrowser.open('wikipedia.com')
            else:

                try:
                    speak("searching wikipedia")
                    query = query.replace("according to wikipedia", "")
                    results = wikipedia.summary(query, sentences=1)
                    speak("According to wikipedia")
                    var.set(results)
                    window.update()
                    speak(results)
                except Exception as e:
                    var.set('sorry sir could not find any results')
                    window.update()
                    speak('sorry sir could not find any results')

#empty recycle bin

        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=True)
            speak("Recycle Bin Recycled")

#Wolframe Alpha API

        elif "calculate" in query:
            app_id = ""
            client = wolframalpha.Client(app_id)
            indx = query.lower().split().index('calculate')
            query = query.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            print("The answer is " + answer)
            speak("The answer is " + answer)

        elif "what is" in query or "who is" in query:
            client = wolframalpha.Client("")
            res = client.query(query)
            try:
                print(next(res.results).text)
                speak(next(res.results).text)
            except StopIteration:
                print("No results")
                speak('No results found')

#Google Map access

        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
            speak(location)
            webbrowser.open("https://www.google.nl/maps/place/" + location +
                            "")

#Open weather API

        elif 'weather' in query:
            api_key = ""
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
            speak("what is the city name")
            city_name = takeCommand()
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()
            if x["cod"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                speak(" Temperature in kelvin unit is " +
                      str(current_temperature) +
                      "\n humidity in percentage is " + str(current_humidiy) +
                      "\n description  " + str(weather_description))
                print(" Temperature in kelvin unit = " +
                      str(current_temperature) +
                      "\n humidity (in percentage) = " + str(current_humidiy) +
                      "\n description = " + str(weather_description))

#Open anything on youtube

        elif 'on youtube' in query:
            song = query.replace('play', '')
            var.set('Playing on Youtube')
            speak('playing' + song)
            pwt.playonyt(song)

#open camera

        elif 'click photo' in query:
            stream = cv2.VideoCapture(0)
            grabbed, frame = stream.read()
            if grabbed:
                cv2.imshow('pic', frame)
                cv2.imwrite('pic.jpg', frame)
                stream.release()
コード例 #14
0
def empty_recylcle_bin():
    """This Function Emyties Your Dirty Recyle Bin"""
    winshell.recycle_bin().empty(confirm=True, show_progress=True, sound=True)
    print("Recyle Bin is Emptied!")
コード例 #15
0
def cmds():
    while True:

        query = main.takeCommand().lower()

        if "lumos" in query:
            query.replace("lumos", "")

            if 'wikipedia' in query:
                main.speak('Searching Wikipedia...')
                query = query.replace("wikipedia", "")
                results = wikipedia.summary(query, sentences=3)
                main.speak("According to Wikipedia")
                print(results)
                main.speak(results)

            elif 'open youtube' in query:
                main.speak("Here you go to Youtube\n")
                webbrowser.get('chrome').open("youtube.com")

            elif 'open google' in query:
                main.speak("Here you go to Google\n")
                codePath = r"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
                os.startfile(codePath)

            elif 'open discord' in query:
                main.speak("Here you go to discord\n")
                codePath = r"C:\\Users\\Username\\AppData\\Local\\Discord\\Update.exe"
                os.startfile(codePath)

            elif 'open spotify' in query:
                main.speak("Here you go to spotify\n")
                codePath = r"C:\\Users\\Username\\AppData\\Roaming\\Spotify\\spotify.exe"
                os.startfile(codePath)

            elif 'open stackoverflow' in query:
                main.speak("Here you go to Stack Over flow.Happy coding")
                webbrowser.get('chrome').open("stackoverflow.com")

            elif 'how are you' in query:
                main.speak("I am fine, Thank you")
                main.speak("How are you")

            elif 'fine' in query or "good" in query:
                main.speak("It's good to know that your fine")

            elif "change my name to" in query:
                query = query.replace("change my name to", "")
                assname = query
                main.speak('okay')

            elif "change name" in query:
                main.speak("What would you like to call me")
                assname = takeCommand()
                main.speak("Thanks for naming me")

            elif "what's your name" in query or "What is your name" in query:
                main.speak("My friends call me")
                speak(assname)
                print("My friends call me", assname)

            elif 'exit' in query:
                main.speak("Thanks for giving me your time")
                exit()

            elif "who made you" in query or "who created you" in query:
                main.speak("I have been created by Astroclad.")

            elif 'joke' in query:
                main.speak(pyjokes.get_joke())

            elif 'search' in query or 'play' in query:

                query = query.replace("search", "")
                query = query.replace("play", "")
                webbrowser.open(query)

            elif "who am i" in query:
                main.speak("If you talk then definately your human.")

            elif "why you came to world" in query:
                main.speak("Thanks to Astroclad. further It's a secret")

            elif 'is love' in query:
                main.speak("It is 7th sense that destroy all other senses")

            elif "who are you" in query:
                main.speak("I am your virtual assistant created by Astroclad")

            elif 'reason for you' in query:
                main.speak("I was created as a Minor project by Astroclad")

            elif 'shutdown system' in query:
                main.speak(
                    "Hold On a Sec ! Your system is on its way to shut down")
                subprocess.call('shutdown / p /f')

            elif 'empty recycle bin' in query:
                winshell.recycle_bin().empty(confirm=False,
                                             show_progress=False,
                                             sound=True)
                main.speak("Recycle Bin Emptied")

            elif "don't listen" in query or "stop listening" in query:
                main.speak(
                    "for how much time you want to stop lumos from listening commands"
                )
                a = int(takeCommand())
                time.sleep(a)
                print(a)

            elif "where is" in query:
                query = query.replace("where is", "")
                location = query
                main.speak("User asked to Locate")
                main.speak(location)
                webbrowser.open("https://www.google.nl / maps / place/" +
                                location + "")

            elif "restart" in query:
                subprocess.call(["shutdown", "/r"])

            elif "hibernate" in query or "sleep" in query:
                main.speak("Hibernating")
                subprocess.call("shutdown / h")

            elif "log off" in query or "sign out" in query:
                main.speak(
                    "Make sure all the application are closed before sign-out")
                time.sleep(5)
                subprocess.call(["shutdown", "/l"])

            elif "write a note" in query:
                main.speak("What should i write")
                note = takeCommand()
                file = open('lumosNotes.txt', 'w')
                main.speak("Should i include date and time")
                snfm = takeCommand()
                if 'yes' in snfm or 'sure' in snfm:
                    strTime = datetime.datetime.now().strftime("% H:% M:% S")
                    file.write(strTime)
                    file.write(" :- ")
                    file.write(note)
                else:
                    file.write(note)

            elif "show note" in query:
                main.speak("Showing Notes")
                file = open("lumosNotes.txt", "r")
                print(file.read())
                main.speak(file.read(6))

            elif "wikipedia" in query:
                webbrowser.get('chrome').open("wikipedia.com")

            elif "Good Morning" in query:
                main.speak("A warm" + query)
                main.speak("How are you ")
                main.speak(assname)

            # most asked question from google Assistant
            elif "how are you" in query:
                main.speak("I'm fine, glad you asked me that")

            elif "what is" or "who is" in query:
                main.speak('thinking')
                if "lumos" in query:
                    query = query.replace("lumos", "")
                    print(query)

                client = wolframalpha.Client("UK8JT2-ATP7JRHVYR")
                res = client.query(str(query))

                try:
                    print(next(res.results).text)
                    main.speak(next(res.results).text)
                except Exception:
                    print("No results")
                    main.speak("Im sorry, i dont know that one")
コード例 #16
0
    def run_Bella(self):

        wishMe()
        while True:
        # if 1:
      
            self.query = self.takeCommand().lower()

            # Logic for executing tasks based on self.query
            if 'wikipedia' in self.query:
                speak('Searching Wikipedia...')
                self.query = self.query.replace("wikipedia", "")
                results = wikipedia.summary(self.query, sentences=2)
                speak("According to Wikipedia")
                print(results)
                speak(results)

            elif 'open youtube' in self.query:
                webbrowser.open("youtube.com")

            elif 'open google' in self.query:
                webbrowser.open("google.com")

            elif 'open stack overflow' in self.query:
                webbrowser.open("stackoverflow.com")   

            elif 'play' in self.query:
                song = self.query.replace('play', '')
                speak('playing ' + song)
                pywhatkit.playonyt(song)
            
            elif 'jokes' in self.query:
                speak(pyjokes.get_joke())    

            elif 'the time' in self.query:
                strTime = datetime.datetime.now().strftime("%H:%M:%S")    
                speak(f"Sir, the time is {strTime}")

            #elif 'open code' in self.query:
                #codePath = " C:\Users\dell\AppData\Local\Programs\Microsoft VS Code\code.exe"
                #os.startfile(codePath)

            elif 'open facebook' in self.query:
                webbrowser.open("https://www.facebook.com")
                speak("opening facebook") 

            elif 'open instagram' in self.query:
                webbrowser.open("https://www.instagram.com")
                speak("opening instagram")   

            elif 'open yahoo' in self.query:
                webbrowser.open("https://www.yahoo.com")
                speak("opening yahoo")
                
            elif 'open gmail' in self.query:
                webbrowser.open("https://mail.google.com")
                speak("opening google mail") 
                
            elif 'open snapdeal' in self.query:
                webbrowser.open("https://www.snapdeal.com") 
                speak("opening snapdeal")  
                
            elif 'open amazon' in self.query or 'shop online' in self.query:
                webbrowser.open("https://www.amazon.com")
                speak("opening amazon")

            elif 'open flipkart' in self.query:
                webbrowser.open("https://www.flipkart.com")
                speak("opening flipkart")  

            elif 'open ebay' in self.query:
                webbrowser.open("https://www.ebay.com")
                speak("opening ebay")     

            elif 'mail to sister' in self.query:
                try:
                    speak("What should I say?")
                    content = self.takeCommand()
                    to = "*****@*****.**"    
                    sendEmail(to, content)
                    speak("Email has been sent!")
                except Exception as e:
                    print(e)
                    speak("Sorry sir. I am not able to send this email")  

            elif 'send a mail' in self.query:
                try:
                    speak("What should I say?")
                    content = self.takeCommand()
                    speak("whome should i send")
                    to = input()    
                    sendEmail(to, content)
                    speak("Email has been sent !")
                except Exception as e:
                    print(e)
                    speak("I am not able to send this email")

            elif "change name" in self.query:
                speak("What would you like to call me, Sir ")
                assname = self.takeCommand()
                speak("Thanks for naming me")
    
            elif "what's your name" in self.query or "What is your name" in self.query:
                speak("My friends call me")
                speak(assname)
                print("My friends call me", assname)                


            elif 'good bye' in self.query:
                speak("good bye")
                exit()

            elif "shutdown" in self.query:
                speak("shutting down")
                os.system('shutdown -s') 

            elif "what\'s up" in self.query or 'how are you' in self.query:
                stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy','i am okey ! How are you']
                ans_q = random.choice(stMsgs)
                speak(ans_q)  
                ans_take_from_user_how_are_you = self.takeCommand()
                if 'fine' in ans_take_from_user_how_are_you or 'happy' in ans_take_from_user_how_are_you or 'okey' in ans_take_from_user_how_are_you:
                    speak('okey..')  
                elif 'not' in ans_take_from_user_how_are_you or 'sad' in ans_take_from_user_how_are_you or 'upset' in ans_take_from_user_how_are_you:
                    speak('oh sorry..') 

            elif 'make you' in self.query or 'created you' in self.query or 'develop you' in self.query:
                ans_m = " For your information shivam gupta Created me ! I give Lot of Thannks to Him "
                print(ans_m)
                speak(ans_m)

            elif "who are you" in self.query or "about you" in self.query or "your details" in self.query:
                about = "I am Bella an A I based computer program but i can help you lot like a your close friend ! i promise you ! Simple try me to give simple command ! like playing music or video from your directory i also play video and song from web or online ! i can also entain you i so think you Understand me ! ok Lets Start "
                print(about)
                speak(about)

            elif "hello" in self.query or "hello Bella" in self.query:
                hel = "Hello Sir ! How May i Help you.."
                print(hel)
                speak(hel)

            elif "your name" in self.query or "sweat name" in self.query:
                na_me = "Thanks for Asking my name my self ! Bella"  
                print(na_me)
                speak(na_me)

            elif "how you feel" in self.query:
                print("feeling Very sweet after meeting with you")
                speak("feeling Very sweet after meeting with you") 
            

            elif 'exit' in self.query or 'abort' in self.query or 'stop' in self.query or 'bye' in self.query or 'quit' in self.query :
                ex_exit = 'I feeling very sweet after meeting with you thankyou! for your time'
                speak(ex_exit)
                exit()   

            elif "calculate" in self.query: 
                
                app_id = "yourAppId"
                client = wolframalpha.Client(app_id)
                indx = self.query.lower().split().index('calculate') 
                self.query = self.query.split()[indx + 1:] 
                res = client.query(' '.join(self.query)) 
                answer = next(res.results).text
                print("The answer is " + answer) 
                speak("The answer is " + answer)    
            
            

            elif 'news' in self.query:
                
                try: 
                    jsonObj = urlopen('''https://newsapi.org/v2/top-headlines?country=in&apiKey=9655f3abc604484586897775536c8622''')
                    data = json.load(jsonObj)
                    i = 1
                    
                    speak('here are some top news from the times of india')
                    print('''=============== TIMES OF INDIA ============'''+ '\n')
                    
                    for item in data['articles']:
                        
                        print(str(i) + '. ' + item['title'] + '\n')
                        print(item['description'] + '\n')
                        speak(str(i) + '. ' + item['title'] + '\n')
                        i += 1
                except Exception as e:
                    
                    print(str(e))

            elif 'lock window' in self.query:
                    speak("locBella the device")
                    subprocess.call("shutdown / h")
    
            elif 'shutdown system' in self.query:
                    speak("Hold On a Sec ! Your system is on its way to shut down")
                    os.system('shutdown -s')
                    
            elif 'empty recycle bin' in self.query:
                winshell.recycle_bin().empty(confirm = False, show_progress = False, sound = True)
                speak("Recycle Bin Recycled")
    
            elif "don't listen" in self.query or "stop listening" in self.query:
                speak("for how much time you want to stop jarvis from listening commands")
                a = int(self.takeCommand())
                time.sleep(a)
                print(a)
    
            elif "where is" in self.query:
                self.query = self.query.replace("where is", "")
                location = self.query
                speak("User asked to Locate")
                speak(location)
                webbrowser.open("https://www.google.nl / maps / place/" + location + "")

            elif "restart" in self.query:
                subprocess.call(["shutdown", "/r"])
                
            elif "hibernate" in self.query or "sleep" in self.query:
                speak("Hibernating")
                subprocess.call("shutdown / h")
    
            elif "log off" in self.query or "sign out" in self.query:
                speak("Make sure all the application are closed before sign-out")
                time.sleep(5)
                subprocess.call(["shutdown", "/l"])
    
            elif "write a note" in self.query:
                speak("What should i write, sir")
                note = self.takeCommand()
                file = open('jarvis.txt', 'w')
                speak("Sir, Should i include date and time")
                snfm = self.takeCommand()
                if 'yes' in snfm or 'sure' in snfm:
                    strTime = datetime.datetime.now().strftime("% H:% M:% S")
                    file.write(strTime)
                    file.write(" :- ")
                    file.write(note)
                else:
                    file.write(note) 

            elif "show note" in self.query:
                speak("Showing Notes")
                file = open("jarvis.txt", "r") 
                print(file.read())
                speak(file.read(6))
    
                       

            elif "send message" in self.query:
                # You need to create an account on Twilio to use this service
                account_sid = 'your sid'
                auth_token = 'your token'
                client = Client(account_sid, auth_token)

                message = client.messages \
                .create(
                    body="Join Earth's mightiest heroes. Like Kevin Bacon.",
                    from_='+18707298456',
                    to='xxxxxxxxx'
                )

                print(message.sid)
                speak("message sent successfully")

            elif "what is" in self.query or "who is" in self.query:
                
                # Use the same API key 
                # that we have generated earlier
                client = wolframalpha.Client("your app id")
                res = client.query(self.query)
                
                try:
                    print (next(res.results).text)
                    speak (next(res.results).text)
                except StopIteration:
                    print ("No results") 

            elif 'open command' in self.query:
                codePath = "C:/WINDOWS/system32/cmd.exe"
                os.startfile(codePath) 

            elif 'close command' in self.query:
                os.system("taskkill /IM cmd.exe")    

            elif 'open notepad' in self.query:
                codePath = "C:\WINDOWS\system32/notepad.exe"
                os.startfile(codePath) 

            elif 'close notepad' in self.query:
                os.system("taskkill /IM notepad.exe")   

            elif 'open chrome' in self.query:
                codePath = "C:\Program Files (x86)\Google\Chrome\Application/chrome.exe"
                os.startfile(codePath)

            elif 'close chrome' in self.query:
                os.system("taskkill /IM chrome.exe")    


            elif 'take screenshot' in self.query or 'take a screenshot' in self.query:
                speak("sir,please tell me the name of this screenshot")
                name = self.takeCommand().lower()
                speak("sir,please hold the screen ,i am taBella a screenshot")
                time.sleep(3)
                img = pyautogui.screenshot()
                img.save(f"{name}.png")
                speak("i am done sir, screenshot is saved ")
            
            elif 'thank you ' in self.query or 'thanks' in self.query:
                speak("welcome sir")   

            elif "weather" in self.query:
             
                Google Open weather website
                to get API of Open weather 
                api_key = "api_key"
                base_url = "http://api.openweapip thermap.org / data / 2.5 / weather?"
                speak(" City name ")
                print("City name : ")
                city_name = self.takeCommand()
                complete_url = 'api.openweathermap.org/data/2.5/weather?q={jaipur}&appid={6eee755a887428d041cdef4103794fac}'

                response = requests.get(complete_url) 
                x = response.json() 
                
                if x["cod"] != "404": 
                    y = x["main"] 
                    current_temperature = y["temp"] 
                    current_pressure = y["pressure"] 
                    current_humidiy = y["humidity"] 
                    z = x["weather"] 
                    weather_description = z[0]["description"] 
                    print(" Temperature (in kelvin unit) = " +str(current_temperature)+"\n atmospheric pressure (in hPa unit) ="+str(current_pressure) +"\n humidity (in percentage) = " +str(current_humidiy) +"\n description = " +str(weather_description)) 
                
                else: 
                    speak(" City Not Found ")

            elif 'location' in self.query:
                speak('What is the location?')
                location = self.takeCommand()
                url = 'https://google.nl/maps/place/' + location + '/&'
                webbrowser.get('chrome').open_new_tab(url)
                speak('Here is the location ' + location)        
コード例 #17
0
def jarvisCore():

    while True:
        # if 1:
        query = takeCommand().lower()

        # Logic for executing tasks based on query
        if 'open facebook' in query:
            fb()
            jarvis()
        elif 'hello' in query:
            speak('Sir!')
            jarvis()
        elif 'clear bin' in query:
            try:
                winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)
                speak('Trash Cleared!')
            except Exception as e:
                speak('Bin is clean sir!')
            jarvis()
        elif 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            print(results)
            speak(f"According to Wikipedia, {results}")
            jarvis()
        elif 'power status' in query:
            bevents()
            jarvis()
        elif 'shutdown system' in query or 'shutdown' in query:
            speak("System Shut Down Initiated! Are you sure sir?")
            sysshutdown()
            jarvis()
        elif 'reboot system' in query:
            speak("System Shut Down Initiated! Are you sure sir?")
            sysreboot()
            jarvis()
        elif 'what' in query or 'weather' in query or 'get' in query:
            try:
                speak('searching...')
                res = wclient.query(query)
                results = next(res.results).text
                speak(f'Wolfram Alpha says,{results}')

            except Exception as e:
                print(e)
                speak('Sorry sir! No data, available!')
            jarvis()
        elif 'open youtube' in query:
           yt()
           jarvis()
        elif 'open google' in query:
            ggl()
            jarvis()

        elif 'open github' in query:
            git()
            jarvis()

        elif 'play music' in query:
            os.system(f"start AIMP3.exe {music_dir}")
            jarvis()

        elif 'stop music' in query or 'top music' in query:
            os.system("TASKKILL /F /IM AIMP3.exe")
            jarvis()
        elif "what's the time" in query:
            ctime()
            jarvis()

        elif 'open utorrent' in query:
            os.system('start uTorrent.exe')
            jarvis()
        elif 'read' in query or 'read screen' in query or 'read it' in query:
            speak('Select the text to read, then say, Start reading!')
            gspeak()
            jarvis()

        elif 'send a mail' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = Email_rp
                sendEmail(to, content)
                speak("Email has been sent!")
            except Exception as e:
                print(e)
                speak("Sorry sir! I am not able to send this email")
            jarvis()
コード例 #18
0
def process_text(query):
    try:
        if "open" in query:
            open_application(query)
            choice()
            return

        elif "time" in query:
            strtime = datetime.datetime.now().strftime("%H:%M %p")
            speak(f"Sir,the time is {strtime}")
            choice()
            return
        elif "day" in query and "birthday" not in query:
            day()
            choice()
            return
        elif "month" in query:
            month()
            choice()
            return
        elif "year" in query:
            strday = datetime.datetime.now().year
            speak(f"Sir,the year is {strday}")
            choice()
            return

        elif 'music' in query or "songs" in query or "song" in query:

            playsong()
            choice()
            return

        elif "movie" in query or "movies" in query:

            playmovie()
            speak("Sir,Tell me your next query")
            return
        elif "name" in query:
            speak("I am Aleeza. Your desktop Assistant")
            choice()
            return
        elif "who are you" in query or "yourself" in query:
            speakd = '''Hello, I am Person. Your personal Assistant.
            I am here to make your life easier. You can command me to perform
            various tasks such as calculating sums or opening applications etcetra'''
            speak(speakd)
            choice()
            return

        elif "who made you" in query or "created you" in query:
            speakd = "I have been created by Aviney Sir."
            speak(speakd)
            choice()
            return

        elif "send email" in query:
            try:
                speak("What should you want to say")
                content = takecommand()
                if (content != "None"):
                    speak("whom should i send.Enter in terminal")
                    to = input("Enter email address\n")
                    sendEmail(to, content)
                    speak("Email Sent successfully")
                else:
                    speak(
                        "Cannot able to judge what you are saying. So try again."
                    )

                choice()

            except Exception as e:
                print(e)
                speak("Sorry sir, I am not able to send this email")
                choice()
            return

        elif "gf" in query or "bf" in query:
            speak("I'm not sure about, may be you should give me some time")
            choice()
            return
        elif "calculate" in query:
            app_id = "K774XR-ELGY95LE8W"
            client = wolframalpha.Client(app_id)

            indx = query.lower().split().index('calculate')
            query2 = query.split()[indx + 1:]
            res = client.query(' '.join(query2))
            answer = next(res.results).text
            speak("The answer is " + answer)
            print(answer)
            choice()
            return
        elif 'search' in query or 'play' in query:
            # a basic web crawler using selenium
            search_input(query)
            return
        elif 'love' in query:
            speak("It is 7th sense that destroy all other senses")
            choice()
        elif "change background" in query:
            ctypes.windll.user32.SystemParametersInfoA(
                20, 0, "Location of wallpaper", 0)
            speak("Background changed successfully")
            choice()
            return
        elif "joke" in query:
            speak("Here's the joke")
            speak(pyjokes.get_joke())
            speak("Hope u enjoyed it")
            choice()
            return
        elif 'lock window' in query:
            speak("locking the device")
            ctypes.windll.user32.LockWorkStation()
            choice()
            return
        elif "shutdown" in query:
            speak("Are you sure you want to shutdown your computer?")
            ans = takecommand().lower()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                speak("Switching off your computer")
                os.system("shutdown /s")
            else:
                choice()
                return
        elif "hibernate" in query or "sleep" in query:
            speak("Are you sure you want to hibernate your computer?")
            ans = takecommand().lower()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                speak("Hibernating")
                os.system("shutdown /h")
            else:
                choice()
                return
        elif "restart" in query:
            speak("Are you sure you want to restart your computer?")
            ans = takecommand().lower()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                speak("Restarting")
                os.system("shutdown /r")
            else:
                choice()
                return

        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm=True,
                                         show_progress=True,
                                         sound=True)
            speak("Recycle Bin Recycled")
            choice()
            return

        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("Just wait for a moment")

            webbrowser.open("https://www.google.nl/maps/place/" + location +
                            "")
            choice()
            return

        elif "camera" in query or "take a photo" in query:
            camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
            ret, frame = camera.read()
            while (True):
                cv2.imshow('img', frame)
                speak("Would you like to save this photo?")
                ans = takecommand().lower()

                if 'yes' in str(ans) or 'yeah' in str(ans):

                    cv2.imwrite('c1.png', frame)
                    cv2.destroyAllWindows()

                    break
                else:
                    speak(
                        "As we didn't get the required output to save this photo,so we will deleting this photo"
                    )
                    cv2.destroyAllWindows()
                    break

            camera.release()
            choice()
            return

        elif 'news' in query:
            try:
                data = requests.get(
                    "https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=01ac17cb0ef940cb83d7e2d67f322844"
                ).json()
                speak('Here are some top news from the times of india')
                print('''=============== TIMES OF INDIA ============''' + '\n')
                i = 1
                for item in data['articles']:

                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    speak(str(i) + '. ' + item['title'] + '\n')
                    i += 1

                speak("That's All")
                choice()
                return
            except Exception as e:
                speak("Sorry,we could not complete your request at moment")

                choice()
                return

        elif "weather" in query:

            # Google Open weather website
            # to get API of Open weather
            api_key = "7862efd0c20c59a8764fe9c37b4d39e3"
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
            speak("What is the City name ")
            city_name = takecommand().lower()
            print(city_name)
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()

            if x["cod"] != "404":
                y = x["main"]
                current_temperature = y["temp"]
                current_pressure = y["pressure"]
                current_humidiy = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                speak(" Temperature (in kelvin unit) = " +
                      str(current_temperature) +
                      "\n atmospheric pressure (in hPa unit) =" +
                      str(current_pressure) +
                      "\n humidity (in percentage) = " + str(current_humidiy) +
                      "\n description = " + str(weather_description))
                print(" Temperature (in kelvin unit) = " +
                      str(current_temperature) +
                      "\n atmospheric pressure (in hPa unit) =" +
                      str(current_pressure) +
                      "\n humidity (in percentage) = " + str(current_humidiy) +
                      "\n description = " + str(weather_description))

            else:
                speak(" Sir,City Not Found ")
            choice()
            return

        else:

            speak("I can search the web for you, Do you want to continue?")
            ans = takecommand()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                search_input(ans.lower())
            else:
                speak("Ok,Then tell me another query?")
                return
    except Exception:

        speak(
            "I don't understand, I can search the web for you, Do you want to continue?"
        )
        ans = takecommand()
        if 'yes' in str(ans) or 'yeah' in str(ans):
            search_input(ans.lower())
        else:
            speak("Ok,Then tell me another query?")
            return
コード例 #19
0
ファイル: test_winshell.py プロジェクト: Jatz/winshell
 def test_factory_function(self):
     recycle_bin = winshell.recycle_bin()
     self.assertIsInstance(recycle_bin, winshell.ShellRecycleBin)
コード例 #20
0
ファイル: undelete_by_criteria.py プロジェクト: Jatz/winshell
import os
import datetime
import fnmatch
import winshell

midnight = datetime.datetime.today().replace(hour=0, minute=0, second=0)
for item in winshell.recycle_bin():
    if fnmatch.fnmatch(os.path.basename(item.original_filename()), "*.txt"):
        if item.recycle_date() >= midnight:
            print("About to undelete %r" % item)
コード例 #21
0
def action(text):
    if "how are you" in text:
        speak("I am fine")

    elif "setting" in text:
        os.system("start ms-settings:")

    elif "time" in text:
        tm = datetime.datetime.now().strftime(
            f"the date is %D and the time is %H:%M:%S")
        speak(tm)

    elif "music" in text:
        #rno = random.randint(0,2)
        mdir = "C:\\Users\\rohit\\desktop\\music"
        songs = os.listdir(mdir)
        os.startfile(os.path.join(mdir, songs[0]))

    elif "mail" in text:
        speak("what's the message")
        message = listen()
        msg = MIMEMultipart()
        msg['Subject'] = "AI Based Desktop Voice Assistant Test Mail"
        msg.attach(MIMEText(message, 'plain'))
        mail = smtplib.SMTP("smtp.gmail.com", 587)
        mail.ehlo()
        mail.starttls()
        mail.login("*****@*****.**", "Write Your Password Here")
        mail.sendmail("*****@*****.**",
                      "*****@*****.**", msg.as_string())
        mail.close()
        speak("mail has been sent successfully")

    elif "youtube" in text:
        speak("what do you want to search in youtube?")
        qr1 = listen()
        url = "https://www.youtube.com/results?search_query={}"
        search_url = url.format(qr1)
        webbrowser.open(search_url)
        speak("here are your search results")

    elif "google" in text:
        speak("what do you want to search in google?")
        qr2 = listen()
        url = "https://www.google.com/search?q={}"
        search_url = url.format(qr2)
        webbrowser.open(search_url)
        speak("here are your search results")

    elif "open chrome" in text:
        speak("Opening Google Chrome")
        os.startfile(
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe")

    elif "wikipedia" in text:
        speak("what do you want to search in wikipedia")
        query = listen()
        results = wikipedia.summary(query, sentences=2)
        url = wikipedia.page(query).url
        webbrowser.open(url)
        time.sleep(3)
        speak("according to wikipedia")
        speak(results)

    elif "weather" in text:
        speak("provide city name")
        city_name = listen()
        try:
            api_key = "30a009ff5a61bb5c03485abf62bf6fad"
            owm_obj = pyowm.OWM(api_key)
            obs_obj = owm_obj.weather_at_place(city_name)
            weather = obs_obj.get_weather()
            temp = weather.get_temperature('celsius')["temp"]
            humidity = weather.get_humidity()
            description = weather.get_detailed_status()
            reg = owm_obj.city_id_registry()
            city_id = reg.ids_for(city_name)
            url = "https://openweathermap.org/city/" + str(city_id[0][0])
            webbrowser.open(url)
            time.sleep(3)
            speak("current temperature is " + str(temp) + "celsius")
            speak("current humidity is " + str(humidity) + "%")
            speak("current weather description is " + description)
        except Exception as e:
            print(e)
            speak("City Not Found!, please provide correct city name")

    elif "news" in text:
        api_key = "b83225aa211a4f5c84002ef45d217086"
        try:
            jsonObj = urlopen(
                "https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey="
                + api_key)
            data = json.load(jsonObj)
            i = 1
            speak("here are some top news from the times of india")
            print("===============TIMES OF INDIA============\n")
            for item in data["articles"]:
                print(str(i) + ". " + item["title"] + "\n")
                print(item['description'] + '\n')
                speak(str(i) + ". " + item["title"] + "\n")
                i += 1
        except Exception as e:
            print(str(e))

    elif "calculate" in text:
        app_id = "AQXUVK-XUEUEKQ9VU"
        client = wolframalpha.Client(app_id)
        indx = text.lower().split().index("calculate")
        query = text.split()[indx + 1:]
        res = client.query(' '.join(query))
        answer = next(res.results).text
        speak("The answer is " + answer)

    elif "where is" in text:
        query = text.replace("where is", "")
        location = query
        webbrowser.open("https://www.google.nl/maps/place/" + location + "")
        time.sleep(3)
        speak(location + " is found here")

    elif "write a note" in text:
        speak("What's in your mind?")
        note = listen()
        file = open("notes.txt", "a")
        strTime = datetime.datetime.now().strftime("%D %H:%M:%S")
        file.write("\n\n" + strTime)
        file.write(" :- \n")
        file.write(note)
        file.close()
        speak("your note is saved thank you..")

    elif "show me note" in text:
        speak("Opening Notes")
        os.startfile("notes.txt")

    elif "joke" in text:
        speak(pyjokes.get_joke())

    elif "empty recycle bin" in text:
        winshell.recycle_bin().empty(confirm=False,
                                     show_progress=False,
                                     sound=True)
        speak("Recycle Bin is cleared")

    elif "camera" in text or "take a photo" in text:
        ec.capture(0, "Camera", "img.jpg")

    elif "word" in text:
        os.system("start winword")
        speak("microsoft word is opening")

    elif "excel" in text:
        os.system("start excel")
        speak("microsoft excel is opening")

    elif "powerpoint" in text:
        os.system("start powerpnt")
        speak("microsoft powerpoint is opening")

    elif "control panel" in text:
        os.system("control")
        speak("control panel is opening")

    elif "search file" in text or "search a file" in text:
        speak("tell me the file name that you want to search")
        query = listen()
        count = 0
        for root, dirs, files in os.walk("C:\\Users\\rohit\\Desktop"):
            for file in files:
                if query in file:
                    if file.endswith(".txt"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".py"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".png"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".jpg"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".jpeg"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".java"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".pdf"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".docs"):
                        count += 1
                        print(root + "\\" + str(file))
                    elif file.endswith(".xlsx"):
                        count += 1
                        print(root + "\\" + str(file))

        if count == 0:
            print("file does not exist")
            speak("file does not exist")
        else:
            speak("file found")

    elif "shutdown" in text:
        speak("Do you want to shutdown this pc?")
        ans = listen()
        if "yes" in ans:
            speak("Your pc is shutting down shortly")
            os.system("shutdown /s /t 1")

    elif "exit" in text:
        speak("bye bye, have a nice day")
        main.destroy()

    else:
        speak("no results found!")
コード例 #22
0
User:               Guodong
Create Date:        2017/4/25
Create Time:        9:53
 """
import codecs
import locale

import winshell


def get_system_encoding():
    """
    The encoding of the default system locale but falls back to the given
    fallback encoding if the encoding is unsupported by python or could
    not be determined.  See tickets #10335 and #5846
    """
    try:
        encoding = locale.getdefaultlocale()[1] or 'ascii'
        codecs.lookup(encoding)
    except Exception as _:
        del _
        encoding = 'ascii'
    return encoding


DEFAULT_LOCALE_ENCODING = get_system_encoding()
try:
    winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=False)
except Exception as e:
    print e, e.args[1].decode(DEFAULT_LOCALE_ENCODING)
コード例 #23
0
def shred(mode='Basic', path=''):
    """
    The Function shreds files in order to protect the user's identity.
    :param mode: the shredding mode: Basic, Safe, Complete
    :param path: the path to be shredded: Recycle Bin or Temporary files
    :return: None
    """
    start_time = time.perf_counter()
    failed_shredding = list()
    if mode == 'Basic':
        repeat = 1
    elif mode == 'Safe':
        repeat = 5
    else:  # mode == 'Complete':
        repeat = 10

    if path == 'Let Me Choose':
        path = random.choice(['Recycle Bin', 'Temporary Files'])

    executed = False  # An auxiliary boolean variable
    if path == 'Recycle Bin':
        object_list = list(winshell.recycle_bin())
        if object_list:  # if list is not empty
            print(f'Starting Shredding process at {path}\n')
            executed = True
            print(f'We are getting ready to shred {len(object_list)} files')
            time.sleep(1)
            for index, file_path in enumerate(object_list):
                for _ in range(repeat):
                    try:
                        success = False
                        file_path = '\\'.join(
                            file_path.original_filename().split('\\')
                        )  # adding double slash (\\) in the file_path
                        # undeleting the selected file
                        winshell.undelete(file_path.original_filename())
                        if not os.path.isdir(file_path):  # is file
                            success = shred_file(file_path)
                            if not success:  # if didn't succeed shredding the file
                                failed_shredding.append(file_path)
                        # deleting the selected file again
                        winshell.delete_file(file_path.original_filename())
                    except:
                        pass
                if (index + 1) == (len(object_list)):  # last file
                    sys.stdout.write(
                        f'\rShredding ({int(((index + 1) / len(object_list)) * 100)}%): {basename(file_path)}last'
                    )
                else:
                    sys.stdout.write(
                        f'\rShredding ({int(((index + 1) / len(object_list)) * 100)}%): {basename(file_path)}'
                    )

            # Emptying recycle bin.
            winshell.recycle_bin().empty(confirm=False,
                                         show_progress=False,
                                         sound=False)
            print('\nShredding Report:')
            print(
                f'Successfully shred: {len(object_list) - len(failed_shredding)} '
                f'out of {len(object_list)} Files || Failed to shred : '
                f'{len(failed_shredding)} files')
            finish_time = time.perf_counter()
        else:
            print('There are no items in the Recycle Bin to be shredded\n')

    elif path == 'Temporary Files':
        directory_path = r'c:\windows\temp'
        object_list = os.listdir(directory_path)
        files_list = []
        if object_list:
            while object_list:
                for file in object_list:
                    file_path = directory_path + file
                    if file_path not in files_list:
                        files_list.append(file_path)
                    object_list.remove(file)
            print(f'Starting Shredding process at {path}\n')
            executed = True
            print(f'We are getting ready to shred {len(files_list)} files')
            time.sleep(1)
            for index, file_path in enumerate(files_list):
                if (index + 1) == len(object_list):  # last file
                    sys.stdout.write(
                        f'\rShredding ({int((index / len(files_list)) * 100)}%): {basename(file_path)}last'
                    )
                else:
                    sys.stdout.write(
                        f'\rShredding ({int((index / len(files_list)) * 100)}%): {basename(file_path)}'
                    )
                for _ in range(repeat):
                    try:
                        if not os.path.isdir(file_path):  # is file
                            success = shred_file(file_path)
                            if not success:  # if didn't succeed shredding the file
                                failed_shredding.append(file_path)
                    except:
                        pass

            for file in files_list:
                os.remove(file)
            process = subprocess.Popen(
                'del /S /Q /F %s\\*.*' % directory_path,
                shell=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  # deleting all temporary files
            process.communicate()
            finish_time = time.perf_counter()
            print('\n\nShredding Report:')
            print(
                f'Successfully shredded: {len(files_list) - len(failed_shredding)} '
                f'out of {len(files_list)} Files || Failed to shred : '
                f'{len(failed_shredding)} files. Deleted: {len(files_list)}')

    if executed:
        print(
            f'Shredding has been finished in {progress_duration(finish_time - start_time)}'
        )
        from Graphic_Interface import display_notifications
        display_notifications('Shredding process has finished.')
    else:
        print(
            f"""We didn't shred any files since we couldn't find any in {path} """
        )
コード例 #24
0
def play():
    btn2['state'] = 'disabled'
    btn0['state'] = 'disabled'
    btn1.configure(bg='orange')
    wishme()
    while True:
        btn1.configure(bg='orange')
        query = takeCommand().lower()
        print(query)
        print(type(query))
        if 'exit' in query:
            var.set("Bye sir")

            btn1.configure(bg='#5C85FB')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            window.update()
            speak("Bye sir")
            break

        elif 'wikipedia' in query:
            if 'open wikipedia' in query:
                webbrowser.open('wikipedia.com')
            else:
                try:
                    speak("searching wikipedia")
                    query = query.replace("according to wikipedia", "")
                    results = wikipedia.summary(query, sentences=2)
                    speak("According to wikipedia")
                    var.set(results)
                    window.update()
                    speak(results)
                except Exception as e:
                    var.set('sorry sir could not find any results')
                    window.update()
                    speak('sorry sir could not find any results')
        elif 'clear bin' or 'recycle' in query:
            try:
                import winshell
                winshell.recycle_bin().empty(confirm=False,
                                             show_progress=False,
                                             sound=False)
                window.update()
                speak('Trash Cleared!')
            except Exception as e:
                window.update()
                speak('Bin is clean sir!')
        elif 'power status' in query:
            bevents()
            window.update()
        elif 'shutdown system' in query or 'shutdown' or 'shut down' in query:
            speak("System Shut Down Initiated! Are you sure sir?")
            sysshutdown()
            window.update()
        elif "joke" in query:
            # search query for joke
            speak("Looking for a good joke for you")
            my_joke = joke.tellAJoke()
            print(my_joke)
            window.update()
            speak(my_joke)
        elif 'reboot system' in query:
            speak("System Shut Down Initiated! Are you sure sir?")
            sysreboot()
            window.update()

        elif 'open youtube' in query:
            var.set('opening Youtube')
            window.update()
            speak('opening Youtube')
            query_text = query.split(' ')[1]
            ytb.playYoutubeVideo(query_text)

        elif 'open course error' in query:
            var.set('opening course era')
            window.update()
            speak('opening course era')
            webbrowser.open("coursera.com")

        elif 'open google' in query:
            var.set('opening google')
            window.update()
            speak('opening google')
            webbrowser.open("google.com")

        elif 'hello' in query:
            var.set('Hello Sir')
            window.update()
            speak("Hello Sir")

        elif 'open stackoverflow' in query:
            var.set('opening stackoverflow')
            window.update()
            speak('opening stackoverflow')
            webbrowser.open('stackoverflow.com')

        elif ('play music' in query) or ('change music' in query):
            var.set('Here are your favorites')
            window.update()
            speak('Here are your favorites')
            music_dir = 'D:\My Music\Favourites'  # Enter the Path of Music Library
            songs = os.listdir(music_dir)
            n = random.randint(0, 27)
            os.startfile(os.path.join(music_dir, songs[n]))

        elif 'the time' or 'time' in query:
            strtime = datetime.datetime.now().strftime("%H:%M:%S")
            var.set("Sir the time is %s" % strtime)
            window.update()
            speak("Sir the time is %s" % strtime)

        elif 'the date' or 'date' in query:
            strdate = datetime.datetime.today().strftime("%d %m %y")
            var.set("Sir today's date is %s" % strdate)
            window.update()
            speak("Sir today's date is %s" % strdate)

        elif 'thank you' in query:
            var.set("Welcome Sir")
            window.update()
            speak("Welcome Sir")

        elif 'can you do for me' in query:
            var.set(
                'I can do multiple tasks for you sir. tell me whatever you want to perform sir'
            )
            window.update()
            speak(
                'I can do multiple tasks for you sir. tell me whatever you want to perform sir'
            )

        elif 'old are you' in query:
            var.set("I am a little baby sir")
            window.update()
            speak("I am a little baby sir")

        elif 'open media player' in query:
            var.set("opening VLC media Player")
            window.update()
            speak("opening V L C media player")
            path = "C:\\Program Files\\VideoLAN\\VLC\\vlc.exe"  #Enter the correct Path according to your system
            os.startfile(path)

        elif 'your name' in query:
            var.set("Myself Jarvis Sir")
            window.update()
            speak('myself Jarvis sir')

        elif 'who creates you' in query:
            var.set('My Creator is Mr. Manoj')
            window.update()
            speak('My Creator is Mr. Manoj')

        elif 'say hello' in query:
            var.set('Hello Everyone! My self Jarvis')
            window.update()
            speak('Hello Everyone! My self Jarvis')

        elif 'open pycharm' in query:
            var.set("Openong Pycharm")
            window.update()
            speak("Opening Pycharm")
            path = "C:\\Program Files\\JetBrains\\PyCharm Community Edition 2018.3.2\\bin\\pycharm64.exe"  #Enter the correct Path according to your system
            os.startfile(path)

        elif 'open chrome' in query:
            var.set("Opening Google Chrome")
            window.update()
            speak("Opening Google Chrome")
            path = "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"  #Enter the correct Path according to your system
            os.startfile(path)

        elif 'email to me' in query:
            try:
                var.set("What should I say")
                window.update()
                speak('what should I say')
                content = takeCommand()
                to = a['name']
                sendemail(to, content)
                var.set('Email has been sent!')
                window.update()
                speak('Email has been sent!')

            except Exception as e:
                print(e)
                var.set("Sorry Sir! I was not able to send this email")
                window.update()
                speak('Sorry Sir! I was not able to send this email')

        elif "open python" in query:
            var.set("Opening Python Ide")
            window.update()
            speak('opening python Ide')
            os.startfile(
                'C:\\Users\\mridu\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.7\\IDLE (Python 3.7 64-bit)'
            )  #Enter the correct Path according to your system

        elif 'open code blocks' in query:
            var.set('Opening Codeblocks')
            window.update()
            speak('opening Codeblocks')
            os.startfile("C:\\Program Files (x86)\\CodeBlocks\\codeblocks.exe"
                         )  #Enter the correct Path according to your system

        elif 'open anaconda' in query:
            var.set('Opening Anaconda')
            window.update()
            speak('opening anaconda')
            os.startfile(
                "C:\\Users\\mridu\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Anaconda3 (64-bit)\\Anaconda Navigator"
            )  #Enter the correct Path according to your system

        elif 'calculation' in query:
            sum = 0
            var.set('Yes Sir, please tell the numbers')
            window.update()
            speak('Yes Sir, please tell the numbers')
            while True:
                query = takeCommand()
                if 'answer' in query:
                    var.set('here is result' + str(sum))
                    window.update()
                    speak('here is result' + str(sum))
                    break
                elif query:
                    if query == 'x**':
                        digit = 30
                    elif query in numbers:
                        digit = numbers[query]
                    elif 'x' in query:
                        query = query.upper()
                        digit = roman.fromRoman(query)
                    elif query.isdigit():
                        digit = int(query)
                    else:
                        digit = 0
                    sum += digit

        elif 'click photo' in query:
            stream = cv2.VideoCapture(0)
            grabbed, frame = stream.read()
            if grabbed:
                cv2.imshow('pic', frame)
                cv2.imwrite('pic.jpg', frame)
            stream.release()

        elif 'record video' in query:
            cap = cv2.VideoCapture(0)
            out = cv2.VideoWriter('output.avi', -1, 20.0, (640, 480))
            while (cap.isOpened()):
                ret, frame = cap.read()
                if ret:

                    out.write(frame)

                    cv2.imshow('frame', frame)
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        break
                else:
                    break
            cap.release()
            out.release()
            cv2.destroyAllWindows()
コード例 #25
0
import winshell

all_deleted_files = list(winshell.recycle_bin())
print(all_deleted_files)
コード例 #26
0
def recyclebin():
    winshell.recycle_bin().empty(confirm=True, show_progress=True, sound=True)