PC & IT SUPPORT MADE EASY FORUM
Would you like to react to this message? Create an account in a few clicks or log in to continue.

A perfect AI Assistant

Go down

A perfect AI Assistant Empty A perfect AI Assistant

Post by jamied_uk 4th May 2023, 22:03

For Windows Python 3

Notes

How to Create Personal AI Assistant Like Iron Man
For venv

For Linux

python3 -m venv myenv

This will create a new virtual environment in a directory named myenv.

To activate the virtual environment, use the following command:



source myenv/bin/activate

This will activate the virtual environment and change your terminal prompt to indicate that you are now working within the virtual environment.

Note: If you are using the fish shell, the command to activate the virtual environment is slightly different. Use the following command instead:



source myenv/bin/activate.fish

Once you have activated the virtual environment, you can install any necessary packages using pip. For example, to install the requests package, use the following command:

pip install requests

To exit the virtual environment and return to your normal shell environment, use the following command:

deactivate


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


For Windows


cd C:\Users\YourUsername\Desktop\myproject

    Create the virtual environment by running the following command:

python -m venv myenv

This will create a new directory called "myenv" in your current directory, containing the files necessary to run a Python3 virtual environment.

    Activate the virtual environment by running the activate script in the "Scripts" subdirectory of your virtual environment. You can do this by typing:

myenv\Scripts\activate.bat

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Now to setup pre reqs

pip install pyaudio
pip install SpeechRecognition
pip install gtts
pip install openai
pip install textblob
python.exe -m pip install feedparser
python.exe -m pip install spellchecker
pip install pyenchant
pip install googletrans
pip install googletrans==4.0.0-rc1
pip install schedule
pip install datefinder
pip install dateparser
pip install num2words
pip install pygame
pip install beautifulsoup4
pip install pip install pyttsx3
pip install pyowm
pip install pip install wikipedia
pip install playsound
pip install pyaudio


You can try

pip install -r requirements.txt


Then

py runV26.py

or start.bat


https://www.youtube.com/watch?v=RAKpMYOlttA


V19 is a google cloud api key required version!!


start.bat stays refered to V18 until a api and may skip this version until a key is gained for experimental research!




Code

run.py

Code:
#
# (c) J~Net 2023
# jnt.club
#
# https://jnet.forumotion.com/t1976-a-perfect-ai-assistant#3046
#
# pip install pyaudio
# pip install SpeechRecognition
# pip install gtts
# pip install openai
# pip install textblob
# python.exe -m pip install feedparser
# python.exe -m pip install spellchecker
# pip install pyenchant
# pip install googletrans
# pip install googletrans==4.0.0-rc1
# pip install schedule
# pip install datefinder
# pip install dateparser
# pip install num2words
# pip install pygame
# pip install beautifulsoup4
# pip install pip install pyttsx3
# pip install pyowm
# pip install pip install wikipedia
# pip install playsound
# pip install pyaudio
# pip install pronouncing
#
#
import os
import time
import speech_recognition as sr
import subprocess
from gtts import gTTS
import openai
import datetime
import nltk
nltk.download('cmudict')
from textblob import TextBlob
import winsound
import pygame
import requests
from bs4 import BeautifulSoup
import feedparser
import random
import pyttsx3
import pyowm
import webbrowser
import wikipedia
from pygame import mixer
import signal
import sys
import enchant
import re
import bs4
from gtts import gTTS
from playsound import playsound
#from google.cloud import translate_v2 as translate
from googletrans import Translator
import threading
import schedule
import datefinder
import dateparser
from urllib.request import urlopen, Request
from num2words import num2words
import pronouncing
from nltk.corpus import cmudict
import json
import textwrap

api_key="KEY_HERE"

weatherapi_key="KEY_HERE"

city='Southampton, UK'

d=cmudict.dict()

def bible(said):
    # Remove the word "Bible" from the said variable
    keyword=said.lower().replace("bible", "").strip()

    # Search for the keyword in the Bible text file
    with open("bible.txt", "r") as file:
        verses=[]
        for line in file:
            if keyword in line.lower():
                verses.append(line.strip())

    # Print the results
    if verses:
        print(f"Here are the verses that contain the keyword '{keyword}':")
        text="\n".join(verses)
        paragraphs=textwrap.wrap(text, width=70)
        #engine=pyttsx3.init()
        for paragraph in paragraphs:
            print(paragraph)
            say(paragraph)
            #engine.runAndWait()
    else:
        print("Sorry I could not find any verses that contain the keyword")



# define a function to read a quote
def read_quote():
    # get the quote of the day from the web
    url="https://www.brainyquote.com/quote_of_the_day"
    headers={
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
    req=Request(url=url, headers=headers)
    page=urlopen(req)
    soup=BeautifulSoup(page, "html.parser")
    quote=soup.find("img", {"class": "p-qotd"})
    quote_text=quote["alt"]
    speak(quote_text)
   

# define a function to send an email
def send_email(receiver, subject, body):
    try:
        # use the Gmail API to send the email
        email=os.getenv("EMAIL_ADDRESS")
        password=os.getenv("EMAIL_PASSWORD")
        server=smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(email, password)
        message=f"Subject: {subject}\n\n{body}"
        server.sendmail(email, receiver, message)
        server.quit()
        return True
    except:
        return False   


def set_reminder(event, time_str):
    # parse the time string into a datetime object
    try:
        time=datetime.datetime.strptime(time_str, '%Y-%m-%d %I%p')
    except ValueError:
        print("Sorry, I couldn't understand the time format. Please use the format 'YYYY-MM-DD HH:MM:SS' in 24-hour format.")
        return
   
    # add minute 00 to the time
    time=time.replace(minute=00)

    # check if time is in the past
    if datetime.datetime.now() > time:
        print("Sorry, I can't set a reminder for the past.")
        return

    # create the reminder
    reminder=Reminder(event, time)
    reminder.schedule()
    print("Reminder set for", time.strftime('%Y-%m-%d %I:%M %p'), ":", event)


def handle_reminder(text):
    event=text.split("for", 1)[0].split("reminder", 1)[-1].strip()
    time_str=text.split("for", 1)[-1].strip()
    time_obj=dateparser.parse(time_str)

    if not time_obj:
        print("Sorry, I couldn't understand the time format. Please try again.")
        return

    set_reminder(event, time_obj)
   
def list_reminders():
    for job in schedule.jobs:
        print(job)


def say(text):
    tts=gTTS(text=text, lang='en')  # en
    tts.save('audio.mp3')
    play_mp3("audio.mp3")



#from playsound import playsound

#import getch

engine=pyttsx3.init()


lang='en'

openai.api_key=api_key
text=""

def calc(said):
    # extract operands and operator from spoken input
    match=re.match(r"what is (\d+) ([\+\-\*/]) (\d+)", said)
    if not match:
        return "Sorry, I didn't understand that. Please try again."
    a, op, b=match.groups()
   
    # perform calculation
    a=int(a)
    b=int(b)
    if op== '+':
        result=a + b
    elif op== '-':
        result=a - b
    elif op== '*':
        result=a * b
    elif op== '/':
        if b== 0:
            return "Sorry, division by zero is not allowed."
        result=a / b
   
    # format and return result
    return f"The result of {a} {op} {b} is {result}."


def play_mp3(file_path):
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(file_path)
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        continue
    pygame.mixer.music.stop()
    pygame.quit()
   
def who_made_you():
    #speak('I was made by Multimedia aka Jay @ J~Net & AI')
    engine.say("I was made by Multimedia aka Jay @ J~Net & AI")
    engine.runAndWait()
    text="I hope this answered your question"


def spell(said):
    pygame.mixer.init()
    said=said.replace("spell", "").strip() # remove "spell" from the text
    said=said.replace(" ", "") # remove any spaces in the text
    for letter in said:
        letter=letter.lower()
        if letter.isalpha():
            file_path=os.path.join(os.path.abspath(os.path.dirname(__file__)), "sounds", f"{letter}.mp3")
            print(letter)
            sound=pygame.mixer.Sound(file_path)
            sound.play()
            pygame.time.wait(int(sound.get_length() * 1000))
           
   
   
def open_youtube():
    text="opening youtube"
    webbrowser.open('www.youtube.com')


def exit_program():
    say(text)
    exit()


def greet():
    greetings=['hey there', 'hello', 'hi', 'Hai', 'hey']
    random_greeting=random.choice(greetings)
    text=(random_greeting)
    say(text)
    #speak("random_greeting")
    #engine.say(text)
  # engine.runAndWait()
   
def get_sound(word):
    url=f"https://api.datamuse.com/words?rel_rhy={word}"
    response=requests.get(url)
    return response

       
def rhyme(word):
    sounds=get_sound(word).text
    return sounds

       
def play_music():
    mixer.init()
    mixer.music.load(".\song.mp3")
    mixer.music.set_volume(0.5)
    mixer.music.play()

def speak(audio_string):
    audio_string=str(audio_string)
    audio_string=audio_string.replace(' ', '_')
    audio_string=audio_string.lower()
    audio_file=f'{audio_string}.mp3'
    winsound.PlaySound(audio_file, winsound.SND_FILENAME)
   

def tell_joke():
    jokes=[
        "Why was the math book sad? Because it had too many problems.",
        "Why don’t scientists trust atoms? Because they make up everything.",
        "Why did the scarecrow win an award? Because he was outstanding in his field.",
        "Why did the tomato turn red? Because it saw the salad dressing!",
        "Why did the cookie go to the doctor? Because it felt crummy.",
        "Why did the belt go to jail? For holding up the pants!",
        "Why do fish live in saltwater? Because pepper water makes them sneeze.",
        "Why do we tell actors to “break a leg?” Because every play has a cast.",
        "Why did the banana go to the doctor? Because it wasn’t peeling well.",
        "What do you call a pile of cats? A meowtain.",
    ]
    joke=random.choice(jokes)
    engine.say(joke)
    engine.runAndWait()
    print(joke)   

def get_weather(weatherapi_key, city):
    owm=pyowm.OWM(weatherapi_key)
    mgr=owm.weather_manager()
    observation=mgr.weather_at_place(city)
    weather=observation.weather
    status=weather.detailed_status
    temperature=weather.temperature('celsius')['temp']
    humidity=weather.humidity
    wind=weather.wind()['speed']
    text="what else can I help you with"
    return f"The weather in {city} is {status} with a temperature of {temperature} degrees Celsius, humidity at {humidity} percent and wind speed at {wind} meter per second."

def get_news_headlines():
    url='https://www.bbc.com/news'
    response=requests.get(url)
    soup=BeautifulSoup(response.text, 'html.parser')
    headlines=[]
    for article in soup.find_all('div', class_='gs-c-promo-body gel-1/2@xs'):
        headline=article.find('h3', class_='gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text')
        if headline is not None:
            headlines.append(headline.text)
    return headlines



def get_context(text):
    # Detect time
    if "time" in text:
        now=datetime.datetime.now()
        return f"The time is {now.strftime('%I:%M %p')}"

def wikipedia_search(said):
    summary=""
    query=said.lower().replace("search ", "").replace("find ", "").replace("wiki ", "").strip()
    try:
        results=wikipedia.search(query)
        if results:
            summary=wikipedia.summary(results[0], sentences=2)
           
            text=f"Here's what I found on {results[0]}: {summary}"
            print(text)
        else:
            text="Sorry, I couldn't find anything on that topic."
            print(text)
    except wikipedia.exceptions.DisambiguationError as e:
        options=e.options[:5]
        options_text= ', '.join(options)
        text=f"There are multiple options, please choose one of the following: {options_text}"
        print(text)
    except wikipedia.exceptions.PageError as e:
        text="Sorry, I couldn't find any results for that search."
        print(text)
    time.sleep(2) # add a delay of 2 seconds
    say(summary)
    text="What else can I help you with?"
    #return text
   
def translate(text, target_lang):
    translator=Translator()
    if text.isnumeric():
        text=num2words(text)
    translated=translator.translate(text, dest=target_lang)
    return translated.text 

def set_timer(duration):
    # Start a new thread for the timer
    def countdown():
        time.sleep(duration * 60)
        print("Timer ended!")
        play_mp3("sounds/timer-sound.mp3")

    timer_thread=threading.Thread(target=countdown)
    timer_thread.start()
    #text=f"Timer Set for {duration} minutes."
    print(f"Timer set for {duration} minutes.")

   
def get_audio():
    r=sr.Recognizer()
    with sr.Microphone() as source:
        audio=r.listen(source)
        said=""
        text=None

        try:
            said=r.recognize_google(audio)
            print(said)

            text="I'm sorry, I didn't catch that. Could you please repeat?"

         
            if "what time is it" in said or "what is the time" in said or "tell me the time" in said:
                current_time=time.strftime("%I:%M %p")
                print(f"The time is {current_time}")
                text=f"The time is {current_time}"
               
            elif "search" in said or "find" in said or "wiki" in said:
                wikipedia_search(said)
                text="What else can I help you with?"

            elif "Bible" in said or "bible" in said:
                out=bible(said)
                print(out)
                text=out
                #text="What else can I help you with?"
               
            elif "what rhymes with" in said:
                word=said.replace("what rhymes with", "").strip()
                rhyme_word=rhyme(word)
                text=rhyme_word
                print(rhyme_word)


               
            elif "quote of the day" in said or "give me the quote of the day" in said:
                wikipedia_search(said)
                quote=read_quote()
                text=quote
                print(quote)

            elif "translate" in said.lower():
                words=said.lower().split()
                target_lang="fr" # fallback language
                for i in range(len(words)):
                    if words[i] == "to" and i < len(words) - 1:
                        target_lang=words[i+1]
                        break
                phrase=" ".join(words[1:i])
                translation=translate(phrase, target_lang)
                print(f"{phrase} translated to {target_lang}: {translation}")
                text=translation

               
            elif "-" in said or "+" in said or "/" in said or "x" in said:
                expression=said.split("calculate", 1)[-1].strip()
                expression=expression.replace("x", "*") # replace 'x' with '*' for multiplication
                if any(op in expression for op in ['+', '-', '*', '/']):
                    try:
                        result=calc(expression)
                        text=f"The answer is {result}. Anything else I can help with?"
                    except:
                        text="Sorry, I couldn't calculate that. Please try again."
                else:
                    text="Sorry, I couldn't understand the math expression. Please try again."


            elif "set timer for" in said.lower():
                duration=int(next((word for word in said.split() if word.isdigit()), None))
                if duration:
                    threading.Thread(target=set_timer, args=[duration]).start()   
                    text=f"timer set for {duration} minutes"
           
            elif "play music" in said or "start music" in said:
                #play_music
                play_mp3("song.mp3")           
               
            elif "open Youtube" in said or "open browser" in said:
                #play_music
                open_youtube()
                #webbrowser.open('www.youtube.com')
               
            elif "spell" in said or "how do i spell" in said:
                spell(said)
                text="Is there anything else I can spell for you?"

            elif "repeat that" in said or "say again" in said:
                play_mp3("welcome1.mp3")
               
            elif "say" in said or "simon says" in said:
                said=said.replace("say", "").replace("Simon says", "")
                say(said)
                text="Is there anything else I can say for you?"
               
            elif "set a reminder" in said:
                event=said.split("for",1)[0].split("reminder",1)[-1].strip()
                time_str=said.split("for",1)[-1].strip()
                try:
                    time_obj=datetime.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
                    set_reminder(event, time_obj)
                    text=f"Reminder set for {event} on {time_str}. Anything else I can help with?"
                except ValueError:
                    text="Sorry, I couldn't understand the time format. Please use the format 'YYYY-MM-DD HH:MM:SS'."
                   
            elif "list schedule" in said:
                schedule=get_schedule()
                if schedule:
                    text="Here's your schedule:\n"
                    for event in schedule:
                        text += f"- {event['event']} on {event['time'].strftime('%Y-%m-%d %H:%M:%S')}\n"
                else:
                    text="You don't have any events in your schedule."

           
            elif "who made you" in said or "who created you" in said:
                text="I hope this answered your question"
                who_made_you()
           
            elif "tell me a joke" in said or "make me laugh" in said:
                #tell_joke()
                joke=tell_joke()
                text=joke
                #print(joke)
                speak(joke)
           
            elif "hello" in said or "hi" in said:
                #tell_joke()
                fgretin=greet()   
                text=fgretin
                #speak(text)
               

            elif "what date is it" in said or "what is the date" in said:
                current_date=datetime.datetime.now().strftime("%d %B %Y")
                print(f"The date is {current_date}")
                text=f"The date is {current_date}"
               
            elif "stop" in said or "bye" in said or "goodbye" in said:
                exit_program()
               
            elif "what is the weather" in said or "weather" in said:
                response=get_weather(weatherapi_key, city)
                print(response)
                #speak(response)
                text=response

               
            elif "news" in said:
                news_url="https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en"
                news_feed=feedparser.parse(news_url)
                headlines=[entry.get("title", "") for entry in news_feed["entries"]]
                if len(headlines) > 0:
                    text="Here are the latest news headlines:"
                    for headline in headlines:
                        text += f" {headline}."
                else:
                    text="Sorry, I could not fetch the news at this time."

            if text:
                print(text)
                speech=gTTS(text=text, lang=lang, slow=False, tld="com.au")
                speech.save("welcome1.mp3")
                play_mp3("welcome1.mp3")
                   
        except sr.UnknownValueError:
            print("Google Speech Recognition could not understand audio")
        except sr.RequestError as e:
            print("Could not request results from Google Speech Recognition service; {0}".format(e))
        except openai.error.RateLimitError:
            print("You exceeded your current quota, please check your plan and billing details. "
                  "Wait for 10 minutes and try again.")
            #time.sleep(10*60)

    return said, text

print("Listening")

while True:
    said, text=get_audio()
    if text is not None and "stop" in said:
        print("Bye for now!")
        break
jamied_uk
jamied_uk
Admin

Posts : 2951
Join date : 2010-05-09
Age : 41
Location : UK

https://jnet.sytes.net

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum