Python Forum
Taking info from Json & using it in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Taking info from Json & using it in Python
#1
Hello,

I have a json file filled with intents that I would like to use in my voice assistant.

I would like to have so it goes when I say one of the patterns it says the corresponding response.
The greetings I would like to be random, but the easterEggs, about, & other sections/tags to be specific/in order.

I get that it would have to be like an array. For example if I said: "Open the pod bay doors" that would be at index 0 in the patterns array, and it's corresponding answer would be: "I'm afraid I can't do that" which is at index 0 in the responses array.

I'm having a hard time implementing because I keep blanking when it comes to the json & I don't know how to implement the json into my python, So any help would be greatly appreciated.
Thanks.

My intents.json:
{"intents": [
    {"tag": "greeting",
        "patterns": ["Hello", "Hey", "Hi", "Good day"],
        "responses": ["Hello Commander. How may I be of service?", 
                    "Welcome back Commander. It's good to see you again"],
        "context": [""]
    },
    {"tag":"farewell",
        "patterns": ["Bye", "See you later", "Goodbye", "I'm leaving", "See you tomorrow"],
        "responses":["Farewell", "Ok, see you", "Goodbye", "Finally, I can enjoy some rest", 
                    "Enjoy your day", "Have a nice day"],
        "context":[""]
    },
    {"tag":"thanks",
        "patterns":["Thanks", "Thank you", "Thanks a lot", "Awesome, thanks"],
        "responses":["No problem", "Happy to help", "Glad to be of service", "My pleasure",
                    "It's no big deal"],
        "context":[""]
    },
    {"tag":"noAnswer",
        "patterns":[],
        "responses":["Sorry, I can't understand you", "I'm not sure I understand"],
        "context":[""]
    },
    {"tag":"about",
        "patterns":["Who are you?", "How old are you?", "Can you get smarter?", "Are you happy?",
                    "What's your favourite movie?", "What's your favourite song?", "Where are you?"],
        "responses":["I am Baxter", "Old enough. Now go fetch me a beer. It's been a rough day",
                     "If you program me to", "Is anyone really happy?", "The Terminator", 
                     "Jimmy cliff's: I can see clearly now", "I'm everywhere and nowhere"],
        "context":[""]
    },
    {"tag":"easterEggs",
        "patterns":["Open the pod bay doors", "Who you gonna call?", "I am your father",  
                    "May the force be with you", "What is your power level?", "Testing"],
        "responses":["I'm afraid I can't do that", "Ghostbusters!", "No, that's not true. That's impossible", 
                    "And may the force be with you, always", "It's over nine-thousand!", "Receiving, over"],
        "context":[""]
    },
    {"tag":"other",
        "patterns":["Will you marry me", "Are we friends", "I'm busy", "I love you"],
        "responses":["A life long commitment with you? I'm going to need some time to think about it",
                    "It's a great show, but it's nowhere near reality", "Then why are you bothering me?"],
        "context":[""]
    }
]}
My voice assistant:
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import os
import time
import sys
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import speech_recognition as sr 
from Animations import startupAnimation

#-------------------------------------------------------------------------------------
                            #Commander Name (You) and A.I Name
#-------------------------------------------------------------------------------------
Commander = "Commander"
AI_Name = 'Baxter'
#-------------------------------------------------------------------------------------

def speak(audio):
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice',voices[1].id)
    engine.setProperty('rate', 125)
    engine.setProperty('volume', 1.0)
    engine.say(audio)
    engine.runAndWait()
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)   
    else:
        speak("Good Evening" + Commander) 


def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)  
    #---------------------------
    # Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')
    #--------------------------------

    except:
            pass

    return command 

wishMe()
speak("How may I be of service?")  

#Initiate Start Up Animation
#startupAnimation()

while True:
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command): 
        if ('who is' in command) or ('what is the' in command) or ('what is a' in command) or ("what is" in command):
            if ('time' not in command):
                if ('news' not in command):
                    speak('Searching Wikipedia...')
                    command = command.replace("who is","")
                    command = command.replace("what is the","")
                    command = command.replace("what is a","")
                    command = command.replace("what is","")
                    results = wikipedia.summary(command, sentences = 2)
                    #----------------------
                    #Auto typing animation:
                    print("Baxter: ", end="")
                    for i in results:
                        sys.stdout.write(i)
                        sys.stdout.flush()
                        time.sleep(0.05)
                    print("\n")
                    #----------------------
                    #speak(results) 
                    engine = pyttsx3.init()
                    voices = engine.getProperty('voices')
                    engine.setProperty('voice',voices[1].id)
                    engine.setProperty('rate', 125 )
                    engine.setProperty('volume',1.0)
                    engine.say(results)
                    engine.runAndWait() 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    if ('weather' not in command):
        if ('news' not in command):
            if ('calculate' in command) or ("what's" in command) or ('define' in command):
                speak('Searching Wolfram Alpha...')
                command = command.replace("calculate","")
                command = command.replace("what's","")
                command = command.replace("define","")
                # Wolframalpha App Id
                appId = 'JH9XHR-W9J76L7H5A'
                # Wolfram Instance
                client = wolframalpha.Client(appId)
                res = client.query(''.join(command))
                results = next(res.results).text
                #----------------------
                #Auto typing animation:
                print("Baxter: ", end="")
                for i in results:
                    sys.stdout.write(i)
                    sys.stdout.flush()
                    time.sleep(0.05)
                print("\n")
                #----------------------
                speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    if ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        #Gets the news headlines from this url:
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    if ('weather' in command):
        if ('week' in command):
            speak('Searching weather networks...')
            command = command.replace("weather for the week","")
            #Call weather data for the week:
            displayWeeksWeatherData()
        else:
            speak('Searching weather networks...')
            command = command.replace("weather","")
        #Call weather data for today:
        displayWeatherData()
    #-------------------------------------------------------------------------------------
                                        #Tell Time
    #-------------------------------------------------------------------------------------
    elif ('time' in command):
        speak('Scanning local clock networks...')
        command = command.replace("time","")
        strTime = datetime.datetime.now().strftime("%I:%M%P")
        speak("The time is {strTime}")
        print("Baxter: The time is ", strTime)
    #-------------------------------------------------------------------------------------
                                #Enter the Matrix (Easter Egg)
    #-------------------------------------------------------------------------------------
    elif ('matrix' in command):
        speak('Entering the matrix...')
        command = command.replace("matrix","")
        response = "Taking the red pill..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        time.sleep(2)
        os.system("cmatrix")
    #-------------------------------------------------------------------------------------

    #-------------------------------------------------------------------------------------
                                #Stop Program/Script Command
    #-------------------------------------------------------------------------------------
    elif ('stop' in command) or ('shutdown' in command) or ('quit' in command):
        speak("Shutting Down...")
        response = "Terminating program..."
        #----------------------
        #Auto typing animation:
        print("Baxter: ", end="")
        for i in response:
            sys.stdout.write(i)
            sys.stdout.flush()
            time.sleep(0.2)
        print("\n")
        #----------------------
        exit()
    #-------------------------------------------------------------------------------------
Reply


Messages In This Thread
Taking info from Json & using it in Python - by Extra - Mar-29-2022, 10:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  What is all the info in the info window in Idle? Pedroski55 3 774 Jul-08-2023, 11:26 AM
Last Post: DeaD_EyE
  Python Split json into separate json based on node value CzarR 1 5,930 Jul-08-2022, 07:55 PM
Last Post: Larz60+
  difficulties to chage json data structure using json module in python Sibdar 1 2,148 Apr-03-2020, 06:47 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020