Advertisement
mikael_upb

Python AI Assistant

May 8th, 2022
16,109
3
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.95 KB | None | 3 0
  1. from datetime import datetime
  2. from logging.config import listen
  3. import speech_recognition as sr
  4. import pyttsx3
  5. import webbrowser
  6. import wikipedia
  7. import wolframalpha
  8.  
  9. # Speech engine initialisation
  10. engine = pyttsx3.init()
  11. voices = engine.getProperty('voices')
  12. engine.setProperty('voice', voices[0].id) # 0 = male, 1 = female
  13. activationWord = 'computer' # Single word
  14.  
  15. # Configure browser
  16. # Set the path
  17. chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
  18. webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
  19.  
  20. # Wolfram Alpha client
  21. appId = '5R49J7-J888YX9J2V'
  22. wolframClient = wolframalpha.Client(appId)
  23.  
  24. def speak(text, rate = 120):
  25.     engine.setProperty('rate', rate)
  26.     engine.say(text)
  27.     engine.runAndWait()
  28.  
  29. def parseCommand():
  30.     listener = sr.Recognizer()
  31.     print('Listening for a command')
  32.  
  33.     with sr.Microphone() as source:
  34.         listener.pause_threshold = 2
  35.         input_speech = listener.listen(source)
  36.  
  37.     try:
  38.         print('Recognizing speech...')
  39.         query = listener.recognize_google(input_speech, language='en_gb')
  40.         print(f'The input speech was: {query}')
  41.     except Exception as exception:
  42.         print('I did not quite catch that')
  43.         speak('I did not quite catch that')
  44.         print(exception)
  45.         return 'None'
  46.  
  47.     return query
  48.  
  49. def search_wikipedia(query = ''):
  50.     searchResults = wikipedia.search(query)
  51.     if not searchResults:
  52.         print('No wikipedia result')
  53.         return 'No result received'
  54.     try:
  55.         wikiPage = wikipedia.page(searchResults[0])
  56.     except wikipedia.DisambiguationError as error:
  57.         wikiPage = wikipedia.page(error.options[0])
  58.     print(wikiPage.title)
  59.     wikiSummary = str(wikiPage.summary)
  60.     return wikiSummary
  61.  
  62. def listOrDict(var):
  63.     if isinstance(var, list):
  64.         return var[0]['plaintext']
  65.     else:
  66.         return var['plaintext']
  67.  
  68. def search_wolframAlpha(query = ''):
  69.     response = wolframClient.query(query)
  70.  
  71.     # @success: Wolfram Alpha was able to resolve the query
  72.     # @numpods: Number of results returned
  73.     # pod: List of results. This can also contain subpods
  74.     if response['@success'] == 'false':
  75.         return 'Could not compute'
  76.    
  77.     # Query resolved
  78.     else:
  79.         result = ''
  80.         # Question
  81.         pod0 = response['pod'][0]
  82.         pod1 = response['pod'][1]
  83.         # May contain the answer, has the highest confidence value
  84.         # if it's primary, or has the title of result or definition, then it's the official result
  85.         if (('result') in pod1['@title'].lower()) or (pod1.get('@primary', 'false') == 'true') or ('definition' in pod1['@title'].lower()):
  86.             # Get the result
  87.             result = listOrDict(pod1['subpod'])
  88.             # Remove the bracketed section
  89.             return result.split('(')[0]
  90.         else:
  91.             question = listOrDict(pod0['subpod'])
  92.             # Remove the bracketed section
  93.             return question.split('(')[0]
  94.             # Search wikipedia instead
  95.             speak('Computation failed. Querying universal databank.')
  96.             return search_wikipedia(question)
  97.  
  98.  
  99.  
  100. # Main loop
  101. if __name__ == '__main__':
  102.     speak('All systems nominal.')
  103.  
  104.     while True:
  105.         # Parse as a list
  106.         query = parseCommand().lower().split()
  107.  
  108.         if query[0] == activationWord:
  109.             query.pop(0)
  110.  
  111.             # List commands
  112.             if query[0] == 'say':
  113.                 if 'hello' in query:
  114.                     speak('Greetings, all.')
  115.                 else:
  116.                     query.pop(0) # Remove say
  117.                     speech = ' '.join(query)
  118.                     speak(speech)
  119.  
  120.             # Navigation
  121.             if query[0] == 'go' and query[1] == 'to':
  122.                 speak('Opening...')
  123.                 query = ' '.join(query[2:])
  124.                 webbrowser.get('chrome').open_new(query)
  125.  
  126.             # Wikipedia
  127.             if query[0] == 'wikipedia':
  128.                 query = ' '.join(query[1:])
  129.                 speak('Querying the universal databank.')
  130.                 speak(search_wikipedia(query))
  131.                
  132.             # Wolfram Alpha
  133.             if query[0] == 'compute' or query[0] == 'computer':
  134.                 query = ' '.join(query[1:])
  135.                 speak('Computing')
  136.                 try:
  137.                     result = search_wolframAlpha(query)
  138.                     speak(result)
  139.                 except:
  140.                     speak('Unable to compute.')
  141.  
  142.             # Note taking
  143.             if query[0] == 'log':
  144.                 speak('Ready to record your note')
  145.                 newNote = parseCommand().lower()
  146.                 now = datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
  147.                 with open('note_%s.txt' % now, 'w') as newFile:
  148.                     newFile.write(newNote)
  149.                 speak('Note written')
  150.  
  151.             if query[0] == 'exit':
  152.                 speak('Goodbye')
  153.                 break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement