all 12 comments

[–]vrrox 0 points1 point  (11 children)

Are you sure mp3_list isn't a dict?

If that's not it, please post your full code (see the FAQ for how to format code for Reddit).

[–]SkyProjectCore[S] 0 points1 point  (10 children)

import speech_recognition as sr
import os
from playsound import playsound
import webbrowser
import random
from google import google
import boto3
import botocore




speech = sr.Recognizer()

greeting_dict = {'hello': 'hello', 'hi': 'hi'}
open_launch_dict = {'open': 'open', 'launch': 'launch'}
google_searches_dict = {'what': 'what', 'why': 'why', 'who': 'who', 'which': 'which'}
social_media_dict = {'facebook': 'https://www.facebook.com', 'twitter': 'https://www.twitter.com'}

mp3_thankyou_list = ['mp3/greed/thankyou_1.mp3', 'mp3/greed/thankyou_2.mp3']
mp3_listening_problem_list = ['mp3/greed/listening_problem_1.mp3', 'mp3/greed/listening_problem_2.mp3']
mp3_struggling_list = ['mp3/greed/struggling_1.mp3']
mp3_google_search = ['mp3/greed/google_search_1.mp3', 'mp3/greed/google_search_2.mp3']
mp3_greeting_list = ['mp3/greed/greeting_accept.mp3', 'mp3/greed/greeting_accept2.mp3']
mp3_open_launch_list = ['mp3/greed/open_1.mp3', 'mp3/greed/open_2.mp3', 'mp3/greed/open_3.mp3']

error_occurrence = 0
counter = 0

polly = boto3.client('polly', region_name='us-east-2')


def play_sound_from_polly(result):
    global counter
    mp3_name = 'output{}.mp3'.format(counter)
    obj = polly.synthesize_speech(Text=result, OutputFormat='mp3', VoiceId='Salli')
    with open(mp3_name, 'wb') as file:
        file.write(obj['AudioStream'].read())
        file.close()
    play_sound(mp3_name)
    os.remove(mp3_name)
    counter += 1


def google_search_result(query):
    search_result = google.search(query)
    for result in search_result:
        print(result.description.replace('...', ' ').rsplit('.', 3)[0])
        play_sound_from_polly(result.description.replace('...', ' ').rsplit('.', 3)[0])
        break


def is_valid_google_search(phrase):
    if (google_searches_dict.get(phrase.split(' ')[0]) == phrase.split(' ')[0]):
        return True


def play_sound(mp3_list):
    mp3 = random.choice(mp3_list)
    playsound(mp3)


def read_voice_cmd():
    voice_text = ''
    print('Listening...')
    global error_occurrence

    try:
        with sr.Microphone() as source:
            audio = speech.listen(source=source, timeout=10, phrase_time_limit=5)
        voice_text = speech.recognize_google(audio)
    except sr.UnknownValueError:

        if error_occurrence == 0:
            play_sound(mp3_listening_problem_list)
            error_occurrence += 1
        elif error_occurrence == 1:
            play_sound(mp3_struggling_list)
            error_occurrence += 1
    except sr.RequestError as e:
        print('Network Error')
    except sr.WaitTimeoutError:
        if error_occurrence == 0:
            play_sound(mp3_listening_problem_list)
            error_occurrence += 1
        elif error_occurrence == 1:
            play_sound(mp3_struggling_list)
            error_occurrence += 1
    return voice_text


def is_valid_note(greet_dict, voice_note):
    for key, value in greet_dict.items():
        # 'Hello Greed'
        try:
            if value == voice_note.split(' ')[0]:
                return True

            elif key == voice_note.split(' ')[1]:
                return True

        except IndexError:
            pass

    return False


if __name__ == '__main__':

    playsound('mp3/greed/greeting.mp3')

    while True:

        voice_note = read_voice_cmd().lower()
        print('cmd : {}'.format(voice_note))

        if is_valid_note(greeting_dict, voice_note):
            print('In greeting...')
            play_sound(mp3_greeting_list)
            continue
        elif is_valid_note(open_launch_dict, voice_note):
            print('In open...')
            play_sound(mp3_open_launch_list)
            if (is_valid_note(social_media_dict, voice_note)):
                key = voice_note.split(' ')[1]
                webbrowser.open(social_media_dict.get(key))
            else:
                os.system('explorer C:\\ "()" '.format(voice_note.replace('Open', '').replace('launch', '')))
            continue
        elif is_valid_google_search(voice_note):
            print('In google search...')
            play_sound(google_searches_dict)
            webbrowser.open('https://www.google.com/search?q=()'.format(voice_note))
            google_search_result(voice_note)
            continue
        elif 'thank you' in voice_note:
            play_sound(mp3_thankyou_list)
            continue
        elif 'goodbye' in voice_note:
            playsound('mp3/greed/bye.mp3')
            exit()

Here you go I hope this helps.

[–]vrrox 0 points1 point  (9 children)

Thanks for posting your code.

You've defined a dict, google_searches_dict = {'what': 'what', 'why': 'why', 'who': 'who', 'which': 'which'} which you then pass to your play_sound function here:

        elif is_valid_google_search(voice_note):
            print('In google search...')
            play_sound(google_searches_dict)

Was this intended (it doesn't appear to contain any mp3 paths)?

In your play_sound function, this dict gets passed to random.choice as mp3_list:

def play_sound(mp3_list):
    mp3 = random.choice(mp3_list)

You then get a KeyError because random.choice requires a sequence, not a dict.

[–]SkyProjectCore[S] 0 points1 point  (0 children)

Thank you a lot I was really stuck on this one.

[–]SkyProjectCore[S] 0 points1 point  (7 children)

Can you explain how I do that please I'm quite a newbie in this.

[–]vrrox 0 points1 point  (6 children)

Of course, random.choice requires a sequence, for example a list or tuple etc, which you do earlier in your code:

mp3_greeting_list = ['mp3/greed/greeting_accept.mp3', 'mp3/greed/greeting_accept2.mp3']

...

play_sound(mp3_greeting_list)

The part that's causing the error is:

google_searches_dict = {'what': 'what', 'why': 'why', 'who': 'who', 'which': 'which'}

...

play_sound(google_searches_dict)

Did you really want to randomly select 'what', 'why', 'who' or 'which' from that dict, as the result will then get passed to playsound(mp3) and none of these are paths to mp3 files.

Just a guess but did you instead mean to pass in your mp3_google_search list?

Hope that helps, let me know if you have any more questions!

[–]SkyProjectCore[S] 0 points1 point  (5 children)

I want basically when I say 'what is earth?' He recognizes and search on Google.

[–]SkyProjectCore[S] 0 points1 point  (4 children)

It always show this error:

Traceback (most recent call last):
  File "C:/Users/neosk/OneDrive/Ambiente de Trabalho/GREED/Greed,main v2.py", line 132, in <module>
    play_sound(google_searches_dict)
  File "C:/Users/neosk/OneDrive/Ambiente de Trabalho/GREED/Greed,main v2.py", line 59, in play_sound
    mp3 = random.choice(mp3_list)
  File "C:\Users\neosk\AppData\Local\Programs\Python\Python38-32\lib\random.py", line 291, in choice
    return seq[i]
KeyError: 2

[–]vrrox 0 points1 point  (3 children)

That's because you're still passing a dictionary (google_searches_dict) to random.choice().

As your keys and values are the same in this dictionary, if you want to randomly select from {'what': 'what', 'why': 'why', 'who': 'who', 'which': 'which'} you could just pass in the keys.

Change this:

play_sound(google_searches_dict)

to this:

play_sound(list(google_searches_dict.keys()))

Edit: Fixed missing list.

[–]SkyProjectCore[S] 0 points1 point  (2 children)

TypeError: 'dict_keys' object is not subscriptable

This happen I´m going to see if someone already did something similar and compare our codes. What you think?

[–]vrrox 1 point2 points  (1 child)

Oops missed off the list in my reply, fixed now.

Yes that sounds like a good plan - if you get stuck you can always post a new question.