Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

artificial intelligence - Basic Voice Assistance with Python

I am a newbie in Python and I am developing a basic Voice Assistance with my teachers on Raspberry Pi 3. The code in this project is collected and fixed by me. However, as a newbie there are many questions I cant answer. Can you help me, please? I want to develop an assistance which can search on Google, Play music on YouTube and show out the weather forecast. The AI.py is my main file, Google_Search.py is used for searching and YouTube_Search.py is used for playing music. When I ask for searching the AI.py will import the Google_Search.py file to search for my requests. It is similar with YouTube file.

The problem is the Google_Search.py and YouTube_search.py just keep running and don't stop or allow me to keep working with the AI.py file. I want to run these two files while I still can run with the AI.py file to stop or re-open them again. These are the code, Please help me out. Thanks so much.

This is AI.py file

import speech_recognition
import pyaudio
import pyttsx3
import time
import os
import webbrowser, sys, imp
import requests, json
import vlc
import pafy
from datetime import date
from datetime import datetime
from googlesearch import search

robot_ear = speech_recognition.Recognizer()
robot_mouth = pyttsx3.init()
robot_brain = ""


api_key = "82328b3addcd3f984da6c1e74cf4c7c9"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = "Melbourne,au"
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json() 

while True:

    with speech_recognition.Microphone() as mic:
        print("Robot: I'm Listening")
        audio = robot_ear.adjust_for_ambient_noise(mic)
        audio = robot_ear.listen(mic, phrase_time_limit=3)
        
    print("Robot: ...")

    try:
        you = robot_ear.recognize_google(audio, language = "en")
    except:
        you = ""
        
    print("You: " + you)
    

    if you == "":
        robot_brain = "I can't hear you, please try again"
    elif "hello" in you:
        robot_brain = "Hello Minh"
    
    elif "play some music" in you:
        import YouTube_Search
        robot_brain = "Music is playing"
    elif "stop music" in you:
        os.system("pkill YouTube_Search")
        robot_brain = "Music is stoped"

    elif "search something" in you:
        robot_brain = "What do you want me to search for?"
        import Google_Search
        imp.reload(Google_Search)
        time.sleep(5)
    elif "stop searching" in you:
        os.system("pkill chromium")
        robot_brain = "Google search is closed"
    
    elif "weather today" in you:
        if x["cod"] != "404":
            y = x["main"]
            current_pressure = y["pressure"]
            current_humidiy = y["humidity"]
            z = x["weather"]
            weather_description = z[0]["description"]
            robot_brain = (" Temperature: " +
                    str(current_temperature) + " °F" + 
          "
 atmospheric pressure: " +
                    str(current_pressure) + " hPa" +
          "
 humidity: " +
                    str(current_humidiy) + " %" +
          "
 weather today: " +
                    str(weather_description))
    
    elif "bye" in you:
        robot_brain = "Bye Minh"
        print("Robot: " + robot_brain)
        robot_mouth.say(robot_brain)
        robot_mouth.runAndWait()
        break
    else:
        robot_brain = "I'm learning"

    print("Robot: " + robot_brain)
    robot_mouth.say(robot_brain)
    robot_mouth.runAndWait()

This is the Google_Search.py file

import speech_recognition
import os, sys
import webbrowser
robot_brain = ""
robot_ear = speech_recognition.Recognizer()
with speech_recognition.Microphone() as mic:
    #print("Robot: What do you want me to search for?")
    audio = robot_ear.adjust_for_ambient_noise(mic)
    audio = robot_ear.listen(mic, phrase_time_limit=2)

try:
    you = robot_ear.recognize_google(audio, language = 'en-US')
except:
    you = ""
     
search_terms = [you]
            
            # ... construct your list of search terms ...
            
for term in search_terms:
    url = "https://www.google.com/search?q={}".format(term)
    webbrowser.open_new_tab(url)
    robot_brain = ("Here is what I found for") + (" ") + str(you)
        
print("Robot: " + robot_brain)

os.system("pkill Google_Search")

This is the YouTube_Search.py

import vlc
import pafy
import time
import urllib.request
import urllib.parse
import re
import speech_recognition


robot_ear = speech_recognition.Recognizer()
with speech_recognition.Microphone() as mic:
    print("Robot: What do you want me to search for?")
    audio = robot_ear.adjust_for_ambient_noise(mic)
    audio = robot_ear.listen(mic, phrase_time_limit=2)

try:
    you = robot_ear.recognize_google(audio, language = 'en-US')
except:
    you = ""

search = you
query_string = urllib.parse.urlencode({"search_query" : search})
html_content = urllib.request.urlopen("http://www.youtube.com/results?search_query="+query_string)
search_results = re.findall(r"watch?v=(S{11})", html_content.read().decode())
#print("http://www.youtube.com/watch?v=" + search_results[0])
url = "http://www.youtube.com/watch?v=" + search_results[0]

video = pafy.new(url)
best = video.getbest()
playurl = best.url

Instance = vlc.Instance()
player = Instance.media_player_new()
Media = Instance.media_new(playurl)
Media.get_mrl()
player.set_media(Media)
player.play()
question from:https://stackoverflow.com/questions/65894755/basic-voice-assistance-with-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The import keyword in Python is used to load other Python source code files in to the current interpreter session. When you import a file, that file will be run first. If you want to call the program in your imported file, you should use a function and call that. For example:

test.py

def myFunction():
  print("Hello")

main.py

import test
test.myFunction()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...