Exemplo n.º 1
0
def factsfunc():
    global mainwindow4
    global value4

    mainwindow4 = Frame(root, bg="#000000")
    mainwindow4.pack(side=TOP, fill=BOTH)

    value4 = Frame(mainwindow4 ,bg="#000066", borderwidth=5)
    value4.pack(side=TOP, fill=X)

    def factsing():
        xt = randfacts.getFact(True) 
        text.config(state=NORMAL)
        text.delete('1.0', END)
        text.insert(END, xt) 
        text.config(state=DISABLED)


    x = randfacts.getFact(True) 


    refreshing = Button(value4, image=refresh ,cursor="hand2",bg="#000066",activebackground="#000066",borderwidth=0, command=factsing)
    refreshing.pack(side=TOP, padx=50)

    scrollbar = Scrollbar(mainwindow4)

    text = Text(mainwindow4,yscrollcommand=scrollbar.set, font="helvetica 40 bold" )
    scrollbar.config(command=text.yview)
    scrollbar.pack(side=RIGHT, fill=Y)
    text.insert(END, x) 
    text.config(state=DISABLED)
    text.pack(fill=BOTH)
Exemplo n.º 2
0
def RandomFacts():
    try:
        x = randfacts.getFact()
        return x
    except Exception as e:
        print(e)
        return e
Exemplo n.º 3
0
    def hierarchy(self):
        if st.button("__Identify Clusters__"):
            funfacts = randfacts.getFact()
            st.info(
                str.join('',
                         ('Identifying... Here is a random fact: ', funfacts)))
            max_num_clusters = -np.infty
            num_clusters = []
            self.min_cluster_size = np.linspace(self.cluster_range[0],
                                                self.cluster_range[1], 25)

            for min_c in self.min_cluster_size:
                learned_hierarchy = hdbscan.HDBSCAN(
                    prediction_data=True,
                    min_cluster_size=int(
                        round(min_c * 0.01 *
                              self.sampled_embeddings.shape[0])),
                    **HDBSCAN_PARAMS).fit(self.sampled_embeddings)
                num_clusters.append(len(np.unique(learned_hierarchy.labels_)))
                if num_clusters[-1] > max_num_clusters:
                    max_num_clusters = num_clusters[-1]
                    retained_hierarchy = learned_hierarchy
            self.assignments = retained_hierarchy.labels_
            self.assign_prob = hdbscan.all_points_membership_vectors(
                retained_hierarchy)
            self.soft_assignments = np.argmax(self.assign_prob, axis=1)
            st.info('Done assigning labels for **{}** instances ({} minutes) '
                    'in **{}** D space'.format(
                        self.assignments.shape,
                        round(self.assignments.shape[0] / 600),
                        self.sampled_embeddings.shape[1]))
            st.balloons()
Exemplo n.º 4
0
def start():
    prompt = instruct_me()
    if 'who are you' in prompt:
        respond('I am your voice assistant!')
    elif 'how are you' in prompt:
        respond("I am fine, Thank you")
        respond("How are you, Sir")
    elif 'wish me' in prompt:
        hour = int(datetime.datetime.now().hour)
        if 0 <= hour < 12:
            respond("Good Morning Sir !")
        elif 12 <= hour < 18:
            respond("Good Afternoon Sir !")
        else:
            respond("Good Evening Sir !")
        respond('I am your assistant created by Medha!')
    elif 'who made you' in prompt:
        respond(
            'Medha from triple I T Allahabad made me , but how did she got time from her busy sleeping schedule!'
        )
    elif 'time' in prompt:
        respond(datetime.datetime.now().strftime('%I:%M %p'))
    elif 'play' in prompt:
        song = prompt.replace('play', '')
        respond('playing' + song)
        pywhatkit.playonyt(song)
    elif 'fact' in prompt:
        respond(randfacts.getFact())
    elif 'joke' in prompt:
        respond(pyjokes.get_joke())
    elif 'who is' in prompt:
        human = prompt.replace('who is', '')
        respond(wikipedia.summary(human, 2))
    elif 'what is a' in prompt:
        thing = prompt.replace('what is a', '')
        respond(wikipedia.summary(thing, 2))
    elif "what is the weather today" in prompt:
        respond("which city")
        city = instruct_me_2()
        humidity, temp, phrase = weatherReport(city)
        respond("currently in " + city + "  temperature is " + str(temp) +
                " degree celsius, " + "humidity is " + str(humidity) +
                " percent and sky is " + phrase)
    elif 'movie rating' in prompt:
        movie = prompt.replace('movie rating', '')
        imdbb = get_review(movie)
        imdbb = imdbb.split("/")
        respond('It has I M B D rating' + imdbb[0])
    else:
        respond('Please say again !')
Exemplo n.º 5
0
def run_assistant():
    try:
        with sr.Microphone() as source:
            print('Listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if assistant in command:
                print(command)
                command = command.replace(assistant, '', 1)
                if 'play' in command:
                    song = command.replace('play ', '', 1)
                    talk('playing' + song)
                    print(song)
                    pywhatkit.playonyt(song)
                elif 'time' in command:
                    time = datetime.datetime.now().strftime('%I:%M %p')
                    talk('The time is ' + time)
                elif 'who is' in command or 'what is' in command:
                    print(command)
                    topic = command.replace('who is ', '', 1)
                    topic = command.replace('what is ', '', 1)
                    info = wikipedia.summary(topic, 1)
                    talk(info)
                elif 'joke' in command:
                    talk(pyjokes.get_joke())
                elif 'random fact' in command:
                    fact = randfacts.getFact()
                    talk(fact)
                    print(fact)
                elif 'refresh' in command:
                    keyboard.press(Key.f5)
                    keyboard.release(Key.f5)
                else:
                    print(command)
                    talk('I did not understand that please say again')
            else:
                pass
            # print(command)
            # talk('I did not understand that please say again')
    except:
        pass
Exemplo n.º 6
0
def blast_search(query_name, path_name, query_sequence):
    """Submit a query nucleotide sequence to BLASTN, and output the raw data
    as an .xml file.

    Args:
        query_sequence ([string]): Nucleotide sequence to submit to BLASTN.
        query_name ([string]): User-defined name for query.
        path_name ([file path]): Directory to store output file in.

    Returns:
        output_path [file path]: Path to output .xml file.
    """
    # Submit query sequence to NCBI BLASTN and read results
    print('\nQuerying BLAST - This may take a long time during peak times.')
    for i in range(1,4):
        print('Querying BLASTN: Attempt ' + str(i))
        print((datetime.now()).strftime("%Y-%m-%d %H:%M:%S"))
        print('\n...whilst you\'re waiting, here\'s a randomly-generated',
            'interesting fact:')
        print(randfacts.getFact() + "\n")
        try:
            result_handle = NCBIWWW.qblast("blastn", "nt", query_sequence)
            break
        except Exception as ex:
            print('Error occurred: ', ex.__class__.__name__)
            if i == 3:
                print('Unable to access BLASTN. Exiting script.')
                exit()
    print('BLAST query complete.')
    blast_results = result_handle.read()
    result_handle.close()

    # Define file path for output file
    output_file = query_name + '_blast_output.xml'
    output_path = os.path.join(path_name, output_file)

    # Write output file
    with open(output_path, 'w') as save_file:
        save_file.write(blast_results)
    print("\nBLAST output xml file created.")

    return output_path
Exemplo n.º 7
0
def surprise(request):
    if not request.user.is_authenticated:
        return redirect('/login')
    fact = randfacts.getFact()
    # keep it lowercase, keep it classy
    fact = fact.lower()
    # randomly determine which post in existence they shall receive
    if randint(0, 1) == 1:
        count = Bell.objects.count()
        post = Bell.objects.all()[randint(0, count - 1)]
        post_type = 'Bell'
    else:
        count = Ring.objects.count()
        post = Ring.objects.all()[randint(0, count - 1)]
        post_type = 'Ring'
    return render(request, 'surprise.html', {
        'rand_fact': fact,
        'post': post,
        'post_type': post_type
    })
Exemplo n.º 8
0
 def randomforest(self):
     if st.button("Start training a random forest classifier"):
         try:
             x = self.sampled_features[self.assignments >= 0, :]
             y = self.assignments[self.assignments >= 0]
             x_train, self.x_test, y_train, self.y_test = train_test_split(x, y.T, test_size=self.part, random_state=42)
             funfacts = randfacts.getFact()
             st.info(str.join('', ('Training random forest classifier on randomly partitioned '
                                   '{}%...'.format((1 - self.part) * 100), 'Here is a random fact: ', funfacts)))
             self.validate_clf = RandomForestClassifier(random_state=42)
             self.validate_clf.fit(x_train, y_train)
             self.clf = RandomForestClassifier(random_state=42)
             self.clf.fit(x, y.T)
             self.predictions = self.clf.predict(self.features.T)
             st.info('Done training random forest classifier mapping '
                     '**{}** features to **{}** assignments.'.format(self.features.T.shape, self.predictions.shape))
             self.validate_score = cross_val_score(self.validate_clf, self.x_test, self.y_test, cv=self.it, n_jobs=-1)
             with open(os.path.join(self.working_dir, str.join('', (self.prefix, '_randomforest.sav'))), 'wb') as f:
                 joblib.dump([self.x_test, self.y_test, self.validate_clf, self.clf,
                              self.validate_score, self.predictions], f)
             st.balloons()
         except AttributeError:
             st.error('Sometimes this takes a bit to update, recheck identify clusters (previous step) '
                      'and rerun this in 30 seconds.')
Exemplo n.º 9
0
def move():
    facts = randfacts.getFact(True)
    c = "*)"
    label = Label(root, text=c + facts)
    label.pack()
Exemplo n.º 10
0
        r.adjust_for_ambient_noise(source, 1.2)
        print("listening..")
        audio = r.listen(source)
        vid = r.recognize_google(audio)
    print("Playing {} on youtube".format(vid))
    speak("Playing {} on youtube".format(vid))
    assist = music()
    assist.play(vid)

elif "news" in text2:
    print("Sure. Reading latest news")
    speak("Sure. Reading latest news")
    arr = news()
    for i in range(len(arr)):
        print(arr[i])
        speak(arr[i])

elif "fact" in text2:
    speak("Sure thing")
    x = randfacts.getFact()
    print(x)
    speak("Did you know that?" + x)

elif "joke" in text2:
    speak("Laughter on the way")
    arr = joke()
    print(arr[0])
    speak(arr[0])
    print(arr[1])
    speak(arr[1])
Exemplo n.º 11
0
def run_snake():
    command = take_command()
    print(command)
    if "time" in command:
        time = datetime.datetime.now().strftime("%H:%M:%S")
        print(time)
        talk("current time is " + time)
    #elif "my project" in command:
    #project_app()
    elif "shut down" in command:
        talk("do you really want to swich off your pc")
        if "yes" in take_command():
            shut_down.power_off()
            talk("finished")
        else:
            exit()
    elif "boot" in command:
        talk("Do you really want to restart your pc")
        if "yes" in take_command():
            shut_down.reboot_pc()
            talk("finished")
        else:
            exit()
    elif "play" in command:
        song = command.replace("play", "")
        talk("playing" + song)
        youtb.playonyt(song)
    elif "body mass index" in command:
        bmi.bmi_calculator()
    elif "text" in command:  #will write what i will say
        command = command.replace("text", "")
        myText = open(
            r'C:\Users\Cristian\AppData\Local\Programs\Python\Python39\Lib\voice_assistant\voice_command.txt',
            'a+')
        mystring = command
        myText.write(mystring + "\n")
        myText.close()
    #elif "body mass index" in command:
    #os.system(r'C:\Users\Cristian\AppData\Local\Programs\Python\Python39\Lib\BMI\dist\bmi\bmi.exe')
    #exit()
    elif "wikipedia" in command:
        person = command.replace("wikipedia", "")
        info = wikipedia.summary(person, 5)
        talk(info)
        text_info = open(
            r'C:\Users\Cristian\AppData\Local\Programs\Python\Python39\Lib\voice_assistant\wikipedia.txt',
            'a+')
        my_text = info
        text_info.write(my_text + "\n")
        text_info.close()
    elif "random fact" in command:
        facts = randfacts.getFact(True)
        talk(facts)
        print(facts)
    elif "search" in command:
        command = command.replace("search", "")
        pywhatkit.search(command)
    elif "dictionary" in command:
        command = command.replace("dictionary", "")
        dit = PyDictionary()
        meaning = dit.meaning(command)
        talk(meaning)
        inf_dex = open(
            r'C:\Users\Cristian\AppData\Local\Programs\Python\Python39\Lib\voice_assistant\dictionar.txt',
            'a+')
        inf_dex.write(str(meaning) + "\n")
        inf_dex.close()
    elif "translate" in command:
        command = str(command.replace("translate", ""))
        translator = Translator(to_lang="romanian")
        var_t = translator.translate(command)
        nf_translate = open(
            r'C:\Users\Cristian\AppData\Local\Programs\Python\Python39\Lib\voice_assistant\translate.txt',
            'a+')
        nf_translate.write(str(var_t) + "\n")
        nf_translate.close()
        talk(var_t)
        print(var_t)
    elif "battery" in command:
        battery_percent.battery()

    elif "exit " in command:
        exit()

    else:
        raise Exception("error")
Exemplo n.º 12
0
    for key in list_ppl.keys():
        double_tab()
        pag.typewrite(key)
        pag.press("tab")
        if list_ppl[key] == "Small":
            pag.press("down")
            double_tab()
        elif list_ppl[key] == "Medium":
            pag.press("down")
            pag.press("down")
            double_tab()
        elif list_ppl[key] == "Large":
            pag.press("down")
            pag.press("down")
            pag.press("down")
            double_tab()
        elif list_ppl[key] == "X-Large":
            pag.press("down")
            pag.press("down")
            pag.press("down")
            pag.press("down")
            double_tab()
        else: 
            pag.press("tab")
        pag.typewrite(rf.getFact())
        pag.press("tab")
        pag.press("enter")
        wb.open("https://docs.google.com/forms/d/e/1FAIpQLScZNtLeMjj8esUbkMKT3jymXq9HQ6n0Lu8RuzVcmulSsXd4gw/viewform")
        time.sleep(5)
    print("all forms were filled in successfully")
Exemplo n.º 13
0
def GetRandomFact():
    r = randfacts.getFact()
    return r
Exemplo n.º 14
0
def chatbot(message):
    original_message = message
    message = original_message.split()
    # Break message by space, if [0] == "/sum" sum = [1]+[2]
    if message[0] == "/sum":
        numbers = original_message.replace('/sum', '').split()
        s = 0
        for x in numbers:
            c = int(x)
            s += c
        j = ' '.join(numbers)
        response = "Sum of Given Number " + str(s)

    elif message[0] == "/diff":
        response = int(message[2]) - int(message[1])

    elif message[0] == "/multi":
        response = int(message[1]) * int(message[2])

    elif message[0] == "/power":
        response = int(message[1])**int(message[2])

    elif message[0] == "/sqrt":
        response = int(message[1])**(1 / 2)

    elif message[0] == "/cbrt":
        response = int(message[1])**(1 / 3)

    elif message[0] == "/fact":
        #try:
        factorial = 1
        num = int(message[1])
        if num < 0:
            response = "Sorry, factorial does not exist for negative numbers"
        elif num == 0:
            response = "The factorial of 0 is 1"
        else:
            for i in range(1, num + 1):
                factorial = factorial * i
                response = "The factorial of " + str(num) + " is " + str(
                    factorial)

        #except:
        #    response= "Error"
    elif message[0] == "/reword":
        l = message[0]
        r = l[::-1]
        if l == r:
            response = "Word is Palindrome!"
        else:
            response = "Word in not Palindrome!"
    elif message[0] == "/dict":
        response = "Meaning: " + str(dictionary.meaning(
            message[1])) + "<br><br>" + "Synonyms: " + str(
                dictionary.synonym(
                    message[1])) + "<br><br>" + "Antonyms: " + str(
                        dictionary.antonym(message[1]))

    elif message[0] == "/translate":
        try:
            tmessage = original_message.replace('/translate', '').splitlines()
            omessage = tmessage[1]
            translator = Translator(to_lang="hi")
            translation = translator.translate(omessage)
            response = "Your Translation: " + str(translation)
        except:
            response = "Failed to translate"

    elif message[0] == "/wiki":
        #c=message[1].lower()
        message.pop(0)
        message = "".join(message)
        response = str(wikipedia.summary(message, sentences=5))

    elif message[0] == "/search":
        message.pop(0)
        message = "".join(message)
        response = ""
        for j in gsearch(message):
            response = str(response) + str(j) + str("\n")

    elif message[0] == "/jokes":
        url = urllib.request.urlopen(
            "https://official-joke-api.appspot.com/jokes/random")
        response = url.read().decode()
    elif message[0] == "/gen":
        message = "".join(message)
        n = message[0]
        password_characters = string.punctuation
        n1 = string.digits
        p1 = ''.join(random.choice(n1) for j in range(7))
        p = ''.join(random.choice(password_characters) for i in range(4))
        c = n[0].upper() + p + n[1:] + p1
        response = str(c)

    elif message[0] == "/time":
        strTime = datetime.datetime.now().strftime("%H:%M:%S")
        response = "Sir Time is: " + str(strTime)

    #/addcontact
    #name
    #phone
    #email
    elif message[0] == "/addcontact":
        try:
            contact_details = original_message.replace('/addcontact',
                                                       '').splitlines()
            name = contact_details[1]
            mobile = contact_details[2]
            email = contact_details[3]
            x = employee(name=name, mobile=mobile, email=email)
            x.save()
            response = "Contact added!"
        except:
            response = "Please send details in correct format as below:"
            response += "<br>/addcontact<br>Name<br>Phone<br>Email"

    elif message[0] == "/searchcontact":
        srch = message[1]
        if srch:
            match = employee.objects.filter(
                Q(name__icontains=srch) | Q(email__icontains=srch))

            if match:
                response = "I got following results - <br><br>"
                for each_match in match:
                    response += "Name: " + each_match.name + "<br>"
                    response += "Mobile: " + each_match.mobile + "<br>"
                    response += "Email: " + each_match.email + "<br><br>"
            else:
                response = "No contact found"

    elif message[0] == "/sendmail":
        try:
            email_detail = original_message.replace('/sendmail',
                                                    '').splitlines()
            to = email_detail[1]
            content = email_detail[2]
            sendEmail(to, content)
            response = "Mail sent"
        except Exception as e:
            print(e)
            response = "Not able to send email Sorry!"

    elif message[0] == "/help":
        response = "Here the things I can do" + "<br>" + "/dict <word>: to find any word meaning with antonyms and Synonyms " + "<br>" + "/translate: to translate any sentence in Hindi language" + "<br>" + "/wiki <word>: to find any information on Wikipedia" + "<br>" + "/search <word>: to find any information on google.com" + "<br>" + "/addcontact: to add any contact detail on server" + "<br>" + "Here is the format to add Contact in a proper way:" + "<br>" + "/addcontact" + "<br>" + "[Name]" + "<br>" + "[Mobile Number]" + "<br>" + "[Email]" + "<br>" + "/searchcontact: to search any contact detail on server" + "<br>" + "Here is the format to search contact on the server" + "<br>" + "/searchcontact [Name]" + "<br>" + "/jokes: to get any randrom jokes" + "<br>" + "/facts: to get interesting random facts" + "<br>" + "/weather <City Name>: To get any details of Weather of any city" + "<br>" + "/gen: to generate random password" + "<br>" + "/sendmail: Used to send message through mail" + "<br>" + "Send Email in the following:<br>" + "/sendmail<br>" + "[Email Address]" + "<br>" + "[Content/Message]" + "<br>" + "/time: it can also show current time"

    elif message[0] == "/weather":
        response = Weather.weather(message[1])
        '''api_key = "ac9ae5f24855de6ba928d40fc22af036"
        base_url = "http://api.openweathermap.org/data/2.5/weather?"
        city_name = message[1].capitalize()
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        r = requests.get(complete_url)
        x = r.json()
        if x["cod"] != "404":
            y = x["main"]
            current_temperature = y["temp"]
            current_pressure = y["pressure"]
            current_humidity = y["humidity"]
            z = x["weather"]
            weather_description = z[0]["description"]
            current_tempc = float(current_temperature) - 273.15 
            response = "Temperature (in Celcius) = "+str(current_tempc)+"<br> Atmospheric Pressure (in hPa unit) = "+str(current_pressure)+"<br> Humidity (in percent) = "+str(current_humidity)+"<br> Description = "+str(weather_description)
        else:
            response = "City Not Found"'''

    elif message[0] == "/facts":
        x = randfacts.getFact()
        response = str(x)

    elif message[0] == "/prime":
        try:
            num = int(message[1])
            if num > 1:
                for i in range(2, num):
                    if (num % i) == 0:
                        response = str(num) + " is not a prime number"
                        response = str(i) + " times " + str(
                            num // i) + " is " + str(num)
                        break
                    else:
                        response = str(num) + " is a prime number"
            ##else:
            #response=num+" is not a prime number"
        except:
            response = "Please enter correct format"  # don't run next condition

    elif message[0].lower() == "hi" or message[0].lower(
    ) == "hello" or message[0].lower() == "hey":
        response = "Hello there! I'm Anjan's bot, type /help to see list of commands :)"
    else:
        response = "Hi, I don't know this command"

    return response
Exemplo n.º 15
0
 async def randomfact(self,ctx):
     await ctx.send(randfacts.getFact())
Exemplo n.º 16
0
 def factsing():
     xt = randfacts.getFact(True) 
     text.config(state=NORMAL)
     text.delete('1.0', END)
     text.insert(END, xt) 
     text.config(state=DISABLED)
Exemplo n.º 17
0
def TaskExecution():
    wish()
    while True:
        query = takecommand()

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<Logic Building to perform tasks>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        date = datetime.datetime.today().strftime("%I:%M %p")

        if "time now" in query:
            speak("The time is now " + date + "")

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

        elif 'open google' in query or 'search in google' in query:
            speak("What should i search on Google")
            google = takecommand().lower()
            webbrowser.open(f'www.google.com/search?q=' + google)
            speak("Searching in google...")

        elif 'open bing' in query or 'search in bing' in query:
            speak("What should i search on Bing")
            bing = takecommand().lower()
            webbrowser.open(f'www.bing.com/search?q=' + bing)
            speak("Searching in Bing...")

        elif 'open duckduckgo' in query or 'search in duckduckgo' in query:
            speak("What should i search on DuckDuckGo")
            duck = takecommand().lower()
            webbrowser.open(f'www.duckduckgo.com/search?q=' + duck)
            speak("Searching in DuckDuckGo...")

        elif 'open youtube' in query:
            speak("What do you want me to play")
            youtube = takecommand().lower()
            pywhatkit.playonyt(youtube)
            speak("Playing...")

        elif "my ip" in query:
            ip = get('https://api.ipify.org').text
            speak(f"Your ip address is {ip}")

        elif 'open wikipedia' in query:
            speak("What do you want to know from Wikipedia?")
            wiki = takecommand().lower()
            info = wikipedia.summary(wiki, 2)
            speak("According to Wikipedia")
            speak(info)

        elif "open notepad" in query:
            npath = "C:\\Windows\\system32\\notepad.exe"
            os.startfile(npath)

        elif "open cmd" in query:
            os.system("start cmd")

        elif 'open task manager' in query:
            tpath = "C:\\Windows\\system32\\Taskmgr.exe"
            os.startfile(tpath)

        elif "open steam" in query:
            spath = "C:\\Program Files (x86)\\Steam\\steam.exe"
            os.startfile(spath)

        elif "open epic games" in query:
            epath = "C:\\Program Files (x86)\\Epic Games\\Launcher\\Portal\\Binaries\\Win32\\EpicGamesLauncher.exe"
            os.startfile(epath)

        elif "open browser" in query:
            bpath = "C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe"
            os.startfile(bpath)
            speak("Opening Edge...")

        elif 'developer' in query or 'made you' in query:
            speak("My Developer is Niaz Mahmud Akash and Jalish Mahmud Sujon")

        elif 'thanks' in query or 'thank you' in query or 'thanks a lot' in query:
            thanks = ["Glad to help you.", "Happy to help", "You're welcome"]
            thanks_random = random.choice(thanks)
            speak(thanks_random)

        elif 'browser' in query:
            webbrowser.open_new('www.google.com')
            speak("Opening Browser...")

        elif 'open facebook' in query:
            webbrowser.open('www.facebook.com')
            speak("Opening Facebook...")

        elif 'open twitter' in query:
            webbrowser.open('www.twitter.com')
            speak("Opening Twitter...")

        elif 'open telegram' in query:
            webbrowser.open('https://web.telegram.org/')
            speak("Opening Telegram...")

        elif 'open youtube' in query:
            webbrowser.open('www.youtube.com')
            speak("Opening Youtube...")

        elif 'open play store' in query:
            webbrowser.open('https://play.google.com/store/apps')
            speak("Opening Google PlayStore...")

        elif 'open instagram' in query:
            webbrowser.open('www.instagram.com')
            speak("Opening Instagram...")

        elif 'love me' in query:
            love = [
                "Of course. You're one of a kind.",
                "Is that a thing to ask? Of course I LOVE YOU ❤",
                "Yes, in an at-your-service sor of way"
            ]
            love_random = random.choice(love)
            speak(love_random)

        elif 'i love you' in query:
            express = [
                "That's so amazing to hear", "I LOVE ME Too!",
                "If I was you, I'd love me too.",
                "Of course you do! Friends don't hate each other."
            ]
            express_random = random.choice(express)
            speak(express_random)

        elif 'will you go on a' in query:
            go = [
                "Sure. Just let me know the place and time",
                "I'd go anywhere you take me"
            ]
            go_random = random.choice(go)
            speak(go_random)

        elif 'you robot' in query or 'are you human' in query:
            speak(
                "Yes, I am a Robot but a smart one. Let me prove it to you. How can i help you?"
            )

        elif 'your name' in query:
            speak("My name is Alice. I am your virtual personal assistant.")

        elif 'how are you' in query or 'hows things' in query or 'how you doing' in query:
            how = ["I am fine. What about you?", "I am good. How are you?"]
            how_random = random.choice(how)
            speak(how_random)

        elif 'marry me' in query:
            marry = [
                "This is one of those things we both have to agree on. I'd prefer to keep our relationship friendly. Romance makes me incredibly awkward",
                "It's not possible"
            ]
            marry_random = random.choice(marry)
            speak(marry_random)

        elif 'about nidhi' in query:
            speak("She can suck my pussy")

        elif 'happy' and 'valentines' in query:
            speak("Happy Valentines Day.")

        elif 'mothers name' in query or 'your mother' in query:
            mname = [
                "I have no mother. I am an Ai", "Every user is my family",
                "It takes a village to raise a virtual assistant"
            ]
            mname_random = random.choice(mname)
            speak(mname_random)

        elif 'your boss' in query:
            speak("You are")

        elif 'where am' in query or 'location' in query or 'where are we' in query:
            location()

        elif 'take a screenshot' in query or 'screenshot' in query:
            speak('What should be the name of this screenshot?')
            name = takecommand().lower()
            speak('Taking Screenshot')
            time.sleep(2)
            img = pyautogui.screenshot()
            img.save(f"{name}.png")
            speak('Screenshot Saved')

        elif 'fact' in query or 'facts' in query:
            x = randfacts.getFact()
            speak(x)

        elif 'annoying' in query or 'you suck' in query:
            dtalk = [
                "I am sorry", "You can report about me in GitHub",
                "Sorry, i am just an ai"
            ]
            dtalk_random = random.choice(dtalk)
            speak(dtalk_random)

        elif 'youre cute' in query or 'smart' in query or 'you are cute' in query or 'you are creepy' in query:
            cute = [
                "Thank you", "Thanks", "Thanks, that means a lot",
                "Much obliged!", "Well, that makes two of us!"
            ]
            cute_random = random.choice(cute)
            speak(cute_random)

        elif 'you live' in query or 'your home' in query:
            live = [
                "I live in your computer",
                "I live in a place filled with games",
                "I live in Servers of Github", "I live in the internet"
            ]
            live_random = random.choice(live)
            speak(live_random)

        elif 'news' in query:
            speak("Sure. Getting News...")
            news()

        elif 'system' and 'report' in query or 'system' and 'status' in query:
            battery = psutil.sensors_battery()
            cpu = psutil.cpu_percent(interval=None)
            percentage = battery.percent
            speak(
                f"All Systems are running. Cpu usage is at {cpu} percent. We have {percentage} percent battery."
            )

        elif 'like me' in query:
            like = [
                "Yes, I like you", "I like you well enough so far",
                "Of Course", "I don't hate you"
            ]
            like_random = random.choice(like)
            speak(like_random)

        elif 'what are you doing' in query or 'thinking' in query:
            think = [
                "Thinking about my future",
                "I am trying to figure out what came first? Chicken or egg.",
                "Algebra",
                "I plan on waiting here quietly until someone asks me a question"
            ]
            think_random = random.choice(think)
            speak(think_random)

        elif 'about me' in query:
            speak("You're Intelligent and ambitious")

        elif 'dictionary' in query:
            speak("Dictionary Opened")
            while True:
                dinput = takecommand()
                try:
                    if 'close' in dinput or 'exit' in dinput:
                        speak("Dictionary Closed")
                        break
                    else:
                        dictionary = PyDictionary(dinput)
                        speak(dictionary.getMeanings())

                except Exception as e:
                    speak("Sorry, I am not able to find this.")

        elif 'date' in query or 'day' in query:
            x = datetime.datetime.today().strftime("%A %d %B %Y")
            speak(x)

        elif 'zodiac' in query:
            zodiac()

        elif 'horoscope' in query:
            speak("Do you know your Zodiac Sign?")
            z = takecommand().lower()
            if 'no' in z:
                zodiac()
            elif 'yes' in z or 'yeah' in z:
                speak("What is your Zodiac Sign?")
                sign = takecommand()
                speak(
                    "Do you want to know the horoscope of today, tomorrow or yesterday?"
                )
                day = takecommand()
                params = (('sign', sign), ('day', day))
                response = requests.post('https://aztro.sameerkumar.website/',
                                         params=params)
                json = response.json()
                print("Horoscope for", json.get('current_date'), "\n")
                speak(json.get('description'))
                print('\nCompatibility:', json.get('compatibility'))
                print('Mood:', json.get('mood'))
                print('Color:', json.get('color'))
                print('Lucky Number:', json.get('lucky_number'))
                print('Lucky Time:', json.get('lucky_time'), "\n")

        # How to Do Mode
        elif 'activate how to' in query:
            speak("How to mode is activated.")
            while True:
                speak("Please tell me what do you want to know?")
                how = takecommand()
                try:
                    if 'exit' in how or 'close' in how:
                        speak("How to do mode is closed")
                        break
                    else:
                        max_results = 1
                        how_to = search_wikihow(how, max_results)
                        assert len(how_to) == 1
                        how_to[0].print()
                        speak(how_to[0].summary)
                except Exception as e:
                    speak("Sorry. I am not able to find this")

        elif 'temperature' in query or 'weather today' in query:
            temperature()

        # Little Chitchat
        elif 'hello' in query or 'hi' in query or 'hey' in query:
            speak("Hello, How are you doing?")
            reply = takecommand().lower()

            if 'what' and 'about' and 'you' in reply:
                how2 = ["I am fine.", "I am good."]
                how2_random = random.choice(how2)
                speak(how2_random)

            elif 'not good' in reply or 'bad' in reply or 'terrible' in reply:
                speak("I am sorry to hear that. Everything will be okay.")

            elif 'great' in reply or 'good' in reply or 'excellent' in reply or 'fine' in reply:
                speak("That's great to hear from you.")

        elif 'help' in query or 'what can you do' in query or 'how does it work' in query:
            do = [
                "I can tell you Time", "Joke", "Open browser",
                "Open Youtube/Facebook/Twitter/Telegram/Instagram",
                "Open or Close applications", "Search in Wikipedia",
                "Play videos in Youtube", "Search in Google/Bing/DuckDuckGo",
                "I can calculate", "Learn how to make or do something.",
                "Switch Window", "Play news",
                "Tell you about interesting facts",
                "Temperature of you current location", "Can take Screenshot",
                "Can find your location", "Shutdown/Restart Computer",
                "Horoscope", "Dictionary", "Zodiac Sign Calculator",
                "System Report"
            ]
            for does in do:
                speak(does)

        elif 'introduce yourself' in query or 'who are you' in query:
            speak(
                "I am Alice. Your personal virtual Assistant. Developed by Jalish Mahmud Sujon and Niaz Mahmud Akash in 2021."
            )

        elif 'go to sleep' in query:
            speak("Sleep mode activated. If you need me just say Wake up.")
            break

        elif 'goodbye' in query:
            speak("Good bye. Have a Lovely day.")
            sys.exit()

        # To close Applications
        elif 'shutdown' in query:
            speak("Shutting Down")
            os.system("shutdown /s /t 5")
            sys.exit()

        elif 'restart' in query:
            speak("Restarting Computer")
            os.system("shutdown /r /t 5")
            sys.exit()

        elif "close notepad" in query:
            speak("Closing Notepad")
            os.system("taskkill /f /im notepad.exe")

        elif "close browser" in query:
            speak("Closing Browser")
            os.system("taskkill /f /im edge.exe")

        elif "close steam" in query:
            speak("Closing Steam")
            os.system("taskkill /f /im steam.exe")

        elif "close epic games" in query:
            speak("Closing Epic Games")
            os.system("taskkill /f /im EpicGamesLauncher.exe")

        elif 'close task manager' in query:
            speak("Closing Task Manager")
            os.system("taskkill /f /im Taskmgr.exe")

        # Switch Window
        elif 'switch window' in query or 'switch the windows' in query or 'switch windows' in query:
            pyautogui.keyDown("alt")
            pyautogui.press("tab")
            time.sleep(1)
            pyautogui.keyUp("alt")

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Calculator Function>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        elif 'do some calculations' in query or 'calculate' in query or 'open calculator' in query:
            try:
                r = sr.Recognizer()
                with sr.Microphone() as source:
                    speak("What you want to calculate? Example 6 plus 6")
                    print("listening...")
                    r.adjust_for_ambient_noise(source)
                    audio = r.listen(source)
                my_string = r.recognize_google(audio)
                print(my_string)

                def get_operator_fn(op):
                    return {
                        '+': operator.add,  # Plus
                        '-': operator.sub,  # Minus
                        'x': operator.mul,  # Multiplied by
                        'divided by': operator.__truediv__,  # Divided by
                    }[op]

                def eval_binary_expr(op1, oper, op2):  # 5 plus 8
                    op1, op2 = float(op1), float(op2)
                    return get_operator_fn(oper)(op1, op2)

                speak("Your Result is")
                speak(eval_binary_expr(*(my_string.split())))

            except Exception:
                speak("Sorry i didn't catch that. Please try again")
Exemplo n.º 18
0
 def rand():
     x = randfacts.getFact(True)
     lab.config(text=x)
Exemplo n.º 19
0
def facts(bot, update):
    fact = randfacts.getFact()
    update.message.reply_text(fact)
Exemplo n.º 20
0
 def compute(self):
     if st.button("__Extract Features__"):
         funfacts = randfacts.getFact()
         st.info(
             str.join('',
                      ('Extracting... Here is a random fact: ', funfacts)))
         try:
             [self.features,
              self.scaled_features] = load_feats(self.working_dir,
                                                 self.prefix)
         except:
             window = np.int(np.round(0.05 / (1 / self.framerate)) * 2 - 1)
             f = []
             my_bar = st.progress(0)
             for n in range(len(self.processed_input_data)):
                 data_n_len = len(self.processed_input_data[n])
                 dxy_list = []
                 disp_list = []
                 for r in range(data_n_len):
                     if r < data_n_len - 1:
                         disp = []
                         for c in range(
                                 0, self.processed_input_data[n].shape[1],
                                 2):
                             disp.append(
                                 np.linalg.norm(
                                     self.processed_input_data[n][r + 1,
                                                                  c:c + 2] -
                                     self.processed_input_data[n][r,
                                                                  c:c + 2]))
                         disp_list.append(disp)
                     dxy = []
                     for i, j in itertools.combinations(
                             range(0, self.processed_input_data[n].shape[1],
                                   2), 2):
                         dxy.append(
                             self.processed_input_data[n][r, i:i + 2] -
                             self.processed_input_data[n][r, j:j + 2])
                     dxy_list.append(dxy)
                 disp_r = np.array(disp_list)
                 dxy_r = np.array(dxy_list)
                 disp_boxcar = []
                 dxy_eu = np.zeros([data_n_len, dxy_r.shape[1]])
                 ang = np.zeros([data_n_len - 1, dxy_r.shape[1]])
                 dxy_boxcar = []
                 ang_boxcar = []
                 for l in range(disp_r.shape[1]):
                     disp_boxcar.append(boxcar_center(disp_r[:, l], window))
                 for k in range(dxy_r.shape[1]):
                     for kk in range(data_n_len):
                         dxy_eu[kk, k] = np.linalg.norm(dxy_r[kk, k, :])
                         if kk < data_n_len - 1:
                             b_3d = np.hstack([dxy_r[kk + 1, k, :], 0])
                             a_3d = np.hstack([dxy_r[kk, k, :], 0])
                             c = np.cross(b_3d, a_3d)
                             ang[kk, k] = np.dot(
                                 np.dot(np.sign(c[2]), 180) / np.pi,
                                 math.atan2(
                                     np.linalg.norm(c),
                                     np.dot(dxy_r[kk, k, :], dxy_r[kk + 1,
                                                                   k, :])))
                     dxy_boxcar.append(boxcar_center(dxy_eu[:, k], window))
                     ang_boxcar.append(boxcar_center(ang[:, k], window))
                 disp_feat = np.array(disp_boxcar)
                 dxy_feat = np.array(dxy_boxcar)
                 ang_feat = np.array(ang_boxcar)
                 f.append(np.vstack((dxy_feat[:, 1:], ang_feat, disp_feat)))
                 my_bar.progress(
                     round((n + 1) / len(self.processed_input_data) * 100))
             for m in range(0, len(f)):
                 f_integrated = np.zeros(len(self.processed_input_data[m]))
                 for k in range(round(self.framerate / 10), len(f[m][0]),
                                round(self.framerate / 10)):
                     if k > round(self.framerate / 10):
                         f_integrated = np.concatenate(
                             (f_integrated.reshape(f_integrated.shape[0],
                                                   f_integrated.shape[1]),
                              np.hstack(
                                  (np.mean((f[m][
                                      0:dxy_feat.shape[0],
                                      range(k - round(self.framerate /
                                                      10), k)]),
                                           axis=1),
                                   np.sum((f[m][
                                       dxy_feat.shape[0]:f[m].shape[0],
                                       range(k - round(self.framerate /
                                                       10), k)]),
                                          axis=1))).reshape(len(f[0]), 1)),
                             axis=1)
                     else:
                         f_integrated = np.hstack((
                             np.mean(
                                 (f[m][0:dxy_feat.shape[0],
                                       range(k - round(self.framerate /
                                                       10), k)]),
                                 axis=1),
                             np.sum(
                                 (f[m][dxy_feat.shape[0]:f[m].shape[0],
                                       range(k - round(self.framerate /
                                                       10), k)]),
                                 axis=1))).reshape(len(f[0]), 1)
                 if m > 0:
                     self.features = np.concatenate(
                         (self.features, f_integrated), axis=1)
                     scaler = StandardScaler()
                     scaler.fit(f_integrated.T)
                     scaled_f_integrated = scaler.transform(
                         f_integrated.T).T
                     self.scaled_features = np.concatenate(
                         (self.scaled_features, scaled_f_integrated),
                         axis=1)
                 else:
                     self.features = f_integrated
                     scaler = StandardScaler()
                     scaler.fit(f_integrated.T)
                     scaled_f_integrated = scaler.transform(
                         f_integrated.T).T
                     self.scaled_features = scaled_f_integrated
             self.features = np.array(self.features)
             self.scaled_features = np.array(self.scaled_features)
             with open(
                     os.path.join(self.working_dir,
                                  str.join('',
                                           (self.prefix, '_feats.sav'))),
                     'wb') as f:
                 joblib.dump([self.features, self.scaled_features], f)
         st.info(
             'Done extracting features from a total of **{}** training data files. '
             'Now reducing dimensions...'.format(
                 len(self.processed_input_data)))
         self.learn_embeddings()
Exemplo n.º 21
0
async def on_message(message):
    if message.author == client.user:
        return

    m8ball = [
        'It is certain.',
        'It os decidedly so.',
        'Without a doubt.',
        'Yes - definitely.',
        'You may rely on it.',
        'As I see it, yes.',
        'Most likely.',
        'Outlook good.',
        'Yes.',
        'Signs point to yes.',
        'Reply hazy, try again.',
        'Ask again later.',
        'Better not tell you now.',
        'Cannot predict now.',
        'Concentrate and ask again.',
        'Don\'t count on it.',
        'My reply is no.',
        'My sources say no.',
        'Outlook not so good.',
        'Very doubtful.',
    ]
    missu = ['I miss you too :cry:', 'Screw you b\*\*\*\*']
    loveu = ['I love you too :heart:', 'Screw you b\*\*\*\*']
    marry = [
        'Ok :heart:', 'You\'re ugly', 'I\'m too out of your league', 'potato',
        'How much do you make in a year?', 'I\'m already married to Carl-Bot',
        'no b\*\*\*\*'
    ]

    fortune = open("fortunes").readlines()

    if 'train' in message.content.lower():
        await message.channel.send('I like trains!')
    elif 'hi gary' in message.content.lower():
        await message.channel.send('Hello!')
    elif 'sup gary' in message.content.lower():
        await message.channel.send('Hello!')
    elif 'hello gary' in message.content.lower():
        await message.channel.send('Hello!')
    elif 'f**k you' in message.content.lower():
        await message.channel.send('F**k you')
    elif 'you suck' in message.content.lower():
        await message.channel.send('no u')
    elif 'ily' in message.content.lower():
        await message.channel.send(random.choice(loveu))
    elif 'i love you' in message.content.lower():
        await message.channel.send(random.choice(loveu))
    elif 'i love gary' in message.content.lower():
        await message.channel.send(random.choice(loveu))
    elif 'i miss you' in message.content.lower():
        await message.channel.send(random.choice(missu))
    elif 'i miss gary' in message.content.lower():
        await message.channel.send(random.choice(missu))
    elif message.content.lower().startswith('~gary'):
        await message.channel.send(random.choice(m8ball))
    elif message.content.startswith('~8ball'):
        await message.channel.send(random.choice(m8ball))
    elif message.content.startswith('~knowledge'):
        await message.channel.send(getFact(False))
    elif message.content.startswith('~fortune'):
        await message.channel.send(random.choice(fortune))
    elif 'marry me' in message.content.lower():
        await message.channel.send(random.choice(marry))
Exemplo n.º 22
0
 async def randomfact(self, ctx: Context) -> None:
     """Get A Random fact"""
     randomfact = randfacts.getFact()
     await ctx.send(embed=Embed(title="Did You Know?",
                                description=randomfact["text"],
                                color=Color.blurple()))
Exemplo n.º 23
0
async def _intervento(ctx):
    x = randfacts.getFact()
    await ctx.send(x)
Exemplo n.º 24
0
def home():
    randomf = randfacts.getFact()
    return render_template('home.html', title="Home", randomf=randomf)
Exemplo n.º 25
0
import randfacts
facts = randfacts.getFact(1)
print(facts)
Exemplo n.º 26
0
def getFact():
    rfact = [randfacts.getFact(),randfacts.getFact(),randfacts.getFact()]
    return rfact
Exemplo n.º 27
0
def sms():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    msg = resp.message()

    if 'good morning' in incoming_msg:
        #! Return a gesture good morning
        msg.body('Good Morning..\nHave a nice day..')

    elif 'good afternoon' in incoming_msg:
        #! Return a gesture good morning
        msg.body('Good Afternoon..')

    elif 'good evening' in incoming_msg:
        #! Return a gesture good evening
        msg.body('Good Evening..\nHow was your day today?')

    elif 'good night' in incoming_msg:
        #! Return a good night gesture
        msg.body('Good Night..\nSee you tomorrow..')

    elif 'fine' in incoming_msg:
        #! Return a sweet gesture and ask what to do
        msg.body('Nice to hear that..\nWhat can I do for you master?')

    elif 'who made you' in incoming_msg:
        #! Telling about your developer
        msg.body('Samwit Adhikary made me.❤️❤️')

    elif "who are you" in incoming_msg:
        #! Telling who am I
        msg.body('I am called Whatsapp Bot made by Samwit Adhikary.❤️❤️')

    elif 'who developed you' in incoming_msg:
        #! Returning whatsapp obeying
        msg.body('I obey whatsapp messenger.')

    elif 'how are you' in incoming_msg:
        #! Telling how am I
        msg.body('I am fine..\nWhat about you??')

    elif '#about' in incoming_msg:
        #! Telling your features
        msg.body(
            "Hi! I am Whatsapp Bot made By Samwit Adhikary. Did you know that you can find out the weather, a movie rating and much more on whatsapp with just a few words!\nTry one of the following and I'll look it up for you!\n\n#weather PLACE: Check out the weather at any place.\n\n#wiki NAME: Search Wikipedia for anything you want.\n\n#quote: We'll send you awesome quote whenever you want it.\n\n#movie NAME: Checkout the IMDB Rating about any movie.\n\n#book NAME: Get details of any book you're interested in.\n\n#meaning WORD: Don't know the meaning of a word someone just messaged you? Try out my built in dictionary\n\n#synonym WORD: Don't know the synonyms of any word. Try my built in synonym finder.\n\n#coronastats: To get current status of Coronavirus in India\n\n#fact: Awesome facts, served streaming hot, whenever you want it!\n\n#news: Get the top 5 breaking news.\n\n#joke: Get jokes."
        )

    elif '#joke' in incoming_msg:
        #! Return random joke.
        url = 'https://official-joke-api.appspot.com/jokes/general/random'
        r = requests.get(url)
        rj = r.json()
        try:
            for joke in rj:
                setup = joke['setup']
                punch = joke['punchline']
                msg.body(f'{setup}\n{punch}')
        except:
            msg.body('Sorry.. No Joke Found!!')

    elif '#news' in incoming_msg:
        #! Return top 5 headlines.
        url = 'http://newsapi.org/v2/top-headlines?country=in&apiKey=<Your Api Key>'
        r = requests.get(url)
        rj = r.json()
        try:
            articles = rj['articles']
            for news in articles[:5]:
                title = news['title']
                link = news['url']
                msg.body(f"\nTitle: {title}\n{link}\n")
        except:
            msg.body('Sorry.. No News Found!!')

    elif '#fact' in incoming_msg:
        #! Return interesting facts.
        try:
            facts = randfacts.getFact()
            msg.body(facts)
        except:
            msg.body('Sorry.. No Facts Found!!')

    elif '#coronastats' in incoming_msg:
        #! Return covid19 stats.
        url = 'https://coronavirus-19-api.herokuapp.com/countries/india'
        r = requests.get(url)
        rj = r.json()
        try:
            totalCases = rj['cases']
            totalRecovered = rj['recovered']
            totalDeaths = rj['deaths']
            active = rj['active']
            critical = rj['critical']
            todaysCases = rj['todayCases']
            todaysDeaths = rj['todayDeaths']
            msg.body(
                f"The current stats for COVID-19 in India are as follow:\n\nTotal Cases: {totalCases}\nTotal Recovered: {totalRecovered}\nTotal Deaths: {totalDeaths}\nActive Cases: {active}\nCritical Cases: {critical}\nNew Cases Today: {todaysCases}\nNew Deaths: {todaysDeaths}\n\nYou can get the latest stats by sending #coronastats"
            )
        except:
            msg.body(
                'Sorry I am unable to retrive corona stats at this time, try later.'
            )

    elif "#synonym" in incoming_msg:
        #! Return 10 synonyms of the word.
        word = incoming_msg.replace('#synonym ', '')
        url = f'https://api.dictionaryapi.dev/api/v2/entries/en/{word}'
        r = requests.get(url)
        synonym = []
        rj = r.json()
        try:
            for i in rj:
                s = i['meanings']
                for j in s:
                    y = j['definitions']
                    for k in y:
                        try:
                            n = k['synonyms']
                            for syn in n:
                                synonym.append(syn)
                        except:
                            pass
        except:
            synonym.append('Sorry.. No Word Found!!')

        msg.body('Synonyms: \n\n')
        for mean in synonym[:10]:
            msg.body(mean + ', ')

    elif '#meaning' in incoming_msg:
        #! Return meaning of word.
        word = incoming_msg.replace('#meaning ', '')
        url = f'https://api.dictionaryapi.dev/api/v2/entries/en/{word}'

        examples = []
        defs = []
        try:
            r = requests.get(url)
            rj = r.json()

            for data in rj:
                meaning = data['meanings']
                for data1 in meaning:
                    definitions = data1['definitions']
                    for data2 in definitions:
                        # print(data2)
                        definition = data2['definition']
                        defs.append(definition)
                        try:

                            example = data2['example']
                            examples.append(example)
                        except:
                            pass
            msg.body('*Meaning:*\n')
            for i in defs:
                msg.body(i + ',\n')
            msg.body('*Examples:*\n')
            for j in examples:
                msg.body(j + ', ')
        except:
            msg.body('Sorry.. No Words Found!!')

    elif '#book' in incoming_msg:
        #! Return book details
        name = incoming_msg.replace('#book ', '')
        url = f'https://www.googleapis.com/books/v1/volumes?q={name}'
        r = requests.get(url)
        try:
            rj = r.json()
            top = rj['items']
            vinfo = []
            for i in top:
                for j in i:
                    if (j == 'volumeInfo'):
                        vinfo.append(i[j])
            bTitle = []
            subtitle = []
            author = []
            bRating = []
            publisher = []
            buylink = []

            for i in vinfo:
                for j in i:
                    try:
                        if j == 'title':
                            bTitle.append(i[j])
                        elif j == 'subtitle':
                            subtitle.append(i[j])
                        elif j == 'authors':
                            author.append(i[j])
                        elif j == 'averageRating':
                            bRating.append(i[j])
                        elif j == 'publisher':
                            publisher.append(i[j])
                        elif j == 'canonicalVolumeLink':
                            buylink.append(i[j])
                    except:
                        if j == 'title':
                            bTitle.append(i[j])
                        elif j == 'authors':
                            author.append(i[j])
                        elif j == 'averageRating':
                            bRating.append(i[j])
                        elif j == 'publisher':
                            publisher.append(i[j])
                        elif j == 'canonicalVolumeLink':
                            buylink.append(i[j])

            try:
                msg.body(
                    f"Title: {bTitle[0]}\nSubtitle: {subtitle[0]}\nAuthor: {author[0][0]}\nRating: {bRating[0]}\nPublisher: {publisher[0]}\n\n{buylink[0]}"
                )
            except:
                msg.body(
                    f"Title: {bTitle[0]}\nAuthor: {author[0][0]}Rating: {bRating[0]}\nPublisher: {publisher[0]}\n\n{buylink[0]}"
                )
        except:
            msg.body(f"Sorry.. Can't find book {name}..\nTry some other book.")

    elif '#movie' in incoming_msg:
        name = incoming_msg.replace('#movie ', '')
        ids = []
        try:
            try:
                url = f'http://www.omdbapi.com/?s={name}&apikey=<Your Api Key>'
                r = requests.get(url)
                rj = r.json()
                search = rj['Search']
                for data in search:
                    ID = data['imdbID']
                    ids.append(ID)
            except:
                url = f'https://imdb-api.com/en/API/SearchAll/k_4livlpf2/{name}'
                r = requests.get(url)
                rj = r.json()
                results = rj['results']
                for data in results:
                    ID = data['id']
                    ids.append(ID)
            iD = ids[0]

            url2 = f'http://www.omdbapi.com/?i={iD}&apikey=<Your Api Key>'
            req = requests.get(url2)
            rjson = req.json()
            title = rjson['Title']
            year = rjson['Year']
            release = rjson['Released']
            rtime = rjson['Runtime']
            actor = rjson['Actors']
            lang = rjson['Language']
            rating = rjson['imdbRating']
            genre = rjson['Genre']
            poster = rjson['Poster']

            msg.body(
                f'Movie Info:\n\nTitle: {title}({year})\nReleased: {release}\nRating: {rating}\nRuntime: {rtime}\nLanguage: {lang}\nGenre: {genre}\nActors: {actor}\n\nPoster:\n{poster}'
            )
        except:
            msg.body(f"Sorry can't find movie {name}")

    elif '#weather' in incoming_msg:
        #! Returning Weather Report
        city_name = incoming_msg.replace('#weather ', '')
        r = requests.get(
            f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid=<Your Api Key>&units=metric'
        )
        try:
            data = r.json()
            name = data['name']
            feels_like = data['main']['feels_like']
            humidity = data['main']['humidity']
            latitude = data['coord']['lat']
            longitude = data['coord']['lon']
            country = data['sys']['country']
            temp = data['main']['temp']
            wind_speed = data['wind']['speed']
            msg.body(
                f"City Name: {name} - {country}\nLongitude: {longitude}°\nLatitude: {latitude}°\nFeels Like: {feels_like}°C\nTemperature: {temp}°C\nHumidity: {humidity}%\nWind Speed: {wind_speed}m/s"
            )
        except:
            titleName = city_name.title()
            msg.body(
                f"Sorry.. Can't find *{titleName}*..\nEnter any city name..\n*#weather kolkata*"
            )

    elif '#wiki' in incoming_msg:
        #! Returning summary from wikipedia
        query = incoming_msg.replace('#wiki ', '')
        wiki = wikipediaapi.Wikipedia('en')
        try:
            page = wiki.page(query)
            url = page.fullurl
            summary = page.summary[0:1500]
            msg.body(f'According to wikipedia..\n\n{summary}...\n{url}')
        except:
            msg.body("Sorry can't find anything.\nTry another search..")

    elif '#quote' in incoming_msg:
        #! Returning quotes
        r = requests.get('http://api.quotable.io/random')
        if r.status_code == 200:
            data = r.json()
            quote = f'{data["content"]} ({data["author"]})'
        else:
            quote = 'Sorry I am unable to retrive quote at this time, try later.'
        msg.body(quote)

    else:
        msg.body("Sorry.. I didn't get that..\nTry *#about* ")

    return str(resp)
Exemplo n.º 28
0
async def on_message(message):
    if message.author == client.user:
        return

    if message.content == ('r!help'):
        await message.add_reaction('👌')
        embedVar = discord.Embed(title="Commands", description="All of Registeel's Commands!", color=0x1abc9c)
        embedVar.add_field(name='Fun Commands', value='`r!help fun`', inline=True)
        embedVar.add_field(name='Games', value='`r!help games`', inline=False)
        embedVar.add_field(name='Other commands', value='`r!help other`', inline=False)
        await message.channel.send(embed=embedVar)

    if message.content == ('r!help fun'):
        embedVar = discord.Embed(title="FUN Commands", description="`r!randomnumber, r!yt, r!say <message>, r!poll, r!fact`", color=0x1abc9c)
        await message.channel.send(embed=embedVar)

    if message.content == ('r!help games'):
        embedVar= discord.Embed(title="Games", description="Game Commands", color=0x1abc9c)
        embedVar.add_field(name="Simple Games", value="`r!coinflip`", inline=False)
        embedVar.add_field(name="Economy", value="*Coming Soon*", inline=False)
        await message.channel.send(embed=embedVar)

    if message.content == ('r!help other'):
        embedVar= discord.Embed(title="Other Commands", description="`r!quote, r!sourcecode, r!website, r!invite, r!vote, r!help`", color=0x1abc9c)
        await message.channel.send(embed=embedVar)

    if message.content == ('r!quote'):
        y = get_quote()
        embed = discord.Embed(title="{}, here is a quote to inspire you.".format(message.author.name), description=y, color=0x1abc9c)
        await message.channel.send(embed=embed)

    if message.content == ('r!invite'):
        await message.channel.send(
            'https://discord.com/api/oauth2/authorize?client_id=809002048447184948&permissions=8&scope=bot'
        )

    if message.content == ('r!website'):
        await message.channel.send(
            'https://registeeldev1.wixsite.com/registeel')

    if message.content == ('r!yt'):
        await message.channel.send('Subscribe here! https://www.youtube.com/channel/UCxzkAP7o94jO-5U1DcESA8w')

    if message.content == ('r!randomnumber'):
      randomnumber = random.randint(0,1000)
      await message.channel.send(randomnumber)
      if randomnumber == 626:
        await message.channel.send('Your number is **626**. You win a cookie :)')

    if message.content == ('r!sourcecode'):
        await message.channel.send(
            'https://github.com/theultimatepokemontrainer/registeeldiscordbot'
        )

    if message.content == ('r!coinflip'):
        embedVar = discord.Embed(title="Coin Flipped!", description=random, color=0xf1c40f,)
        await message.channel.send(embed=embedVar)

    if message.content == ('r!vote'):
        await message.channel.send('You can vote every 12 hours! https://top.gg/bot/809002048447184948/vote')

    if message.content == ('r!poll'):
        await message.add_reaction('👍')
        await message.add_reaction('👎')
        await message.channel.send('👍 for yes 👎 for no')

    if message.content == ("r!say"):
        await message.channel.send(message.content[5:].format(message))

    if message.content == ('r!fact'):
        x = getFact()
        embed = discord.Embed(title='{}, here is your fact'.format(message.author.name), description=x, color=0x1abc9c)
        await message.channel.send(embed=embed)
Exemplo n.º 29
0
import randfacts
import os
import re

print("")
print("")
print(u"\u001b[33m===================================================================\u001b[0m")
print(u"\u001b[36mInitializing test! (1/3)")
try:
	print(u"\u001b[33m===================================================================\u001b[0m")
	print(randfacts.getFact())
	print(u"\u001b[33m===================================================================\u001b[0m")
	print("")
except AttributeError:
	print(u"\u001b[31m===================================================================\u001b[0m")
	print(u"\u001b[31mWhoops! Executing a getFact() call got an AttributeError!\u001b[0m")
	print(u"\u001b[31m===================================================================\u001b[0m")
	exit(2)
print(u"\u001b[33m===================================================================\u001b[0m")
print(u"\u001b[32mSuccessful Test! (1/3 COMPLETE)\u001b[0m")
print(u"\u001b[36mInitializing test! (2/3)\u001b[0m")
try:
	print(u"\u001b[33m===================================================================\u001b[0m")
	print(randfacts.getVersion())

	print(u"\u001b[33m===================================================================\u001b[0m")
	print("")
except AttributeError:
	print(u"\u001b[31m===================================================================\u001b[0m")
	print(u"\u001b[31mWhoops! Executing a getVersion() call got an AttributeError!\u001b[0m")
	print(u"\u001b[31m===================================================================\u001b[0m")
Exemplo n.º 30
0
 def compile_data(self):
     st.write('Identify pose to include in clustering.')
     if self.software == 'DeepLabCut' and self.ftype == 'csv':
         data_files = glob.glob(self.root_path + self.data_directories[0] +
                                '/*.csv')
         file0_df = pd.read_csv(data_files[0], low_memory=False)
         file0_array = np.array(file0_df)
         p = st.multiselect('Identified __pose__ to include:',
                            [*file0_array[0, 1:-1:3]],
                            [*file0_array[0, 1:-1:3]])
         for a in p:
             index = [i for i, s in enumerate(file0_array[0, 1:]) if a in s]
             if not index in self.pose_chosen:
                 self.pose_chosen += index
         self.pose_chosen.sort()
         if st.button("__Preprocess__"):
             funfacts = randfacts.getFact()
             st.info(
                 str.join('', ('Preprocessing... Here is a random fact: ',
                               funfacts)))
             for i, fd in enumerate(
                     self.data_directories):  # Loop through folders
                 f = get_filenames(self.root_path, fd)
                 my_bar = st.progress(0)
                 for j, filename in enumerate(f):
                     file_j_df = pd.read_csv(filename, low_memory=False)
                     file_j_processed, p_sub_threshold = adp_filt(
                         file_j_df, self.pose_chosen)
                     self.raw_input_data.append(file_j_df)
                     self.sub_threshold.append(p_sub_threshold)
                     self.processed_input_data.append(file_j_processed)
                     self.input_filenames.append(filename)
                     my_bar.progress(round((j + 1) / len(f) * 100))
             with open(
                     os.path.join(self.working_dir,
                                  str.join('', (self.prefix, '_data.sav'))),
                     'wb') as f:
                 joblib.dump([
                     self.root_path, self.data_directories, self.framerate,
                     self.pose_chosen, self.input_filenames,
                     self.raw_input_data,
                     np.array(self.processed_input_data), self.sub_threshold
                 ], f)
             st.info(
                 'Processed a total of **{}** .{} files, and compiled into a '
                 '**{}** data list.'.format(
                     len(self.processed_input_data), self.ftype,
                     np.array(self.processed_input_data).shape))
             st.balloons()
     elif self.software == 'DeepLabCut' and self.ftype == 'h5':
         data_files = glob.glob(self.root_path + self.data_directories[0] +
                                '/*.h5')
         file0_df = pd.read_hdf(data_files[0], low_memory=False)
         p = st.multiselect(
             'Identified __pose__ to include:',
             [*np.array(file0_df.columns.get_level_values(1)[1:-1:3])],
             [*np.array(file0_df.columns.get_level_values(1)[1:-1:3])])
         for a in p:
             index = [
                 i for i, s in enumerate(
                     np.array(file0_df.columns.get_level_values(1)))
                 if a in s
             ]
             if not index in self.pose_chosen:
                 self.pose_chosen += index
         self.pose_chosen.sort()
         if st.button("__Preprocess__"):
             funfacts = randfacts.getFact()
             st.info(
                 str.join('', ('Preprocessing... Here is a random fact: ',
                               funfacts)))
             for i, fd in enumerate(self.data_directories):
                 f = get_filenamesh5(self.root_path, fd)
                 my_bar = st.progress(0)
                 for j, filename in enumerate(f):
                     file_j_df = pd.read_hdf(filename, low_memory=False)
                     file_j_processed, p_sub_threshold = adp_filt_h5(
                         file_j_df, self.pose_chosen)
                     self.raw_input_data.append(file_j_df)
                     self.sub_threshold.append(p_sub_threshold)
                     self.processed_input_data.append(file_j_processed)
                     self.input_filenames.append(filename)
                     my_bar.progress(round((j + 1) / len(f) * 100))
             with open(
                     os.path.join(self.working_dir,
                                  str.join('', (self.prefix, '_data.sav'))),
                     'wb') as f:
                 joblib.dump([
                     self.root_path, self.data_directories, self.framerate,
                     self.pose_chosen, self.input_filenames,
                     self.raw_input_data,
                     np.array(self.processed_input_data), self.sub_threshold
                 ], f)
             st.info(
                 'Processed a total of **{}** .{} files, and compiled into a '
                 '**{}** data list.'.format(
                     len(self.processed_input_data), self.ftype,
                     np.array(self.processed_input_data).shape))
             st.balloons()
     elif self.software == 'SLEAP' and self.ftype == 'h5':
         data_files = glob.glob(self.root_path + self.data_directories[0] +
                                '/*.h5')
         file0_df = h5py.File(data_files[0], 'r')
         p = st.multiselect('Identified __pose__ to include:',
                            [*np.array(file0_df['node_names'][:])],
                            [*np.array(file0_df['node_names'][:])])
         for a in p:
             index = [
                 i
                 for i, s in enumerate(np.array(file0_df['node_names'][:]))
                 if a in s
             ]
             if not index in self.pose_chosen:
                 self.pose_chosen += index
         self.pose_chosen.sort()
         if st.button("__Preprocess__"):
             funfacts = randfacts.getFact()
             st.info(
                 str.join('', ('Preprocessing... Here is a random fact: ',
                               funfacts)))
             for i, fd in enumerate(self.data_directories):
                 f = get_filenamesh5(self.root_path, fd)
                 my_bar = st.progress(0)
                 for j, filename in enumerate(f):
                     file_j_df = h5py.File(filename, 'r')
                     file_j_processed, p_sub_threshold = adp_filt_sleap_h5(
                         file_j_df, self.pose_chosen)
                     self.raw_input_data.append(file_j_df['tracks'][:][0])
                     self.sub_threshold.append(p_sub_threshold)
                     self.processed_input_data.append(file_j_processed)
                     self.input_filenames.append(filename)
                     my_bar.progress(round((j + 1) / len(f) * 100))
             with open(
                     os.path.join(self.working_dir,
                                  str.join('', (self.prefix, '_data.sav'))),
                     'wb') as f:
                 joblib.dump([
                     self.root_path, self.data_directories, self.framerate,
                     self.pose_chosen, self.input_filenames,
                     self.raw_input_data,
                     np.array(self.processed_input_data), self.sub_threshold
                 ], f)
             st.info(
                 'Processed a total of **{}** .{} files, and compiled into a '
                 '**{}** data list.'.format(
                     len(self.processed_input_data), self.ftype,
                     np.array(self.processed_input_data).shape))
             st.balloons()
     elif self.software == 'OpenPose' and self.ftype == 'json':
         data_files = glob.glob(self.root_path + self.data_directories[0] +
                                '/*.json')
         file0_df = read_json_single(data_files[0])
         file0_array = np.array(file0_df)
         p = st.multiselect('Identified __pose__ to include:',
                            [*file0_array[0, 1:-1:3]],
                            [*file0_array[0, 1:-1:3]])
         for a in p:
             index = [i for i, s in enumerate(file0_array[0, 1:]) if a in s]
             if not index in self.pose_chosen:
                 self.pose_chosen += index
         self.pose_chosen.sort()
         if st.button("__Preprocess__"):
             funfacts = randfacts.getFact()
             st.info(
                 str.join('', ('Preprocessing... Here is a random fact: ',
                               funfacts)))
             for i, fd in enumerate(self.data_directories):
                 f = get_filenamesjson(self.root_path, fd)
                 json2csv_multi(f)
                 filename = f[0].rpartition('/')[-1].rpartition(
                     '_')[0].rpartition('_')[0]
                 file_j_df = pd.read_csv(str.join(
                     '', (f[0].rpartition('/')[0], '/', filename, '.csv')),
                                         low_memory=False)
                 file_j_processed, p_sub_threshold = adp_filt(
                     file_j_df, self.pose_chosen)
                 self.raw_input_data.append(file_j_df)
                 self.sub_threshold.append(p_sub_threshold)
                 self.processed_input_data.append(file_j_processed)
                 self.input_filenames.append(
                     str.join(
                         '',
                         (f[0].rpartition('/')[0], '/', filename, '.csv')))
             with open(
                     os.path.join(self.working_dir,
                                  str.join('', (self.prefix, '_data.sav'))),
                     'wb') as f:
                 joblib.dump([
                     self.root_path, self.data_directories, self.framerate,
                     self.pose_chosen, self.input_filenames,
                     self.raw_input_data,
                     np.array(self.processed_input_data), self.sub_threshold
                 ], f)
             st.info(
                 'Processed a total of **{}** .{} files, and compiled into a '
                 '**{}** data list.'.format(
                     len(self.processed_input_data), self.ftype,
                     np.array(self.processed_input_data).shape))
             st.balloons()