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
#2
The basic way is like this.
import json

with open('intents.json') as f:
    data = json.load(f)
Now is the json a Python dictionary,as it comes from json it will be a mix of dictionary and list.
Usage will be like this.
>>> data['intents'][0]
{'context': [''],
 '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"],
 'tag': 'greeting'}
>>> data['intents'][0]['patterns']
['Hello', 'Hey', 'Hi', 'Good day']
>>>
>>> data['intents'][1]['responses']
['Farewell',
 'Ok, see you',
 'Goodbye',
 'Finally, I can enjoy some rest',
 'Enjoy your day',
 'Have a nice day']
>>> data['intents'][1]['responses'][-1]
'Have a nice day'
Reply
#3
So if I did:
 if (['intents'][0]['patterns'] in command):
        speak(['intents'][0]['responses'])
Would that work??

I'm a little confused.
Reply
#4
(Mar-29-2022, 11:07 PM)Extra Wrote: Would that work??

I'm a little confused
Yes.and if do small test with print()(easier) before use of speak().
>>> commands = 'Hi'
>>> if commands in data['intents'][0]['patterns']:
...     print(data['intents'][0]['responses'][1])
...     
Welcome back Commander. It's good to see you again
Reply
#5
So I understand that if I set commands = 'hi' and set the response output to index [1] it's going to print "Welcome back Commander. It's good to see you again" because that's the responses index 1.

But what I don't get is how to get it working with my voice assistant script.

If I have an if statement that says:
 if command in data['intents'][0]['patterns']: 
     print(data['intents'][0]['responses'][1])
If the command I speak is a word inside the patterns of the greeting tag it should print the response. But it won't work for me?
Do I need something else, or am I misunderstanding?

Can I call it by the tag and get the patterns and responses from there?
if (command in greetings.patterns): 
     speak(random.choice(greetings.response))
So it looks for the patterns in the greetings tag and speaks a random response??
Reply
#6
(Mar-31-2022, 11:31 PM)Extra Wrote: If the command I speak is a word inside the patterns of the greeting tag it should print the response. But it won't work for me?
Do I need something else, or am I misunderstanding?
If it's a text with serval word you have deal with that.
Example with use of any.
>>> commands = 'Hey this is a test'
>>> if any(word in commands for word in data['intents'][0]['patterns']):
...     print(data['intents'][0]['responses'][0])
...     
Hello Commander. How may I be of service?
If word not in pattern nothing or can add else.
>>> commands = 'This is a test'
>>> if any(word in commands for word in data['intents'][0]['patterns']):
...     print(data['intents'][0]['responses'][0])
... else:    
...     print('Not in patterns')    
...     
Not in patterns
Reply
#7
Ok, so I can get it working when I do:

>>> commands = 'Hey this is a test'
>>> if any(word in commands for word in data['intents'][0]['patterns']):
...     print(data['intents'][0]['responses'][0])
...     
Hello Commander. How may I be of service?
Put I'm having a hard time applying to to my voice assistant script so it takes in my command(received by my mic and converted to a string) and sets it to commands where it will check the json for the matching pattern and response.

Any ideas on how I could get that working?


P.S:
I've also been playing around with a separate python script (intents_test.py) that holds an array of patterns and responses (like the json).

intents_test.py:
def greetings():
        patterns = ['hi', 'hello', 'hey']
        responses = ['hello', 'good day']

def farewell():
        patterns = ['bye', 'see ya', 'good bye']
        responses = ['see you later', 'have a nice day']


I was trying to call the patterns from "greetings()" into my main script so I can test it out that way but I don't know how to call it.
I was thinking
if (command = greetings().patterns)
but that didn't work (at that point I'm pretty sure I was getting confused with another programming language).
Any idea's?

Thanks.
Reply
#8
(Apr-01-2022, 10:55 PM)Extra Wrote: Put I'm having a hard time applying to to my voice assistant script so it takes in my command(received by my mic and converted to a string) and sets it to commands where it will check the json for the matching pattern and response.

Any ideas on how I could get that working?
If the command is convert to a working string then it should work as i have showed.
(Apr-01-2022, 10:55 PM)Extra Wrote: I've also been playing around with a separate python script (intents_test.py) that holds an array of patterns and responses (like the json).
You can make you own structure,but it make no diffence if data comes from a function or json.
Also you most return out of function or it will not work.
I have supposition that you struggle with basic Python understanding,then you may not now if code before or the voice assistant which is the problem.
def greetings():
    patterns = ['hi', 'hello', 'hey']
    responses = ['hello', 'good day']
    return patterns, responses
>>> greetings()
(['hi', 'hello', 'hey'], ['hello', 'good day'])
>>> greetings()[0]
['hi', 'hello', 'hey']
>>> greetings()[0][2]
'hey'
>>> 
>>> # Or can unpack if needed
>>> patterns, greetings = greetings()
>>> patterns
['hi', 'hello', 'hey']
>>> greetings
['hello', 'good day']
Reply
#9
Quote:You can make you own structure,but it make no diffence if data comes from a function or json.
Also you most return out of function or it will not work.

Thanks for the help.
I got it working using my "Intents.py" file by adding the return statement (which I can't believe I forgot) and adding:
    #Greetings from Intents.py
    patterns, responses = greetings()
    if (command in patterns):
        speak(random.choice(responses))

in my voice assistant script.
I'm still gonna try playing around with the "intents.json" to see if I can get that working, but at least I have the "Intents.py" to fall back on if I can't get it working.

Quote:I have supposition that you struggle with basic Python understanding,then you may not now if code before or the voice assistant which is the problem.
Yes I'm new at python, and I'm still learning. The problem for me is that I started taking a programming course at school where we're learning a bunch of different programming languages at once (sadly, python's not one of them), so I tend to get confused and sometimes mix up the languages.


So, thanks for the help.
It's much appreciated.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What is all the info in the info window in Idle? Pedroski55 3 711 Jul-08-2023, 11:26 AM
Last Post: DeaD_EyE
  Python Split json into separate json based on node value CzarR 1 5,638 Jul-08-2022, 07:55 PM
Last Post: Larz60+
  difficulties to chage json data structure using json module in python Sibdar 1 2,096 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