class SimonSaysService:
    '''
        Houses the simon says services.
    '''
    def __init__(self):
        '''
            Setup for the service dependencies.
        '''
        self.assistant = Assistant()
        self.game_commands = ["Touch your head", "Touch your toes", "Spin around", "Touch your ears", "Touch your ears", "Touch your eyes", "Jump!", "Touch your hair",
            "Do 5 jumping jacks", "Do 5 press ups", "Do 5 situps", "Do 5 Burpees", "Wink with your left eye", "Wink with your right eye", "Walk like a penguin", 
            "Act like a monkey", "Sit down", "Stand on one foot", "Touch your nose", "Pretend to ride a horse", "Pretend to swim", "Turn around",
            "Walk on the spot", "Pretend to sit on a chair", "Don't move", "Pretend to lift a very heavy box", "Pretend to drink water", "Walk in a straight line",
            "Pretend to be cold", "Moo like a cow", "Whispher your name", "Do a silly dance", "Move in slow motion"]
        self.simon_commands = ["Simon says", ""]

    def mirror_me(self):
        '''
            Repeat whatever the user says.
        '''
        # Get the user command to mirror and repeat if they don't say anything.
        while True:
            self.assistant.speak("What does Simon say?")
            print("What does Simon say?")
            command = self.assistant.take_command()

            if command != "None":
                break

        # Speak what they say.
        self.assistant.speak("Simon says, " + command)
        print("Simon says, " + command)

        time.sleep(1)

    def simon_says_game(self):
        '''
            Simon says game. Tasks give at random to perform 10 times.  
            If the command doesn't have simon says at the front you shouldn't
            complete the task and visversa. 
        '''
        # Perform 10 rounds.
        for round in range(10):
            # Get a random game command and random start of command.
            simon_command = random.choices(self.simon_commands)
            command = random.choices(self.game_commands)

            # Print and speak new command.
            if simon_command[0] != "":
                self.assistant.speak(simon_command[0] + " " + command[0])
                print(simon_command[0] + " " + command[0])
            else:
                self.assistant.speak(command[0])
                print(command[0])
        
            time.sleep(5)

        self.assistant.speak("Game over! Thanks for playing!")
        print("\nGame over! Thanks for playing!")
        time.sleep(1)
Example #2
0
class MusicService:
    '''
        Houses the music service and it's related methods.
    '''
    def __init__(self, key):
        '''
            Setup the dependencies.  
            Args:
                key: string, music api key.
        '''
        self.api_key = "&apikey=" + key
        self.assistant = Assistant()

    def get_input(self, question):
        '''
            Get the input from the user.  
            Args:
                question: string, quesiton to ask.  
            Returns:
                statement: string, user input.
        '''
        # Ask for input and ask again if nothing is returned.
        while True:
            self.assistant.speak(question)
            print(question)
            statement = self.assistant.take_command()

            if statement != "None":
                break
        
        return statement

    def sing_song_segment(self):
        '''
            Call the api and sing the start of the song to the user via the assistant.
        '''
        self.assistant.speak("Welcome to the Music Service!")
        print("Welcome to the Music Service!")

        artist_name = self.get_input("Whats's the name of the artist?")
        track_name = self.get_input("What's the name of the track?")

        self.assistant.speak("Loading music...")
        print("Loading music...")

        # Create API request.
        api_call = "https://api.musixmatch.com/ws/1.1/matcher.lyrics.get?format=json&callback=callback&q_artist=" + artist_name + "&q_track=" + track_name + self.api_key
        
        # Perform the API call.
        try:
            request = requests.get(api_call)
            data = request.json()
            # Extract the data from reponse and print/speak.
            data = data['message']['body']
            data['lyrics']['lyrics_body'] = data['lyrics']['lyrics_body'].replace("\n...\n\n******* This Lyrics is NOT for Commercial use *******", "")
            self.assistant.speak(f"Playing {track_name} by {artist_name}")
            print(f"Playing {track_name} by {artist_name}")
            print(data['lyrics']['lyrics_body'])
            self.assistant.speak(data['lyrics']['lyrics_body'])
        except Exception:
            self.assistant.speak(f"Sorry the song, {track_name} by {artist_name} wasn't found.")
            print(f"Sorry the song, {track_name} by {artist_name} wasn't found.")

        time.sleep(1)
Example #3
0
# Program dependencies
assistant = Assistant()
os_service = OSService()
internet_service = InternetService()
general_service = GeneralService()
simon_says_service = SimonSaysService()
quiz_service = QuizService()
file_service = FileService("./appsettings.json")
appsettings = file_service.read_appsettings()
api_call_service = ApiCallService(appsettings["WeatherApiKey"],
                                  appsettings["WolframalphaApiKey"])
music_service = MusicService(appsettings["MusixmatchApiKey"])

# Startup
print("Loading your AI personal assistant Jarvis")
assistant.speak("Loading your AI personal assistant Jarvis")
assistant.wish_me()

print("\n     ###############     ")
print("     ##           ##     ")
print("     #  ~~     ~~  #     ")
print("     #  ()     ()  #     ")
print("     (      ^      )     ")
print("      |           |      ")
print("      |  {=====}  |      ")
print("       \         /       ")
print("      /  -------  \      ")
print("    --- |%\   /%| ---    ")
print("  /     |%%%%&%%|    \   ")
print(" |      |%/   \%|     |  ")
print(" |                    |  ")
Example #4
0
class QuizService:
    '''
        Houses the quiz service logic.
    '''
    def __init__(self):
        '''
            Setup the quiz service dependencies.
        '''
        self.assistant = Assistant()
        self.questions = [
            ("What is the biggest animal in the world?", "blue whale"),
            ("Which country did brie cheese originate from?", "france"),
            ("What year was Heniz established?", "1869"),
            ("What is a baby rabbit called?", "kit"),
            ("As of 2020 who is manager of the england football team?",
             "gareth southgate"),
            ("What does He stand for on the periodic table?", "helium"),
            ("What is the capital of Australia?", "canberra"),
            ("Which bird can fly backwards?", "hummingbird"),
            ("When did the Vietnam War end?", "1975"),
            ("Which hit video game series has released games called World At War and Black Ops?",
             "call of duty"),
            ("What building did I'm a Celebrity 2020 taking place in?",
             "castle"),
            ("What type of nut is in the middle of a Ferrero Rocher?",
             "hazelnut"), ("What is a baby kangaroo called?", "joey"),
            ("What's the national flower of Japan?", "cherry blossom"),
            ("Which football team is known as The Red Devils?",
             "manchester united"),
            ("Which football team is known as The Baggies?",
             "west bromwich albion"),
            ("How many ghosts visit Scrooge in A Christmas Carol?", "4"),
            ("Which TV series has an alternate universe called The Upside Down?",
             "stranger things"),
            ("In Texas, it’s illegal to swear in front of what?", "corpse"),
            ("What was Marilyn Monroe’s natural hair color?", "red"),
            ("What do you call a group of unicorns?", "blessing"),
            ("What is banned in public places in Florida after 6 pm on a Thursday?",
             "farting"),
            ("What animal cannot stick out its tongue?", "crocodile"),
            ("With how many bricks is the Empire State Building made of?",
             "10 million"),
            ("According to Russian law, a homeless person must be where after 10 pm?",
             "at home"),
            ("How many years old the oldest piece of chewing gum?",
             "9000 years"),
            ("On Sunday, what is illegal to sell in Columbus, Ohio?",
             "cornflake"),
            ("What is illegal to eat with a cherry pie in Kansas?",
             "ice cream"),
            ("On average, what is the thing that Americans do 22 times in a day?",
             "open the fridge"),
            ("A crossbreed between a donkey and the zebra is known as?",
             "zonkey"),
            ("What was the first fruit that was eaten on the moon?", "peach"),
            ("How do you tell the age of a horse?", "it's teeth"),
            ("What sport has been played on the moon?", "golf"),
            ("How many noses does a slug have?", "four"),
            ("What were clocks missing before 1577?", "minute hands")
        ]

    def play_quiz(self):
        '''
            Play the quiz game.  
            Asked 5 questions and given 10 seconds to think of an anwser.  
            Then the assistant will ask for your asnwer and store whether you
            got it right or wrong.  
            At the end you will get given a score out of 5.
        '''
        print(
            "Welcome to the Quiz! Here's how this is going to work. Your going to be asked 5 questions total and then given a score out of 5 at the end. "
            +
            "Each round you get asked a question and then given 10 seconds to think of an answer. After the 10 seconds are up you will asked by Jarvis for your answer. Until you "
            +
            "have answered 5 questions. Once you have completed the quiz you'll get your score."
        )
        self.assistant.speak(
            "Welcome to the Quiz! Here's how this is going to work. Your going to be asked 5 questions total and then given a score out of 5 at the end. "
            +
            "Each round you get asked a question and then given 10 seconds to think of an answer. After the 10 seconds are up you will be asked by Jarvis for your answer. Until you "
            +
            "have answered 5 questions. Once you have completed the quiz you'll get your score."
        )

        previous_questions = []
        score = 0

        # Perform 5 rounds.
        for round in range(5):
            self.assistant.speak(f"Round {round + 1}")
            print(f"Round {round + 1}")
            running = True
            exists = True

            # Get the question from the list and get another if it already exists.
            while running:
                random_question = random.choices(self.questions)

                if random_question in previous_questions:
                    random_question = random.choices(self.questions)
                else:
                    running = False

            previous_questions.append(random_question)

            self.assistant.speak(random_question[0][0])
            print(random_question[0][0])
            time.sleep(10)

            # Get the user's answer.
            while True:
                self.assistant.speak("What is your answer?")
                print("What is your answer?")
                statement = self.assistant.take_command()

                if statement != "None":
                    break

            # Check the answer is correct or not.
            if statement.lower() in random_question[0][1]:
                print("Correct")
                self.assistant.speak("Correct")
                score += 1
            else:
                print("Incorrect")
                self.assistant.speak("Incorrect")

            time.sleep(1)

        # Final score and exit speech.
        print("Quiz Complete!")
        self.assistant.speak("Quiz Complete!")

        print("Drum role please...")
        self.assistant.speak("Drum role please...")

        print(f"Your final score is, {score} points!")
        self.assistant.speak(f"Your final score is, {score} points!")

        print("Well done and thanks for playing!")
        self.assistant.speak("Well done thanks for playing!")

        time.sleep(1)
class InternetService:
    '''
        Houses all the logic responsible for the internet.
    '''
    def __init__(self):
        '''
            Setting up the dependencies.
        '''
        self.assistant = Assistant()

    def open_tab(self, url, website_name):
        '''
            Open a new tab for the user.  
            Args:
                url: string, url search string.
                website_name: string, website name.
        '''
        webbrowser.open_new_tab(url)
        self.assistant.speak(f"{website_name} is open now")
        print(f"{website_name} is open now")
        time.sleep(1)

    def search_web(self, statement):
        '''
            Open a new browser based of the statement given by the user.  
            Args:
                statement: string, user command.
        '''
        statement = statement.replace("search", "")
        search_query = ""
        statement = statement.split()

        # Create the query string.
        for item in range(len(statement)):
            if item == 0:
                search_query += statement[item]
            else:
                search_query += "+" + statement[item]

        webbrowser.open_new_tab(
            f"https://www.bing.com/search?q={search_query}")
        self.assistant.speak("Website is open")
        print("Website is open")
        time.sleep(1)

    def search_wikipedia(self, statement):
        '''
            Search wikipedia based off the user statement.  
            Args:
                statement: string, user command.
        '''
        self.assistant.speak("Searching Wikipedia...")
        print("Searching Wikipedia...")

        # Fetch wikipedia data.
        try:
            # Get rid of the word wikipedia in the statement.
            statement = statement.replace("wikipedia", "")
            results = wikipedia.summary(statement, sentences=3)
            self.assistant.speak("According to Wikipedia")
            print(results)
            self.assistant.speak(results)
        except Exception:
            self.assistant.speak("That Wikipedia page couldn't be found")
            print("That Wikipedia page couldn't be found")

        time.sleep(1)
Example #6
0
class ApiCallService:
    '''
        Houses all logic for calling the third party API's.
    '''
    def __init__(self, weather_api_key, wolframalpha_api_key):
        '''
            Setup for API keys from appsettings and other dependencies.
        '''
        self.weather_api_key = weather_api_key
        self.wolframalpha_api_key = wolframalpha_api_key
        self.assistant = Assistant()
        self.general_service = GeneralService()

    def forecast_weather(self):
        '''
            Forecast weather using the openweathermap api.
        '''
        self.assistant.speak("What is the city name")
        city_name = self.assistant.take_command()
        # Create the API request.
        complete_url = "https://api.openweathermap.org/data/2.5/weather?" + "appid=" + self.weather_api_key + "&q=" + city_name
        response = requests.get(complete_url)
        response_dic = response.json()

        # Check if the response is bad.
        if response_dic["cod"] != "404":
            # Extract response and print out.
            data = response_dic["main"]
            current_temperature = data["temp"]
            current_temperature = self.general_service.convert_temperature(
                current_temperature)
            current_humidity = data["humidity"]
            weather_data = response_dic["weather"]
            weather_description = weather_data[0]["description"]
            self.assistant.speak(
                f"Tempurature is {current_temperature} degrees celsius.\nHumidity is {current_humidity} percent.\nDescription {weather_description}."
            )
            print(
                f"Tempurature is {current_temperature} degrees celsius.\nHumidity is {current_humidity} percent.\nDescription {weather_description}."
            )
        else:
            self.assistant.speak("Failed to fetch weather data.")
            print("Failed to fetch weather data.")

        time.sleep(1)

    def call_wolframalpha(self):
        '''
            Respond to questions about computational and geographical questions using
            the wolframalpha api.
        '''
        self.assistant.speak(
            "I can answer to computational and geographical questions and what question do you want to ask now?"
        )
        print(
            "I can answer to computational and geographical questions and what question do you want to ask now?"
        )
        question = self.assistant.take_command()

        # Call and fetch data.
        try:
            client = wolframalpha.Client(self.wolframalpha_api_key)
            res = client.query(question)
            answer = next(res.results).text
            self.assistant.speak(answer)
            print(answer)
        except Exception:
            self.assistant.speak("Failed to fetch response.")
            print("Failed to fetch response.")

        time.sleep(1)