1

I am facing an issue with my code I want my main code to take input from gui but it assumes returned zero , I don't know what is wrong I need help, also if there is a better way to apply gui to code please do not hesitate to mention it, if there is something that I can read to help me get better please mention it ps: the two codes are in two different files

Main code:

def get_audio():
    # This fuction uses the microphone as an input to speech and recognises it using speech recognition library
    # and it tries to recognise the speech using google recogniser and if it didn't recognise it returns the exception
    # else it returns the speech as text
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
    try:
        text = r.recognize_google(audio, language='en')
        print('User: ' + text + '\n')

    except sr.UnknownValueError:


        speak('Sorry! I didn\'t get that! Try typing the command!')

        __import__(said)
        text=str(said)

tkinter code

stdoutQueue=queue.Queue()

def click():
    said=commandentry.get()
    print(said)
    return (said)

def producer(input):
    while True:
        line = input.readline()
        stdoutQueue.put(line)
        if not line:
            break
def consumer(output, root, term='<end>'):
    try:
        line =stdoutQueue.get(block=False)
    except queue.Empty:
        pass
    else:
        if not line:
            output.write(term)
            return
        output.write(line)
    root.after(250, lambda: consumer(output, root, term))
def redirectGui(command, root):
    input = os.popen(command, 'r')
    output =GuiOutput(root)
    thread.start_new_thread(producer, (input,))
    consumer(output, root)

if __name__=='__main__':
    window = Tk()
    window.geometry("484x670")
    window.title("Jarvis assistant")
    scroll = Scrollbar(window)
    scroll.pack(side=RIGHT, fill='y')
    photo = PhotoImage(file="JARVIS background.PNG")
    Label(window, image=photo, bg='navy blue').pack(side=TOP, expand=True, fill=BOTH)
    Label(window, text="Type or say your command:", fg='black').pack(side=TOP)
    commandentry = Entry(window, width=60)
    commandentry.pack(side=TOP)
    Button(window, text="Send", width=8, command=click).pack(side=BOTTOM)
    redirectGui('python -u jarvis.py', window)
    window.mainloop()

How can I do it ?

main whole code

music = ["song", "music", "play song", "play music", "some music"]
weather = ["what is the weather in", "weather in", "current weather", "today's weather"]
forecast = ["weather forecaste", "forecast"]
jokes = ["What do you call a cow in an earthquake , . , . A milkshake",
         "What did the shark say when it ate a clown-fish . , . , this tastes funny",
         "what do you get when you put a vest on an alligator . , . , an investigator ",
         "How do you keep warm in a cold room  . , . , you go to a corner because its always 90 degrees",
         "I'm reading a book about anti-gravity. , . , I can't put it down.",
         "Time flies like an arrow. , . , Fruit flies like a banana.",
         "What do you call a nervous javelin thrower? , . , . Shakespeare."]
scope = ['https://www.googleapis.com/auth/calendar.readonly']
Months = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november",
          "december"]
Days = ["saturday", "sunday", "monday", "tuesday", "wednesday", "thursday", "friday"]
DayExtension = ["st", "nd", "rd", "th"]
CalenderWords = ["what do i have on....", "do i have plans", "am i busy", "plants", "events", "plans"]
Note_jarvis = ["make a note", "write this down", "remeber that"]


# make voice assisstant speak
def speak(text):
    engine = pyttsx3.init()
    engine.setProperty('rate', 125)
    engine.say(text)
    engine.runAndWait()




# get audio from user
def get_audio():
    # This fuction uses the microphone as an input to speech and recognises it using speech recognition library
    # and it tries to recognise the speech using google recogniser and if it didn't recognise it returns the exception
    # else it returns the speech as text
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        r.pause_threshold = 1
        audio = r.listen(source)
    try:
        text = r.recognize_google(audio, language='en')
        print('User: ' + text + '\n')

    except sr.UnknownValueError:
        speak('Sorry! I didn\'t get that! Try typing the command!')
        text=str(input('enter your command: '))

    return text




# greet user according to the time
def greetMe():
    currentH = int(datetime.datetime.now().hour)
    if currentH >= 0 and currentH < 12:
        speak('Good Morning!')

    if currentH >= 12 and currentH < 18:
        speak('Good Afternoon!')

    if currentH >= 18 and currentH != 0:
        speak('Good Evening!')


# OPEN NOTEPAD TO WRITE IN IT
def note(text):
    date = datetime.datetime.now()
    file_name = str(date).replace(":", "-") + "-note.txt"
    with open(file_name, "w") as f:
        f.write(text)
    subprocess.Popen(["notepad.exe", file_name])


# Authenticate google to begin searching events in user calender
def authenticate_google():
    """check user credintals in google and get them to log in to their google calender """
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no valid credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', scope)
            creds = flow.run_local_server(port=0)
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('calendar', 'v3', credentials=creds)

    return service


# function return time and date of the event
def get_events(day, service):
    date = datetime.datetime.combine(day, datetime.datetime.min.time())
    end_date = datetime.datetime.combine(day, datetime.datetime.max.time())
    utc = pytz.UTC
    date = date.astimezone(utc)
    end_date = end_date.astimezone(utc)
    # currently logged in user primary, iso format is shown format of date
    events_result = service.events().list(calendarId='primary', timeMin=date.isoformat(), timeMax=end_date.isoformat(),
                                          singleEvents=True,
                                          orderBy='startTime').execute()
    # List of events on the calendar
    events = events_result.get('items', [])

    if not events:
        speak('No upcoming events found.')
    else:
        speak(f"You have {len(events)} events on this day.")

        for event in events:
            start = event['start'].get('dateTime', event['start'].get('date'))
            speak(start, event['summary'])
            start_time = str(start.split("T")[0].split("-")[0])  # get the hour the event starts
            if int(start_time.split(":")[0]) < 12:  # if the event is in the morning
                start_time = (int(start_time) + 2) + "am"
            else:
                # int utc
                start_time = str(int(start_time.split(":")[0]) - 12)  # convert 24 hour time to regular
                start_time = start_time + "pm"
            speak(event["summary"] + " at " + "UTC" + (int(start_time) + 2))


def Date(text):
    text = text.lower()
    # To know where to start counting from
    today = datetime.date.today()
    # To check if text said contains today.
    if text.count("today") > 0:
        return today
    day = -1
    day_of_week = -1
    month = -1
    year = today.year

    for word in text.split():
        if word in Months:
            month = Months.index(word) + 1
        elif word in Days:
            day_of_week = Days.index(word)
        elif word.isdigit():
            day = int(word)
        else:
            for ext in DayExtension:
                found = word.find(ext)
                if found > 0:
                    try:
                        day = int(word[:found])
                    except:
                        pass
    # if month is before the month we are currently in , then the year will be next year (7amada helal reaction)
    if month < today.month and month != -1:
        year = year + 1

    # we have a day but not a month
    if month == -1 and day != -1:
        if day < today.day:
            month = today.month + 1
        else:
            month = today.month

        # if we only found a date of the week which is terrible to deal with e7na mmkn n7ot lluser specify ashl :)
    if month == -1 and day == -1 and day_of_week != -1:
        current_day_of_week = today.weekday()
        dif = day_of_week - current_day_of_week
        # if the day we are referring to is less than current day in index
        if dif < 0:
            dif += 7
            if text.count("next") >= 1:
                dif += 7
        # represent duration
        return today + datetime.timedelta(dif)
    # avoid error of returning a negative month which could cause an error :)
    if month == -1 or day == -1:
        return None
    return datetime.date(month=month, day=day, year=year)


Service = authenticate_google()
greetMe()

speak('Hello Sir, I am your voice assistant Jarvis ')
speak('How may i help you?')
print("Ready for you order")

if __name__ == '__main__':

    while True:

        text = get_audio()
        text = text.lower()
        for phrase in CalenderWords:
            if phrase in text:
                date = Date(text)
                if date:
                    get_events(date, Service)
                    speak("next command")
                    text = get_audio()
                    break
                else:
                    speak("Speak again ")

        # Tell weather in a city
        for word in weather:
            if word in text:
                speak("which city do you want?")
                city = get_audio()
                reg_ex = re.search(city, text.lower())
                if reg_ex:
                    city = reg_ex.group(1)
                    location = owm.weather_at_place(city)
                    condition = location.get_weather()
                    # target temperature conversion
                    temp = condition.get_temperature(unit='celsius')
                    for key, val in temp.items():
                        print(f'{key}={val}')
                        speak(f'{key}={val}')
                        speak("next command")
                        text = get_audio()
                        break

        # weather forecast
        for word in forecast:
            if word in text:
                reg_ex = re.search('weather forecast in (.*)', text.lower())
                if reg_ex:
                    city = reg_ex.group(1)
                    location = owm.weather_at_place(city)
                    weather = location.get_weather()

                    # temperature
                    temp = weather.get_temperature(unit='celsius')

                    for key, val in temp.items():
                        print(f'{key} => {val}')
                        break

                    # humidity, wind, rain, snow
                    humidity = weather.get_humidity()
                    wind = weather.get_wind()
                    rain = weather.get_rain()
                    snow = weather.get_snow()

                    print(f'humidity = {humidity}')
                    print(f'wind = {wind}')
                    print(f'rain = {rain}')
                    print(f'snow = {snow}')
                    speak(f'humidity = {humidity}' + "%")
                    speak(f'wind = {wind}')

                    # clouds and rain
                    loc = owm.three_hours_forecast(city)

                    clouds = str(loc.will_have_clouds())
                    rain = str(loc.will_have_rain())

                    if rain == True:
                        speak("It will rain")
                    else:
                        speak("no rain")
                    if clouds == True:
                        speak("It will be cloudy")
                        speak("next command")
                        text = get_audio()
                        break


                    else:
                        speak("It will not be cloudy today")
                        speak("next command")
                        text = get_audio()
                        break

        for words in music:
            if words in text:
                speak("name of the song")
                query_string = urllib.parse.urlencode({"search_query": get_audio()})
                html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
                search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
                webbrowser.open("http://www.youtube.com/watch?v=" + search_results[0])
                speak("next command")
                text = get_audio()
                break

        else:
            if text in Note_jarvis:
                speak("what would you like me to write down sir")
                note_text = get_audio()
                note(note_text)
                speak("done sir")

            elif 'open youtube' in text:
                speak('okay')
                webbrowser.open('www.youtube.com')

            elif 'open google' in text:
                speak('okay')
                webbrowser.open('www.google.co.in')

            elif 'open gmail' in text:
                speak('okay')
                webbrowser.open('www.gmail.com')
            elif 'news' in text:
                webbrowser.open('https://www.bbc.com/news/world')
            elif "what\'s up" in text or 'how are you' in text:
                stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy']
                speak(random.choice(stMsgs))
            elif 'joke' in text:
                speak(random.choice(jokes))
            elif 'email' in text:
                speak('Who is the recipient? ')
                recipient = input("enter the email address: ")
                password = input('enter your password')
                speak("what is you google email address")
                # Allow less secure app in your google account to avoid being stuck in 4 hours of exception :)
                myemail = input("enter your email adress")
                try:
                    speak('What should I say? ')
                    content = ('Hello, \n Hope this email finds you well ' + get_audio())

                    server = smtplib.SMTP('smtp.gmail.com', 587)
                    server.ehlo()
                    server.starttls()
                    server.login(myemail, password)
                    server.sendmail(myemail, recipient, content)
                    server.close()
                    speak('Email sent!')

                except:
                    speak('Sorry Sir! I am unable to send your message at this moment!')



            elif 'nothing' in text or 'abort' in text or 'stop' in text:
                speak('okay')
                speak('Bye, have a nice day and do not forget to give my makers the full mark.')
                sys.exit()

            elif 'hello' in text:
                speak('Hello Sir')

            elif 'bye' in text:
                speak('Bye, have a nice day and do not forget to give my makers the full mark.')
                sys.exit()
            else:
                text = text
                speak('Searching...')
                try:
                    try:
                        res = client.query(text)
                        results = next(res.results).text
                        speak('Got it.')
                        speak('WOLFRAM-ALPHA says - ')
                        print(results)
                        speak(results)
                    except:
                        results = wikipedia.summary(text, sentences=2)
                        speak('Got it.')
                        speak('WIKIPEDIA says - ')
                        print(results)
                        speak(results)
                except:
                    # tld stands for domain because maybe we wamt to search in .com not scholar, pause is the time between each http request
                    query = text
                    for i in search(query, tld='com', lang='en', num=1, stop=1, pause=2.0):
                        print(i)
                        webbrowser.open(i)

            speak('Next Command! Sir!')
4
  • Is the indent right? Commented Jun 2, 2020 at 15:31
  • yes but It's my first time to copy into stack overflow so I probably didn't copy it right Commented Jun 2, 2020 at 15:48
  • I have revised your post, just check it. Commented Jun 2, 2020 at 15:49
  • ok , thanks they are two separate codes I want to link them together problem in main code is that it have too many function in it so I couldn't put gui directly Commented Jun 2, 2020 at 16:18

1 Answer 1

1

For gui code I added another code named shared.py import tkinter as Tk from tkinter import *

def on_click():
    said = commandentry.get()
    print(said)
    return said


window =Tk()
commandentry = Entry(window, width=60)
commandentry.pack(side=TOP)
Button(window, text="Send", width=8, command=lambda: on_click()).pack(side=BOTTOM)
window.mainloop()

for the main code to take only return value I used subprocess like this

cp = subprocess.run(['python.exe', 'shared.py'], universal_newlines=True, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
        text= cp.stdout
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.