· 4 years ago · Mar 24, 2021, 05:10 AM
1import subprocess
2import wolframalpha
3import pyttsx3
4import tkinter
5import json
6import random
7import operator
8import speech_recognition as sr
9import datetime
10import wikipedia
11import webbrowser
12import os
13import winshell
14import pyjokes
15import feedparser
16import smtplib
17import ctypes
18import time
19import requests
20import shutil
21from twilio.rest import Client
22from clint.textui import progress
23from ecapture import ecapture as ec
24from bs4 import BeautifulSoup
25import win32com.client as wincl
26from urllib.request import urlopen
27from telegram.ext import updater, commandhandler, messagehandler, filters
28import ftransc.core as ft
29import logging
30logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
31
32def start(bot, context):
33 context.message.reply_text("I'm a ChatBot, please talk to me!")
34# We always like to be polite (and have a very simple feature to see if the ChatBot is alive)
35def hello(bot, update):
36 update.message.reply_text(
37 'Hello {}'.format(update.message.from_user.first_name))
38# A bit of help does not hurt
39def help(bot, context):
40 update.message.reply_text(
41 'THis is a chatbot, it transcribes your voice messages \n' +
42 'It also responds to a few commands' +
43 '/start restarts the ChatBot' +
44 '/help prints this help \n' +
45 '/hello triggers an hello message'
46 )
47
48
49# transcribe a voice note to text
50def transcribe_voice(bot, context):
51 duration = context.message.voice.duration
52 logger.info('transcribe_voice. Message duration: ' + duration)
53
54 # Fetch voice message
55 voice = bot.getFile(context.message.voice.file_id)
56
57 # Transcode the voice message from audio/x-opus+ogg to audio/x-wav
58 # One should use a unique in-memory file, but I went for a quick solution for demo purposes
59 ft.transcode(voice.download('file.ogg'), 'wav')
60
61 # extract voice from the audio file
62 r = sr.Recognizer()
63 with sr.WavFile('file.wav') as source:
64 # r.adjust_for_ambient_noise(source) # Optional
65 audio = r.record(source)
66
67 # Convert voice to text
68 try:
69 txt = r.recognize_google(audio)
70 logger.info(txt)
71 except sr.UnknownValueError:
72 logger.warn('Speech to Text could not understand audio')
73 except sr.RequestError as e:
74 logger.warn('Could not request results from Speech to Text service; {0}'.format(e))
75
76 # return the voice message in text format
77 context.message.reply_text(txt)
78
79def speak(audio):
80 engine = pyttsx3.init()
81 engine.say(audio)
82 engine.runAndWait()
83
84
85def wishMe():
86 hour = int(datetime.datetime.now().hour)
87 if hour >= 0 and hour < 12:
88 speak("Good Morning Mr.fahad !")
89
90 elif hour >= 12 and hour < 18:
91 speak("Good Afternoon Mr.fahad !")
92
93 else:
94 speak("Good Evening Mr.fahad !")
95
96 assname = ("Jarvis")
97 speak("I am your Assistant")
98 speak(assname)
99
100
101def usrname():
102 #speak("What should i call you sir")
103 #uname = takeCommand()
104 #speak("Welcome Mister")
105 #speak(uname)
106 #columns = shutil.get_terminal_size().columns
107
108 print("#####################")
109 print("Welcome Mr.fahad")
110 print("#####################")
111
112 speak("How can i Help you, Sir")
113
114
115def takeCommand():
116 r = sr.Recognizer()
117
118 with sr.Microphone() as source:
119
120 print("Listening...")
121 audio = r.listen(source)
122
123 try:
124 print("Recognizing...")
125 query = r.recognize_google(audio, language='en-in')
126 print(f"User said: {query}\n")
127
128 except Exception as e:
129 print(e)
130 print("Unable to Recognize your voice.")
131 return "None"
132
133 return query
134
135
136def sendEmail(to, content):
137 server = smtplib.SMTP('smtp.gmail.com', 587)
138 server.ehlo()
139 server.starttls()
140
141 # Enable low security in gmail
142 server.login('af4x305@gmail.com', 'f2w66266')
143 server.sendmail('af4x305@gmail.com', to, content)
144 server.close()
145
146
147if __name__ == '__main__':
148 clear = lambda: os.system('cls')
149
150 # This Function will clean any
151 # command before execution of this python file
152 clear()
153 wishMe()
154 usrname()
155
156 while True:
157
158 query = takeCommand().lower()
159
160 # All the commands said by user will be
161 # stored here in 'query' and will be
162 # converted to lower case for easily
163 # recognition of command
164 if 'wikipedia' in query:
165 speak('Searching Wikipedia...')
166 query = query.replace("wikipedia", "")
167 results = wikipedia.summary(query, sentences=3)
168 speak("According to Wikipedia")
169 print(results)
170 speak(results)
171
172 elif 'open youtube' in query:
173 speak('yes sir')
174 webbrowser.open("youtube.com")
175
176 elif 'open google' in query:
177 speak('here it is sir')
178 webbrowser.open("google.com")
179
180 elif 'open stackoverflow' in query:
181 webbrowser.open("stackoverflow.com")
182
183 elif 'play music' in query or "play song" in query:
184 # music_dir = "G:\\Song"
185 music_dir = "C:\\Users\\GAURAV\\Music"
186 songs = os.listdir(music_dir)
187 print(songs)
188 random = os.startfile(os.path.join(music_dir, songs[1]))
189
190 elif 'what is the time' in query:
191 strTime = datetime.datetime.now().strftime("%H:%M:%S")
192 speak(f"Sir, the time is {strTime}")
193
194 elif 'open opera' in query:
195 codePath = r"C:\\Users\\GAURAV\\AppData\\Local\\Programs\\Opera\\launcher.exe"
196 os.startfile(codePath)
197
198 elif 'email' in query:
199 try:
200 speak("What should I say?")
201 content = takeCommand()
202 to = "almoteri0@gmail.com"
203 sendEmail(to, content)
204 speak("Email has been sent !")
205 except Exception as e:
206 print(e)
207 speak("I am not able to send this email")
208
209 elif 'send a mail' in query:
210 try:
211 speak("What should I say?")
212 content = takeCommand()
213 speak("whome should i send")
214 to = input()
215 sendEmail(to, content)
216 speak("Email has been sent !")
217 except Exception as e:
218 print(e)
219 speak("I am not able to send this email")
220
221 elif 'how are you' in query:
222 speak("I am fine, Thank you")
223 speak("How are you, Sir")
224
225 elif 'fine' in query:
226 speak("It's good to know that your fine")
227
228 elif "change my name to" in query:
229 query = query.replace("change my name to", "")
230 assname = query
231
232 elif "change name" in query:
233 speak("What would you like to call me, Sir ")
234 assname = takeCommand()
235 speak("Thanks for naming me")
236
237 elif "what's your name" in query or "What is your name" in query:
238 speak("My friends call me")
239 speak(assname)
240 print("My friends call me", assname)
241
242 elif 'exit' in query:
243 speak("Thanks for giving me your time")
244 exit()
245
246 elif "who made you" in query or "who created you" in query:
247 speak("I have been created by the powerfull Fahad.")
248
249 elif 'give me a joke' in query:
250 speak(pyjokes.get_joke())
251
252 elif "calculate" in query:
253
254 app_id = "Wolframalpha api id"
255 client = wolframalpha.Client(app_id)
256 indx = query.lower().split().index('calculate')
257 query = query.split()[indx + 1:]
258 res = client.query(' '.join(query))
259 answer = next(res.results).text
260 print("The answer is " + answer)
261 speak("The answer is " + answer)
262
263 elif 'search' in query or 'play' in query:
264
265 query = query.replace("search", "")
266 query = query.replace("play", "")
267 webbrowser.open(query)
268
269 elif "who i am" in query:
270 speak("If you talk then definately your human.")
271
272 elif "why you came to world" in query:
273 speak("Thanks to Gaurav. further It's a secret")
274
275 elif 'power point presentation' in query:
276 speak("opening Power Point presentation")
277 power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
278 os.startfile(power)
279
280 elif 'is love' in query:
281 speak("It is 7th sense that destroy all other senses")
282
283 elif "who are you" in query:
284 speak("I am your virtual assistant created by the powerfull Fahad")
285
286 elif 'reason for you' in query:
287 speak("I was created as a Minor project by Mister Fahad ")
288
289 elif 'change background' in query:
290 ctypes.windll.user32.SystemParametersInfoW(20,
291 0,
292 "Location of wallpaper",
293 0)
294 speak("Background changed succesfully")
295
296 elif 'open bluestack' in query:
297 appli = r"C:\\ProgramData\\BlueStacks\\Client\\Bluestacks.exe"
298 os.startfile(appli)
299
300 elif 'news' in query:
301
302 try:
303 jsonObj = urlopen(
304 '''https://newsapi.org / v1 / articles?source = the-times-of-india&sortBy = top&apiKey =\\times of India Api key\\''')
305 data = json.load(jsonObj)
306 i = 1
307
308 speak('here are some top news from the times of india')
309 print('''=============== TIMES OF INDIA ============''' + '\n')
310
311 for item in data['articles']:
312 print(str(i) + '. ' + item['title'] + '\n')
313 print(item['description'] + '\n')
314 speak(str(i) + '. ' + item['title'] + '\n')
315 i += 1
316 except Exception as e:
317
318 print(str(e))
319
320
321 elif 'i am out' in query:
322 speak("locking the device")
323 ctypes.windll.user32.LockWorkStation()
324
325 elif 'shutdown the system' in query:
326 speak("Hold On a Sec ! Your system is on its way to shut down")
327 subprocess.call('shutdown / p /f')
328
329 elif 'empty recycle bin' in query:
330 winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
331 speak("Recycle Bin Recycled")
332
333 elif "don't listen" in query or "stop listening" in query:
334 speak("for how much time you want to stop jarvis from listening commands")
335 a = int(takeCommand())
336 time.sleep(a)
337 print(a)
338
339 elif "where is" in query:
340 query = query.replace("where is", "")
341 location = query
342 speak("User asked to Locate")
343 speak(location)
344 webbrowser.open("https://www.google.nl/maps/place/" + location + "")
345
346 elif "camera" in query or "take a photo" in query:
347 ec.capture(0, "Jarvis Camera ", "img.jpg")
348
349 elif "restart" in query:
350 subprocess.call(["shutdown", "/r"])
351
352 elif "hibernate" in query or "sleep" in query:
353 speak("Hibernating")
354 subprocess.call("shutdown / h")
355
356 elif "log off" in query or "sign out" in query:
357 speak("Make sure all the application are closed before sign-out")
358 time.sleep(5)
359 subprocess.call(["shutdown", "/l"])
360
361 elif "write a note" in query:
362 speak("What should i write, sir")
363 note = takeCommand()
364 file = open('jarvis.txt', 'w')
365 speak("Sir, Should i include date and time")
366 snfm = takeCommand()
367 if 'yes' in snfm or 'sure' in snfm:
368 strTime = datetime.datetime.now().strftime("% H:% M:% S")
369 file.write(strTime)
370 file.write(" :- ")
371 file.write(note)
372 else:
373 file.write(note)
374
375 elif "show note" in query:
376 speak("Showing Notes")
377 file = open("jarvis.txt", "r")
378 print(file.read())
379 speak(file.read(6))
380
381 elif "update assistant" in query:
382 speak("After downloading file please replace this file with the downloaded one")
383 url = '# url after uploading file'
384 r = requests.get(url, stream=True)
385
386 with open("Voice.py", "wb") as Pypdf:
387
388 total_length = int(r.headers.get('content-length'))
389
390 for ch in progress.bar(r.iter_content(chunk_size=2391975),
391 expected_size=(total_length / 1024) + 1):
392 if ch:
393 Pypdf.write(ch)
394
395 # NPPR9-FWDCX-D2C8J-H872K-2YT43
396 elif "jarvis" in query:
397
398 speak("yes sir")
399
400 elif "weather" in query:
401
402 # Google Open weather website
403 # to get API of Open weather
404 api_key = "Api key"
405 base_url = "http://api.openweathermap.org/data/2.5/ weather?"
406 speak(" City name ")
407 print("City name : ")
408 city_name = takeCommand()
409 complete_url = base_url + "appid =" + api_key + "&q =" + city_name
410 response = requests.get(complete_url)
411 x = response.json()
412
413 if x["cod"] != "404":
414 y = x["main"]
415 current_temperature = y["temp"]
416 current_pressure = y["pressure"]
417 current_humidiy = y["humidity"]
418 z = x["weather"]
419 weather_description = z[0]["description"]
420 print(" Temperature (in kelvin unit) = " + str(
421 current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(
422 current_pressure) + "\n humidity (in percentage) = " + str(
423 current_humidiy) + "\n description = " + str(weather_description))
424
425 else:
426 speak(" City Not Found ")
427
428 elif "send message " in query:
429 # You need to create an account on Twilio to use this service
430 account_sid = 'Account Sid key'
431 auth_token = 'Auth token'
432 client = Client(account_sid, auth_token)
433
434 message = client.messages \
435 .create(
436 body=takeCommand(),
437 from_='Sender No',
438 to='Receiver No'
439 )
440
441 print(message.sid)
442
443 elif "wikipedia" in query:
444 webbrowser.open("wikipedia.com")
445
446 elif "Good Morning" in query:
447 speak("A warm" + query)
448 speak("How are you Mister")
449 speak(assname)
450
451 # most asked question from google Assistant
452 elif "will you be my gf" in query or "will you be my bf" in query:
453 speak("I'm not sure about, may be you should give me some time")
454
455 elif "how are you" in query:
456 speak("I'm fine, glad you me that")
457
458 elif "i love you" in query:
459 speak("It's hard to understand")
460
461 elif "what is" in query or "who is" in query:
462
463 # Use the same API key
464 # that we have generated earlier
465 client = wolframalpha.Client("API_ID")
466 res = client.query(query)
467
468 try:
469 print(next(res.results).text)
470 speak(next(res.results).text)
471 except StopIteration:
472 print("No results")
473
474 # Instantiate Updater
475 updater = updater('1774265112:AAEfL8sBAr43BFRJ63TB3g1GCxbIa5AAOjI')
476
477 # Attach command handlers to dispatcher
478 updater.dispatcher.add_handler(CommandHandler('hello', hello))
479 updater.dispatcher.add_handler(CommandHandler('help', help))
480 updater.dispatcher.add_handler(CommandHandler('start', start))
481
482 # Attach voiemessage handler to dispatcher. Note the filter as we ovly want the voice mesages to be transcribed
483 updater.dispatcher.add_handler(MessageHandler(Filters.voice, transcribe_voice))
484
485 # Start polling for events from the message queue.
486 updater.start_polling()
487 updater.idle()