Beispiel #1
0
import discord
from discord.ext import commands
import random
import praw
import os
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import wolframalpha
from googletrans import Translator
import time

wolfClient = str(os.getenv('WOLF'))
client2 = wolframalpha.Client(wolfClient)
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sheet = client.open("Cool").sheet1
token = os.getenv('TOKEN')
client = commands.Bot(command_prefix = '_')
client.remove_command('help')
reddit = praw.Reddit("bot1", user_agent="Cyan's program 1.0 by /u/RosogollaBot")


@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('R.I.P Zyen'))
    print('bot is ready')


@client.command(aliases=['Ping'])
async def ping(ctx):
            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.")
            print("buzzer is turned off")
            speak("buzzer is turned off")
             
def search(text):
    try:
        results = wikipedia.summary(text, sentences=2)
        print(results)
        speak(results)

    except:
        pass
    return 0
    
def calculate(query):
    app_id = "TH57PT-W4XYVTEY5L"
    client = wolframalpha.Client(app_id) 
    indx = query.lower().split().index("calculate") 
    query = query.split()[indx + 1:] 
    res = client.query(' '.join(query))
    try:
        answer = next(res.results).text
        print(answer)
        speak(answer)
    except:
        pass
    return 0

def note(text):
    fd=os.open("py.txt",os.O_RDWR|os.O_CREAT)
    line = text
    b = str.encode(line)
Beispiel #4
0
 def wolframalphaCon(self, app_id, querry):
     #self_id=XWH3RH-KE5EVL4W5Q
     client = wolframalpha.Client(app_id)
     res = client.query(querry)
     return (next(res.results).text)
     web.open_new_tab("www.twitter.com")
 elif "open" in text and "reddit" in text:
     jarvis.say("opening reddit in browser")
     jarvis.runAndWait()
     web.open_new_tab("www.reddit.com")
 elif "who are you?" in text:
     jarvis.say(
         "I'd like to keep that secret to myself, unlike humans i care about my privacy"
     )
     jarvis.runAndWait()
 elif "search" in text:
     jarvis.say("Here you go, use google search")
     jarvis.runAndWait()
     web.open_new_tab("www.google.com")
 elif "how" in text or "weather" in text or "why" in text:
     client = w.Client('VH6GPR-GY7TT3X399')
     res = client.query(text)
     res = next(res.results).text
     jarvis.say(res)
     jarvis.runAndWait()
 elif "who" in text or "what" in text or "where" in text:
     jarvis.say("According to wiki ")
     jarvis.runAndWait()
     jarvis.say(wiki.summary(text, 2))
 elif "take" in text and "photo" in text:
     jarvis.say("Say cheese")
     jarvis.runAndWait()
     ec.capture(0, True, False)
     jarvis.say("Excellent photo it is")
     jarvis.runAndWait()
 elif "stop" in text or "goodbye" in text or "bye" in text or "exit" in text:
def test_invalid_app_id():
    client = wolframalpha.Client('abcdefg')
    with pytest.raises(Exception):
        client.query('30 deg C in deg F')
Beispiel #7
0
from __future__ import print_function
import os
import json
import redis
import wolframalpha

REDIS_URL = os.getenv('REDISTOGO_URL', 'redis://localhost:6379')
APP_ID = os.getenv('WOLFRAMALPHA_APP_ID', '')

print('APP_ID ' + APP_ID)

r_server = redis.StrictRedis.from_url(REDIS_URL)
client = wolframalpha.Client(APP_ID)

# get list of space probes
fname = 'scrapers/list_active_probes.txt'
probe_names = []
with open(fname) as f:
    content = f.readlines()
    for l in content[1:]:  # first line is a comment
        probe_names.append(l.strip())

# lookup in wolframalpha each probe
probe_data = {}
for probe in probe_names:

    probe_data[probe] = {}
    lookup_str = probe + ' spacecraft'
    print('looking up: ' + lookup_str)
    res = client.query(lookup_str)
Beispiel #8
0
    def start(self):
        self.change_value("Hi")

        while (1):
            # root.update()
            respond("Let's make a command Sir!")
            self.change_value("Let's make a command Sir!")
            text = talk().lower()
            if text == 0:
                continue
            if "who" in str(text):
                respond(random.choice(CHOICE))
            if "stop" in str(text) or "exit" in str(text) or "bye" in str(
                    text):
                respond("Ok bye and take care")
                break

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

            elif 'time' in text:
                strTime = datetime.datetime.now().strftime("%H:%M:%S")
                respond(f"the time is {strTime}")
            elif 'search' in text:
                text = text.replace("search", "")
                webbrowser.open_new_tab(text)
                time.sleep(5)

            elif "calculate" or "what is" in text:
                question = talk()
                print("testss " + text)
                app_id = "H547RP-7YTRPJ77UA"
                client = wolframalpha.Client(app_id)
                res = client.query(text)
                answer = next(res.results).text
                print("tets  " + answer)
                respond("The answer is " + answer)

            elif 'open google' in text:
                webbrowser.open_new_tab("https://www.google.com")
                respond("Google is open")
                time.sleep(5)

            elif 'youtube' in text:
                driver = webdriver.Chrome(r"Mention your webdriver location")
                driver.implicitly_wait(1)
                driver.maximize_window()
                respond("Opening in youtube")
                indx = text.split().index('youtube')
                query = text.split()[indx + 1:]
                driver.get("http://www.youtube.com/results?search_query =" +
                           '+'.join(query))

            elif "open word" in text:
                respond("Opening Microsoft Word")
                os.startfile('Mention location of Word in your system')

            else:
                respond("Application not available")
Beispiel #9
0
import wolframalpha

appid = "74PH97-WLV3Y3G8XR"
client = wolframalpha.Client(appid)

res = client.query('temperature in State College, PA now')

print(next(res.results).text[:5])
Beispiel #10
0
    def __init__(self, bot):
        super().__init__(bot)

        self.wac = wolframalpha.Client(self.bot.config.WOLFRAMALPHA_APP_ID)
        self.owm = pyowm.OWM(self.bot.config.OWM_APIKEY)
Beispiel #11
0
def process_text(input):
    try:
        if 'light' in input or 'lights' in input:
            # Creating client
            client = mqtt.Client(client_id='macbook')

            # Connecting callback functions
            client.on_connect = connect_msg
            client.on_publish = publish_msg

            # Connect to broker
            client.connect("192.168.1.73", 1883)

            if 'on' in input:
                # print("Lights are on")
                # Publish a message with topic
                ret = client.publish("house/closet-light", "on")
                speak = '''The lights are on'''
            if 'off' in input:
                # print("Lights are off")
                # Publish a message with topic
                ret = client.publish("house/closet-light", "off")
                speak = '''The lights are off'''

            # Run a loop
            client.loop()
            assistant_speaks(speak)

        elif 'search' in input or 'play' in input:
            # a basic web crawler using selenium
            search_web(input)
            return

        elif "who are you" in input or "define yourself" in input:
            speak = '''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'''
            assistant_speaks(speak)
            return

        elif "who made you" in input or "created you" in input:
            speak = "I have been created by Sheetansh Kumar."
            assistant_speaks(speak)
            return

        elif "geeksforgeeks" in input:  # just
            speak = """Geeks for Geeks is the Best Online Coding Platform for learning."""
            assistant_speaks(speak)
            return

        elif "calculate" in input.lower():

            # write your wolframalpha app_id here
            app_id = "WOLFRAMALPHA_APP_ID"
            client = wolframalpha.Client(app_id)

            indx = input.lower().split().index('calculate')
            query = input.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            assistant_speaks("The answer is " + answer)
            return

        elif 'open' in input:

            # another function to open
            # different application availaible
            open_application(input.lower())
            return

        else:

            assistant_speaks(
                "I can search the web for you, Do you want to continue?")
            ans = get_audio()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                search_web(input)
            else:
                return
    except:

        assistant_speaks(
            "I don't understand, I can search the web for you, Do you want to continue?"
        )
        ans = get_audio()
        if 'yes' in str(ans) or 'yeah' in str(ans):
            search_web(input)
Beispiel #12
0
import smtplib
import speech_recognition as sr
import wikipedia
import wolframalpha
import datetime
import os
import sys
import subprocess
from playsound import playsound
import boto3
import threading
import time
import google

engine = pyttsx3.init('sapi5')
client = wolframalpha.Client('PTRKX7-5VG5RGLTJQ')
voices = engine.getProperty('voices')
playsound('C:\\Users\\charan\\Desktop\\python projets\\AI\\audio.mpeg')
rain = "C:\\Users\\charan\\Desktop\\python projets\\AI\\Rainmeter\\Rainmeter.exe"

subprocess.Popen(rain)  #rainmetter


def mp3_start_note():
    playsound(mp3_start_note)


print(voices[0].id)
engine.setProperty('voice', voices[0].id)

Beispiel #13
0
import wolframalpha

client = wolframalpha.Client('PAWLAH-UHVA9RJQL8')

while True:
    query = str(input('Query: '))
    res = client.query(query)
    output = next(res.results).text
    print(output)
 def calc_alpha(self, query):
     app_id = "KVL9TA-YHEAR986WP"
     client = wolframalpha.Client(app_id)
     res = client.query(query)
     answer = next(res.results).text
     self.talk(answer)
Beispiel #15
0
# import all the libraries we will be using
from flask import Flask, request
from twilio.twiml.messaging_response import Message, MessagingResponse
import wikipedia
import yweather
import wolframalpha

# set up Flask to connect this code to the local host, which will
# later be connected to the internet through Ngrok
app = Flask(__name__)

wolfram_app_id = "4U2HPE-VT3UY6383H"
wolf = wolframalpha.Client(wolfram_app_id)
client = yweather.Client()


# Main method. When a POST request is sent to our local host through Ngrok
# (which creates a tunnel to the web), this code will run. The Twilio service # sends the POST request - we will set this up on the Twilio website. So when # a message is sent over SMS to our Twilio number, this code will run
@app.route('/', methods=['POST'])
def sms():
    # Get the text in the message sent
    message_body = request.form['Body']

    # Create a Twilio response object to be able to send a reply back (as per         # Twilio docs)
    resp = MessagingResponse()

    # Send the message body to the getReply message, where
    # we will query the String and formulate a response
    replyText = getReply(message_body)

    # Text back our response!
Beispiel #16
0
def play():
    global count
    btn2['state'] = 'disabled'
    btn0['state'] = 'disabled'
    btn1.configure(bg='orange')
    if count == 0:
        wishme()
    count = 1
    while True:
        btn1.configure(bg='orange')
        query = takeCommand().lower()
        if 'thank you' in query:
            var.set(f"It was Pleasure Helping You {username}")
            btn1.configure(bg='#5C85FB')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            window.update()
            speak(f"It was Pleasure Helping You {username}")
            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=1)
                    speak("According to wikipedia")
                    var.set(results)
                    window.update()
                    speak(results)
                except Exception as e:
                    var.set(f"sorry {username}, could not find any result")
                    window.update()
                    speak(f"sorry {username}, could not find any result")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif 'open youtube' in query:
            var.set('opening Youtube')
            window.update()
            speak('opening Youtube')
            webbrowser.open("youtube.com")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif 'open course era' in query:
            var.set('opening course era')
            window.update()
            speak('opening course era')
            webbrowser.open("coursera.com")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif 'open google' in query:
            var.set('opening google')
            window.update()
            speak('opening google')
            webbrowser.open("google.com")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

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

        elif 'open stack overflow' in query:
            var.set('opening stack overflow')
            window.update()
            speak('opening stack overflow')
            webbrowser.open('stackoverflow.com')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif ('play music' in query) or ('change music' in query):
            var.set('Here are your favorites')
            window.update()
            speak('Here are your favorites')
            os.startfile("C:\\Users\Rajnish Chanchal\Desktop\Amazon Music.lnk")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif 'the 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' 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 '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 mature enough to help you sir")
            window.update()
            speak("I am mature enough to help you sir")

        elif 'open media player' in query:
            var.set("opening VLC media Player")
            window.update()
            speak("opening V L C media player")
            path = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\VideoLAN\VLC media player.lnk"  #Enter the correct Path according to your system
            os.startfile(path)
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

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

        elif 'who creates you' in query:
            var.set('My Creator is Shivanshu and Rajnish')
            window.update()
            speak('My Creator is Shivanshu and Rajnish')

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

        elif 'open chrome' in query:
            var.set("Opening Google Chrome")
            window.update()
            speak("Opening Google Chrome")
            path = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Google Chrome.lnk"  #Enter the correct Path according to your system
            os.startfile(path)
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif 'send email' in query:
            try:
                var.set("What should I say")
                window.update()
                speak('what should I say')
                content = takeCommand()
                var.set('please give me reciever email id')
                window.update()
                speak('please give me reciever email id')

                to = takeEmail()

                var.set(f"sending email to {to}")
                window.update()
                var.set(f'confirm send email to {to}')
                window.update()
                speak(f'confirm send email to {to}')
                confirm = takeCommand()
                if 'yes' in confirm:
                    sendemail(to, content)
                    var.set('Email has been sent!')
                    window.update()
                    speak('Email has been sent!')
                elif 'no' in confirm:
                    var.set('email sending cancelled')
                    window.update()
                    speak('email sending cancelled')

            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')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif "open python" in query:
            var.set("Opening Python Idle")
            window.update()
            speak('opening python Idle')
            os.startfile(
                'C:\\Users\Rajnish Chanchal\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Python 3.8\IDLE (Python 3.8 64-bit)'
            )  #Enter the correct Path according to your system
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif "write a note" in query:
            var.set('What should i write,sir')
            window.update()
            speak("What should i write, sir")
            note = takeCommand()
            file = open('jarvis.txt', 'w')
            var.set('Sir, should i include date and time')
            window.update()
            speak("Sir, Should i include date and time")
            snfm = takeCommand()
            if 'yes' in snfm or 'sure' in snfm:
                strTime = datetime.now().strftime("% H:% M:% S")
                file.write(strTime)
                file.write(" :- ")
                file.write(note)
                var.set('done sir')
                window.update()
                speak('done sir')
            else:
                file.write(note)
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif "show notes" in query:
            var.set('Showing Notes')
            window.update()
            speak("Showing Notes")
            file = open("jarvis.txt", "r")
            file.read()
            var.set(f'{file.read(6)}')
            window.update()
            speak(file.read(6))
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif "calculate" in query:

            try:
                app_id = "V7KLV6-Y5GQ54UQR7"
                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
                var.set(f"The answer is {answer}")
                window.update()
                speak(f"The answer is {answer}")
                btn2['state'] = 'normal'
                btn0['state'] = 'normal'
            except:
                var.set("No result")
                window.update()
                speak("No result")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break

        elif "what is" in query or "who is" in query:
            app_id = "V7KLV6-Y5GQ54UQR7"
            client = wolframalpha.Client(app_id)
            res = client.query(query)

            try:
                var.set(f"{next(res.results).text}")
                window.update()
                speak(f"{next(res.results).text}")
            except StopIteration:
                var.set("No results")
                window.update()
                speak("No result")
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            break
Beispiel #17
0
import pyttsx3
import webbrowser
import smtplib
import random
import speech_recognition as sr
import wikipedia
import datetime
import wolframalpha
import os
import sys

engine = pyttsx3.init('sapi5')

client = wolframalpha.Client('Q2G9HA-63GXT344E9')

voices = engine.getProperty('voices')
engine.setProperty('voice', voices[len(voices) - 1].id)


def speak(audio):
    print('Computer: ' + audio)
    engine.say(audio)
    engine.runAndWait()


def greetMe():
    currentH = int(datetime.datetime.now().hour)
    if currentH >= 0 and currentH < 12:
        speak('Good Morning!')

    if currentH >= 12 and currentH < 18:
Beispiel #18
0
 def _load(self):
     self.app = wolframalpha.Client(self.config["app_id"])
Beispiel #19
0
            else:
                file.write(note)

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

        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 = "YTR6KJ-WXWPP54V3L"
            client = wolframalpha.Client('YTR6KJ-WXWPP54V3L')
            res = client.query(question)
            answer = next(res.results).text
            speak(answer)
            print(answer)

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

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

        elif "log off" in statement or "sign out" in statement:
            speak(
                "Ok , your pc will log off in 10 sec make sure you exit from all applications"
Beispiel #20
0
def Solve(question):
    client = wolframalpha.Client(app_id)
    res = client.query(question)
    if res['@success'] == 'true': answer = next(res.results).text
    else: answer = 'Упс, что-то пошло не так. Проверьте вопрос'
    return answer
Beispiel #21
0
from tkinter import *
from PIL import ImageTk, Image
import speech_recognition as sr
import pyttsx3, datetime, sys, wikipedia, wolframalpha, os, smtplib, random, webbrowser, pygame, subprocess

client = wolframalpha.Client('Your_App_ID')

folder = 'C:\\Users\\skt\\Music\\YouTube\\'

engine = pyttsx3.init()
voices = engine.getProperty('voices')

b_music = ['Edison', 'Micro', 'Lucid_Dreamer']
pygame.mixer.init()
pygame.mixer.music.load(folder + random.choice(b_music) + '.mp3')
pygame.mixer.music.set_volume(0.05)
pygame.mixer.music.play(-1)


def speak(audio):
    print('Karen:', audio)
    engine.setProperty('voice', voices[len(voices) - 1].id)
    engine.say(audio)
    engine.runAndWait()


def myCommand():

    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
Beispiel #22
0
# -*- coding: utf-8 -*-
import fbchat
import wolframalpha

from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
from tts import TTS
from stt import STT

wolfram_client = wolframalpha.Client('LXA9LJ-3835YR8529')


class Assistant(object):
    def __init__(self, use_speech):
        self.tts = TTS()

        self.use_speech = use_speech

        if self.use_speech:
            self.stt = STT()

        self.chatbot = ChatBot(
            'JARVIS',
            storage_adapter='chatterbot.storage.JsonFileStorageAdapter',
            filters=['chatterbot.filters.RepetitiveResponseFilter'],
            logic_adapters=[{
                'import_path': 'chatterbot.logic.BestMatch'
            }])

        self.chatbot.set_trainer(ChatterBotCorpusTrainer)
        self.chatbot.train("chatterbot.corpus.english.greetings")
Beispiel #23
0
                speak('Here are some headlines from the twenty four hours. Happy reading')
                time.sleep(6)

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

            elif 'search'  in statement:
                statement = statement.replace("search", "")
                webbrowser.open_new_tab(statement)
                time.sleep(5)

            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="R2K75H-7ELALHR35X"
                client = wolframalpha.Client('R2K75H-7ELALHR35X')
                res = client.query(question)
                answer = next(res.results).text
                speak(answer)
                print(answer)


            elif "log off" in statement or "sign out" in statement:
                speak('Are you sure you want to log off of your computer?')
                warn=1
            if 'yes' in statement and warn==1:
                warn=2
            if 'no' in statement and warn==1:
                warn=0
            if warn==2:
                warn=0
def wolfram_intent(intent, session):
    """ Sets the color in the session and prepares the speech to reply to the
    user.
    """

    card_title = intent['name']
    session_attributes = {}
    speech_output = ""
    reprompt_text = ""
    should_end_session = True

    if 'PullType' in intent['slots']:

        if 'value' in intent['slots']['PullType']:

            input_choice = intent['slots']['PullType']['value']
            #resultToChoose={"Picture": 1, "Function":2}

            if (input_choice == "picture"):
                if 'PullTarget' in intent['slots']:
                    if 'value' in intent['slots']['PullTarget']:

                        input_target = intent['slots']['PullTarget']['value']
                        client = wolframalpha.Client("26TT73-89H59Y46TE")

                        speech_output = "Found an image for {}, pushing now. ".format(
                            input_target)
                        reprompt_text = "Found an image for {}, pushing now. ".format(
                            input_target)

                        res = client.query(input_target + ' ' + input_choice)

                        i = 0
                        for pod in res.pods:
                            print(pod.text)
                            i += 1
                            if (i == 2 and pod.text != "NULL"):
                                #push_img = re.sub("gif", "jpg", pod.img)
                                #convert_image(pod.img)
                                print("about to convert and push")
                                firebase_push(convert_image(pod.img), "image")

                    else:
                        speech_output = "We could not find that pull target"
                        reprompt_text = "We could not find that pull target"

                else:
                    speech_output = "We could not find that pull target"
                    reprompt_text = "We could not find that pull target"

            elif (input_choice == "function"):
                if 'PullTarget' in intent['slots']:
                    if 'value' in intent['slots']['PullTarget']:

                        input_target = intent['slots']['PullTarget']['value']
                        client = wolframalpha.Client("26TT73-89H59Y46TE")

                        speech_output = "Found a graph for {}, pushing now. ".format(
                            input_target)
                        reprompt_text = "Found a graph for {}, pushing now. ".format(
                            input_target)

                        res = client.query(input_target + ' ' + input_choice)

                        print(res)

                        i = 0
                        for pod in res.pods:
                            print(pod.text)
                            if (i >= 1 and pod.text != "NULL"):
                                #push_img = re.sub("gif", "jpg", pod.img)
                                #convert_image(pod.img)
                                print("about to convert and push")
                                firebase_push(convert_image(pod.img), "image")

                            else:
                                i = i + 1

                    else:
                        speech_output = "We could not find that pull target"
                        reprompt_text = "We could not find that pull target"

                else:
                    speech_output = "We could not find that pull target"
                    reprompt_text = "We could not find that pull target"

            # elif (input_choice == "function"):
            #     if 'PullTarget' in intent['slots']:
            #         if 'value' in intent['slots']['PullTarget']:

            #             input_target = intent['slots']['PullTarget']['value']
            #             client = wolframalpha.Client("26TT73-89H59Y46TE")

            #             speech_output = "Found an graph for {}, pushing now. ".format(input_target)
            #             reprompt_text = "Found an graph for {}, pushing now. ".format(input_target)

            #             res = client.query(input_target+' '+input_choice)

            #             i=0
            #             for pod in res.pods:
            #                 print (pod.text)
            #                 if(i>=1 and pod.text!= "NULL"):
            #                     #push_img = re.sub("gif", "jpg", pod.img)
            #                     #convert_image(pod.img)
            #                     print("about to convert and push")
            #                     firebase_push(convert_image(pod.img), "image")
            #                     break;
            #                 else:
            #                     i=i+1

            #         else:
            #             speech_output = "We could not find that pull target"
            #             reprompt_text = "We could not find that pull target"

            # else:
            #     speech_output = "We could not find that pull target"
            #     reprompt_text = "We could not find that pull target"

            else:
                speech_output = "That is currently not a supported pull type"
                reprompt_text = "That is currently not a supported pull type"

        else:
            speech_output = "I didn't quite hear that. "
            reprompt_text = "Sorry, what was that? "

    else:
        speech_output = "I didn't quite hear that. "
        reprompt_text = "Sorry, what was that? "

    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
Beispiel #25
0
import pyttsx3
import webbrowser
import smtplib
import random
import speech_recognition as sr
import wikipedia
import datetime
import wolframalpha
import os
import sys
engine = pyttsx3.init('sapi5')

client = wolframalpha.Client('Your wolframalpha ID')

voices = engine.getProperty('voices')
engine.setProperty('voice', voices[len(voices) - 1].id)


def speak(audio):
    print('Computer: ' + audio)
    engine.say(audio)
    engine.runAndWait()


def greetMe():
    currentH = int(datetime.datetime.now().hour)
    if currentH >= 0 and currentH < 12:
        speak('Good Morning!')

    if currentH >= 12 and currentH < 18:
        speak('Good Afternoon!')
Beispiel #26
0
 def assistant(speech):
     cmd=str(speech)
     delete,p=0,0
     if "note" in cmd:
         print("your voice will be converted to text & will be saved in dictate.txt file")
         time.sleep(5)
         print("start")
         say("start")
         note()
         p=1
     if "what is the time" in cmd or "show me the time" in cmd or "time" in cmd:
         t = time.localtime()
         currenttime = time.strftime("%H:%M", t)
         a=str(currenttime)
         if int(a[:2])>0 and int(a[:2])<12:
             a=a+" AM "
         if int(a[:2])>=12 and int(a[:2])<24:
             h=str(int(a[:2])-12)
             a=h+a[2:]+" PM "
             atext='The time is '+str(a)
             say(atext)
             print(a)
         p=1
     if "set" in cmd and "alarm" in cmd:
         stop = False
         tm=str(input("enter time:"))
         label=str(input("enter label of alarm:"))
         atext='The alarm is set'
         myobj = gTTS(text=atext, lang='en')
         myobj.save("time.mp3")
         a1="time"
         playaudio('time.mp3')
         time.sleep(2)
         c=0
         while stop == False and c!=1:
             rn = str(datetime.datetime.now().time())
             if tm==rn[:8]:
                 print(label,rn[:8])
                 say("wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up wake up ")
                 c,p=1,1
     if "date" in cmd:
         today = datetime.date.today()
         atext='The date is '+str(today)
         say(atext)
         print("Today's date:", today)
         p=1
     if "calendar" in cmd:
         today = datetime.date.today()
         say("calendar of the year is given below")
         y=str(today)
         year=y[0:4]
         print (calendar.calendar(int(year), 2, 1, 6))
         p=1       
     if "who are you" in cmd or "what is your name" in cmd or "your name please" in cmd:
         print("Hello, my name is Catalina.")
         say("Hello, my name is Catalina.")
         p=1
     if "translate" in cmd:
         d={"English":"en","Hindi":"hi","Kannada":"kn","Telugu":"te","Marathi":"mr","French":"fr",
             "Punjabi":"pa","Korean":"ko","Latin":"la","German":"de",'Malayalam':"ml",'Russian':"ru",'Gujarati':"gu"}
         lan="English"
         for i in d:
             if i in cmd:
                 lan=str(i)
             else:
                 a=10
         l=str(d[lan])
         text4=str(input("enter the text to know details:"))
         s = Translator().translate(text=text4, dest=l).text
         atext1=str(s)
         myobj = gTTS(text=atext1, lang=l,slow=False)
         myobj.save("lantranslate.mp3")
         playaudio('lantranslate.mp3')
         print("translated :  ",s)
         p=1
     if "one more" in cmd or "again" in cmd:
         p=1
         con1=cs.connect(host="localhost",user="******",passwd="",database="catalina")
         cursor1=con1.cursor()
         query1="select * from history"
         cursor1.execute(query1)
         dat1=cursor1.fetchall()
         c,count=-1,0
         while count!=6:
             recent=str((dat1[c]))
             if "again" not in recent[44:] or recent[44:] is not "" or "one more" not in recent[44:]:
                 sp=recent[44:]
                 assistant(sp)
                 break
             else:
                 c=c-1
                 count=count+1
         con1.close()
     if "open" in cmd:
         p=1#'''or "Open"''':  
         if "open file" in cmd :
             cmd=cmd[9:]
             cmd=cmd[1:]
             print(cmd)
             print("The file will only be searched in C disk")
             say("searching file in C disk. Wait .")
             findfile(cmd)
         if "" in cmd:
             cmd=cmd.lower()
             print(cmd)
             apps={"chrome":'C:/Program Files/Google/Chrome/Application/chrome.exe',
                   'powerpoint':'C:/Program Files/Microsoft Office/root/Office16/POWERPNT.exe',
                   'settings':'C:/Windows/System32/control.exe',
                   'word':'C:/Program Files/Microsoft Office/root/Office16/WINWORD.exe',
                   'access':'C:/Program Files/Microsoft Office/root/Office16/MSASCCESS.exe',
                   'excel':'C:/Program Files/Microsoft Office/root/Office16/EXCEL.exe',
                   'task manager':'C:/Windows/system32/Taskmgr.exe',
                   'onenote':'C:/Program Files/Microsoft Office/root/Office16/ONENOTE.exe',
                   'command prompt':'C:/Windows/system32/cmd.exe',
                   'onscreen keyboard':'C:/Windows/system32/osk.exe',
                   'notepad':'C:/Windows/system32/notepad.exe',
                   'paint':'C:\Windows\system32\mspaint.exe',
                   'this pc':'C:/'}
             for i in apps:
                 if str(i) in cmd:
                     p=1
                     text3="opening"+str(i)
                     say(text3)
                     os.startfile(apps[i])
         else:
             say("i think software is not installed please install the software and then try again")
             p=1
     if "open YouTube" in cmd or "video of" in cmd:
         if "video of" in cmd or "videos related to" in cmd or "videos" in cmd:
             url="https://www.youtube.com/results?search_query="+cmd
             webbrowser.open(url)
             p=1
     if "history" in cmd:
         if "delete" in cmd :
             delhistory()
             p=1
         else:
             say("fetching your data")
             con1=cs.connect(host="localhost",user="******",passwd="",database="catalina")
             cursor1=con1.cursor()
             query1="select * from history"
             cursor1.execute(query1)
             p=1
             dat1=cursor1.fetchall()
             for i in dat1:
                 print(i)
             con1.close()
     if "os" in cmd or "operating system" in cmd and "my" in cmd:
         import platform
         a=str(platform.platform())
         say(a)
         print(a)
         p=1
     if "show me" in cmd or "" in cmd:
         text3="I found this for you."
         if "images" in cmd or "photos" in cmd:
             r1=cmd
             r1=r1.lstrip("show me images of")
             url="https://www.google.com/search?q="+str(r1)+"&source=lnms&tbm=isch&sa"
             say("i found this ")
             webbrowser.open(url)
             p=1
         if "news" in cmd:
             r1=cmd
             r1=r1.lstrip("show me news of")
             url="https://www.google.com/search?q="+str(r1)+"&tbm=nws&source=lnms&tbm=nws&sa"
             say("i found this ")
             webbrowser.open(url)
             p=1
     if "what can you do" in cmd:   
         say("i can do a lot like managing your activities, play a game, set a remainder,entertain,play a video, and a lot more")
         p=1
     if "copy" in cmd:
         t=cmd[5:]
         pyperclip.copy(t)
         say('text copied')
         p=1
     if "game" in cmd or "play" in cmd:
         if "game" in cmd or "a game" in cmd:
             url1="https://www.google.com/search?q=tic+tac+toe"
             url2="https://www.google.com/search?q=minesweeper"
             url3="https://www.google.com/search?q=play%20snake"
             url4="https://doodlecricket.github.io"
             url5="https://www.bing.com/fun/sudoku"
             url6="https://www.bing.com/fun/chess"
             r5=random.randint(0,5)
             url=[url1,url2,url3,url4,url5,url6]
             url=url[r5]
             say("OK let's play a game")
             print(p)
             p=1
             webbrowser.open(url)
         if "video" in cmd or "music" in cmd or "song" in cmd:
             g=".mp4"
             q=5
             lst=[]
             if 'music' in cmd or "song" in cmd:
                 g=".mp3"
             if q==5:
                 if " " in cmd :
                     say("searching file in c disk")
                     r1=5
                     for x,d,f in os.walk("c:\\"):
                         for files in f:
                             if g in files:
                                 location=str(os.path.join(x,files))
                                 lst.append(location)
                     p=1
                     w=random.randint(0,len(lst)-1)
                     ob=lst[w]
                     print("location:",ob)
                     os.startfile(ob)
     if "image to text" in cmd:
         pr=0
         try:
             from PIL import Image
         except ImportError:
             import Image
         import pytesseract
         import cv2
         file=str(input("enter image name:"))
         if " " in cmd :
             say("searching file in c disk")
             for x,d,f in os.walk("c:\\"):
                 if pr==0:
                     for files in f:
                         if files ==file and pr==0:
                             location=str(os.path.join(x,files))
                             print("location of file------   ",location)
                             img = cv2.imread(location)
                             p,pr=1,1
                             print("____________________________IMAGE PROCESSED TO TEXT________________________________")
                             print(pytesseract.image_to_string(Image.open(location)))
                             project()
                             break
     if "screenshot" in cmd or "take a photo of my screen" in cmd:
         time.sleep(5)
         if __name__ == '__main__':
             im = ImageGrab.grab()
             say("screenshot taken")
             n=str(input("enter name of the file:"))
             im.save(n+'.png')
             p=1
             time.sleep(3)
             im.show()
     if "tell me a joke" in cmd or "make me laugh" in cmd or "make me smile" in cmd or " joke " in cmd:
         j1='''A snail walks into a bar and the barman tells him there's a strict policy about having snails in the bar and so kicks
         him out.A year later the same snail re-enters the bar and asks the barman "What did you do that for?'''
         j2='''Three mice are being chased by a cat. The mice were cornered when one of the mice turned around and barked, "Ruff! Ruff! Ruff!" The surprised cat ran away scared.
         Later when the mice told their mother what happened, she smiled and said, "You see, it pays to be bilingual!"'''
         j3='''A nervous old lady on a bus was made even more nervous by the fact that the driver periodically took his arm out of the window. When she couldn't stand it any longer, she tapped him on the shoulder and whispered on his ear:
         "Young man...you keep both hands on the wheel...I'll tell you when it's raining!"'''
         j4='''Customer: Waiter, waiter! There is a frog in my soup!!! 
         Waiter: Sorry, sir. The fly is on vacation. '''
         j=[j1,j2,j3,j4]
         w1=random.randint(0,3)
         select=j[w1]
         say(select)
         for i in select:
             print(i,end="")
             time.sleep(0.047)
         print()
         p=1
     if "search for" in cmd:
         cmd=cmd.lstrip("search for")
         url="https://www.google.com/search?q="+cmd+"&source"
         say("i found this according to your search")
         p=1
         webbrowser.open(url)
     if "credits" in cmd or "made" in cmd and "you" in cmd:
         say("this is an open source project made by varun, mayank, souranh hope you liked it")
         p=1
     if "features" in cmd or "help" in cmd:
         features=["opening a file/app","entertain","search","weather","calculate","history","game","quiz","puzzle","video",
                 "take screenshot","download video","show time","note","OCR from image","alarm","math problems",'Q and A',"and many more"]
         for i in features:
             say(i)
             print(i)
         p=1
     if "feedback" in cmd:
         say("feel free to leave your feedback")
         os.startfile(cloc+"\\"+"main.html")
         p=1
     if "hello" in cmd:
         say('hello, how can I help you')
         p=1
     if "close" in cmd or "turn off"in cmd or "shutdown" in cmd and "computer" in cmd :
         os.system("shutdown -s")
         say("shutting down in  minute")
         p=1
     if "restart" in cmd and"computer" in cmd:
         os.system("shutdown /r /t 1")
         p=1
     if "exit" in cmd or "quit" in cmd or"close" in cmd:
         exit()
         p=1
     if "" in cmd and p==0:
         import wolframalpha
         client = wolframalpha.Client('42XG9Q-L76KJ35T39')
         try:
             res =client.query(cmd)
             output =next(res.results).text
             a=str(output)
             print(output)
             say(a)
             p=1
         except:
             try:
                 if p==0:
                     a=wikipedia.summary(cmd)
                     print(a)
                     say('According to Wikipedia'+a)
             except:
                 link='https://www.google.com/search?q='+str(cmd)
                 webbrowser.open(link)
                 p=1
     if delete!=1:
         con=cs.connect(host="localhost",user="******",passwd="",database="catalina")
         cursor=con.cursor()
         a=datetime.date.today()
         timesave=datetime.datetime.now().time()
         rn = str(timesave)
         tm=rn[:10]
         data=[(str(a),str(tm),cmd)]
         query='insert into history(date,time,word) values(%s,%s,%s)'
         cursor.executemany(query,data)
         con.commit()
         con.close()
         p=1
Beispiel #27
0
 def __init__(self, key):
     self.key = key
     self.client = wolframalpha.Client(key)
Beispiel #28
0
import threading

# Create global variables to enable movement and blinking to be turned on and off.
global moving, blinking

# Set these global variables to False for the time being.
moving = False
blinking = False

# Set wiki to False to use wolframalpha instead of wikipedia.
wiki = True

# Please replace ???? with your own wolframalpha client id.
# Sign up free here to get a client id: https://products.wolframalpha.com/simple-api/documentation/

wolfclient = wolframalpha.Client('??????-??????????')

picoh.reset()


def handleInput():
    global moving
    while True:

        picoh.say("Hello picoh here, what shall I look up on wolfram alpha?")

        text = input("Question:\n")
        picoh.say(text)
        picoh.baseColour(10, 5, 0)

        # Stop the random movement.
Beispiel #29
0
def play():
    btn2['state'] = 'disabled'
    btn0['state'] = 'disabled'
    btn1.configure(bg='orange')
    wishme()
    while True:
        btn1.configure(bg='orange')
        input = listencommand().lower()

        if ('exit') in input:
            var.set("Goodbye ! Have a nice day")
            btn1.configure(bg='#5C85FB')
            btn2['state'] = 'normal'
            btn0['state'] = 'normal'
            windows.update()
            speak("Goodbye! Have a nice day ")
            break

        elif ('hello') in input:
            var.set('Hello Ashish!')
            windows.update()
            speak('Hello Ashish !')

        elif ('what is your name') in input or ('who are you?') in input:
            var.set("Hello ! I am a voice bot named Nory.")
            windows.update()
            speak(
                "Hello ,I am a voice bot named Nory "
                "I am here to make your life easier. You can command me to perform various tasks like "
                "calculations , opening applications etcetra ")

        elif ('do you feel') in input:
            var.set('No I am a voice bot,I do not feel')
            windows.update()
            speak('No  I am a Voicebot, I do not feel')

        elif ('which language do you speak') in input:
            var.set('I speak in English')
            windows.update()
            speak('I speak in English ')

        elif ('when is my birthday') in input:
            var.set('Your birthday is on 30 July')
            windows.update()
            speak(' Your birthday is on 30 July')

        elif ('what is the date and time ') in input or (
                ' date and time') in input:
            var.set(ctime())
            windows.update()
            speak('The date and time is ' + ctime())

        elif ('who am i') in input:
            var.set(
                'You are a humanbeing classified as h**o sapiens according to nomenclature'
            )
            windows.update()
            speak(
                'you are a human being classified as h**o sapiens according to nomenclature'
            )

        elif ('jokes') in input:
            print(pyjokes.get_joke())
            var.set(pyjokes.get_joke())
            windows.update()
            speak('here is a joke for you')

        elif ('game') in input:
            var.set("Opening tic-tac-toe.Enjoy!")
            windows.update()
            speak("opening tictactoe enjoy")
            codepath = "H:\\python vs\\dist\\tic_tac_toe\\tic_tac_toe.exe"
            os.startfile(codepath)

        elif ('calculate') in input or ('find the value of') in input:
            app_id = "8QW392-UJYVJWUWX9"
            client = wolframalpha.Client(app_id)
            indx = input.lower().split().index('calculate')
            query = input.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            var.set(answer)
            windows.update()
            speak("The answer to the question is" + answer)
            print(answer)

        elif ('news') in input:
            res = requests.get('https://timesofindia.indiatimes.com')
            soup = BeautifulSoup(res.text, 'lxml')
            news_box = soup.find('ul', {'class': 'list9'})
            all_news = news_box.find_all('a')
            for news in all_news:
                print(news.text)
                speak("todays headline is :" + news.text)
            windows.update()

        elif ('current weather') in input:
            api_key = "b11dd6fcfbefe8d4f60486bb86ec1449"
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
            city_name = "kanpur"
            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_humidity = y["humidity"]
                z = x["weather"]
                weather_description = z[0]["description"]
                var.set("Temperature (in kelvin unit) =" +
                        str(current_temperature) +
                        "\n atmospheric pressure(in hPa unit =" +
                        str(current_pressure) +
                        "\n humidity (in  percentage =" +
                        str(current_humidity) + "\n description =" +
                        str(weather_description))
                windows.update()
                speak(
                    "this is  the current temperature , pressure, humidity and description of kanpur"
                )
            else:
                print("City not found")

        elif ("chrome") in input:
            var.set("Opening google chrome..")
            windows.update()
            speak(" Opening Google Chrome")
            os.startfile(
                "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            )

        elif ('send mail') in input:
            var.set("Compose Mail")
            windows.update()
            speak("you can compose you mail here")
            url = "https://mail.google.com/mail/u/0/#inbox?compose=new"
            webbrowser.get().open(url)

        elif ("firefox") in input:
            var.set("Opening Mozilla firefox...")
            windows.update()
            speak(" Opening Mozilla Firefox")
            os.startfile(
                "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe")

        elif ('play music') in input:
            var.set("Here are your favourites.Enjoy!")
            windows.update()
            speak('Here are your favorites. enjoy')
            music_dir = "H:\\music"
            songs = os.listdir(music_dir)
            n = random.randint(0, 5)
            print(songs)
            os.startfile(os.path.join(music_dir, songs[n]))

        elif ('code') in input:
            var.set("Opening Visual Studio code.....")
            windows.update()
            speak("Opening visual studio code..")
            codepath = "C:\\Users\\hp\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
            os.startfile(codepath)

        elif ('notepad') in input:
            var.set("Opening notepad...")
            windows.update()
            speak("Opening notepad")
            codepath = "H:\\python vs\\dist\\sushma_notepad\\sushma_notepad.exe"
            os.startfile(codepath)

        elif ('shareit') in input:
            var.set("Opening Shareit....")
            windows.update()
            speak("Opening Shareit..")
            codepath = "C:\\Program Files (x86)\\SHAREit Technologies\\SHAREit\\SHAREit.exe"
            os.startfile(codepath)

        elif ('youtube') in input:
            video = listencommand("which video i should open?")
            url = 'http://youtube.com/search?q=' + video
            var.set("Opening in youtube")
            windows.update()
            speak("Opening  in Youtube...")
            webbrowser.get().open(url)
            speak('This is the video i found ' + video)

        elif ('wikipedia') in input:
            speak('Searching wikipedia....')
            input = input.replace("wikipedia", "")
            results = wikipedia.summary(input, sentences=2)
            speak("According to wikipedia...")
            var.set(results)
            windows.update()
            speak(results)

        elif ('search') in input:
            speak("what do you want me to search for")
            search = listencommand("What do you want me to search for?")
            url = 'http://google.com/search?q=' + search
            windows.update()
            speak('Searching google...')
            webbrowser.get().open(url)
            windows.update()
            speak('here is what i found for your input ' + search)

        elif ('open stackoverflow') in input:
            var.set("Opening Stack overflow..")
            windows.update()
            speak("Opening stackoverflow...")
            url = 'http://www.stackoverflow.com'
            webbrowser.get().open(url)

        elif ('find location') in input:
            var.set("What is the location ?")
            location = listencommand('what is your location?')
            url = 'http://www.google.com/maps/place/' + location
            speak("searching google maps..")
            webbrowser.get().open(url)
            speak('here is the location of' + location)
            windows.update()

        elif ('click photo') in input:
            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 input:
            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) & OxFF == ord('q'):
                        break
                    else:
                        break
            cap.release()
            out.release()
            cv2.destroyAllWindows()
Beispiel #30
0
def process_text(input):
    try:
        if "who are you" in input or "define yourself" in input or "who is Lima" in input:
            speak = '''Hello, I am Lima. Your personal Assistant.
            I am here to make your life easier. 
            You can command me to perform various tasks'''
            assistant_speaks(speak)
            return
        elif "who made you" in input or "created you" in input:
            speak = "I have been created by Surya Raj."
            assistant_speaks(speak)
            return
        elif "who is Surya Raj" in input:
            speak = "Thanks for asking about Surya. He is the creator of me."
            assistant_speaks(speak)
            return
        elif "what can you do" in input:
            speak = '''Something you can ask me like: search web, play youtube, open apps, calculations
           and Q&A. Also, you can add new functionalities as a developer.'''
            assistant_speaks(speak)
            return
        elif "crazy" in input:
            speak = """Well, there are 2 mental asylums in India."""
            assistant_speaks(speak)
            return
        elif "calculate" in input.lower():
            app_id = "UP67VA-28RPELRA52"
            client = wolframalpha.Client(app_id)

            indx = input.lower().split().index('calculate')
            query = input.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            assistant_speaks("The answer is " + answer)
            return
        elif 'the time' in input.lower():
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            assistant_speaks(f"Sir, the time is {strTime}")
        elif 'open' in input:
            open_application(input.lower())
            sys.exit()
        elif 'search' in input or 'play' in input:
            search_web(input.lower())
            sys.exit()

        elif 'wikipedia' in input.lower():
            assistant_speaks('Searching Wikipedia...')
            query = input.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=5)
            assistant_speaks("According to Wikipedia")
            assistant_speaks(results)
            return
        else:
            assistant_speaks(
                "I can search the web for you, Do you want to continue?")
            ans = get_audio()
            if 'yes' in str(ans) or 'yeah' in str(ans):
                search_web(input)
            else:
                return
    except Exception as e:
        print(e)
        assistant_speaks(
            "I don't understand, I can search the web for you, Do you want to continue?"
        )
        ans = get_audio()
        if 'yes' in str(ans) or 'yeah' in str(ans):
            search_web(input)