0% found this document useful (0 votes)
31 views

Complete Code

This Python code defines functions for natural language processing tasks including text-to-speech, speech-to-text, email composition and sending, contact list management, email inspection and parsing, and sanitization of email subjects and filtering of links. The functions work together to enable an intelligent voice assistant to communicate with a user via speech, compose and send emails on their behalf, and inspect email contents by reading them aloud.

Uploaded by

akvakarthik2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Complete Code

This Python code defines functions for natural language processing tasks including text-to-speech, speech-to-text, email composition and sending, contact list management, email inspection and parsing, and sanitization of email subjects and filtering of links. The functions work together to enable an intelligent voice assistant to communicate with a user via speech, compose and send emails on their behalf, and inspect email contents by reading them aloud.

Uploaded by

akvakarthik2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

In [1]:

from User_credentials import *


import pyttsx3 as tts
from speech_recognition import *
from smtplib import *
from ssl import *
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from contact_list import *
from word2number import w2n
import inflect as inf
from imaplib import *
from email.header import decode_header
from email import *
import os
import re
import unidecode

In [2]:
def Text_to_speech(content):
engine = tts.init()
#engine.setProperty('rate', 580)
engine.say(content)
engine.runAndWait()
return

In [3]: def Speech_to_text():


recogniser = Recognizer()
while(1):
with Microphone() as access_to_system_mic:
recogniser.energy_threshold = 385
recogniser.adjust_for_ambient_noise(access_to_system_mic,durati
try:
audio = recogniser.listen(access_to_system_mic,timeout=15,p
text = recogniser.recognize_google(audio)
return(text)
except UnknownValueError:
print('Apologies!!! could not able to hear what you said. P
Text_to_speech('Apologies!!! could not able to hear what yo
except WaitTimeoutError:
print('Apologies!!! could not able to hear what you said. P
Text_to_speech('Apologies!!! could not able to hear what yo
except RequestError as e:
print("Please make sure that you are connected to the Inter
Text_to_speech("Please make sure that you are connected to

In [4]:
def Compose_email(recipients_Email_Id,subject,body):
print('Sending the Email, please wait.')
Text_to_speech('Sending the Email, please wait.')
message = MIMEMultipart()
message['From'] = sender_Email_Id
if(len(recipients_Email_Id) > 1):
message['To'] = ' ,'.join(recipients_Email_Id)
else:
message['To'] = ' '.join(recipients_Email_Id)
message['Subject'] = subject
message.attach(MIMEText(body,'plain'))
context = create_default_context()
try:
with SMTP_SSL('smtp.gmail.com',465,context = context) as server:
server.login(sender_Email_Id,sender_AppKey)
print('success')
server.sendmail(sender_Email_Id,recipients_Email_Id,message.as_
print('Email Sent Successfully!!!')
Text_to_speech('Email Sent Successfully')
print("Sir, I'm done with this task")
Text_to_speech("Sir, I'm done with this task")
return
except:
print('Error encountered while sending the email!!!\nPlease check t
Text_to_speech('Error encountered while sending the email. Please c
return

In [5]:
def contact_list():

recipient_emails = []
print('Sir, once please listen to the contact list')
Text_to_speech('Sir, once please listen to the contact list')
for i in contacts:
print(f'{i}:{contacts[i]}')
Text_to_speech(f'{i}:{contacts[i]}')

while(1):
print('Sir, please speak out the recipients you want to include (e.
Text_to_speech('Sir, please speak out the recipients you want to in
recipients_input = Speech_to_text().lower().split(' and ')
for recipient_input in recipients_input:
for j in contact_lst:
if any(alias.lower() in recipient_input for alias in [j] +
recipient_emails.append(contacts[j])
break

if(len(recipient_emails) >= 1):


return recipient_emails
else:
print('Sir, I request you to please repeat the process again as
Text_to_speech('Sir, I request you to please repeat the process

In [6]:
def sending_email():
recipients = contact_list()
Text_to_speech('Please speak the subject of the Email')
print('Please speak the subject of the Email:')
subject = Speech_to_text()
print(subject)
Text_to_speech('Please speak the body of the Email')
print('Please speak the body of the Email')
body = Speech_to_text()
print(body)
Compose_email(recipients,subject,body)

In [7]:
def sanitize_gmail_subject(subject):

# Convert byte input to string if needed


if isinstance(subject, bytes):
subject = subject.decode('utf-8', errors='ignore')

# Remove emojis and convert special characters to ASCII


sanitized_subject = unidecode.unidecode(subject)

# Remove any remaining special characters


sanitized_subject = ''.join(e for e in sanitized_subject if (e.isalnum(

# Replace spaces with underscores and convert to lowercase


# sanitized_subject = sanitized_subject.replace(' ', '_').lower()

return sanitized_subject

In [8]: def filter_links(text):


"""
Filter out links from the given text.
Returns a tuple containing the filtered text and a flag indicating if l
"""
# Replace links with an empty string using a regular expression
url_pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%
filtered_text = re.sub(url_pattern, '', text)

# Check if links were present


links_present = filtered_text != text

return filtered_text, links_present

In [9]: def inspect_email():

mail_obj = IMAP4_SSL("imap.gmail.com")
mail_obj.login(sender_Email_Id, sender_AppKey)

Text_to_speech('Sir, please listen to the number which is associated wi


print('Number 1: Inbox')
Text_to_speech('Number 1: Inbox')
print('Number 2: Starred')
Text_to_speech('Number 2: Starred')
print('Number 3: Important')
Text_to_speech('Number 3: Important')
print('Number 4: Sent')
Text_to_speech('Number 4: Sent')
print('Number 5: Drafts')
Text_to_speech('Number 5: Drafts')
print('Number 6: Spam')
Text_to_speech('Number 6: Spam')
print('Number 7: Bin')
Text_to_speech('Number 7: Bin')
print('Sir, please select the number which is associated with the label
Text_to_speech('Sir, please select the number which is associated with
user_choice = Speech_to_text()
print(user_choice)
if('number 1' in user_choice or 'number one' in user_choice or 'number
status_of_selection_state, messages = mail_obj.select('Inbox')
elif('number 2' in user_choice or 'number tu' in user_choice or 'number
status_of_selection_state, messages = mail_obj.select('[Gmail]/Star
elif('number 3' in user_choice or 'number three' in user_choice):
status_of_selection_state, messages = mail_obj.select('[Gmail]/Impo
elif('number 4' in user_choice or 'number four' in user_choice or 'numb
status_of_selection_state, messages = mail_obj.select('"[Gmail]/Sen
elif('number 5' in user_choice or 'number five' in user_choice):
status_of_selection_state, messages = mail_obj.select('[Gmail]/Draf
elif('number 6' in user_choice or 'number six' in user_choice):
status_of_selection_state, messages = mail_obj.select('[Gmail]/Spam
elif('number 7' in user_choice or 'number seven' in user_choice):
status_of_selection_state, messages = mail_obj.select('[Gmail]/Tras
else:
print('As the user choice is invalid, selecting the inbox label as
Text_to_speech('As the user choice is invalid, selecting the inbox
status_of_selection_state, messages = mail_obj.select('inbox')
if status_of_selection_state != 'OK':
print(f"Failed to select mailbox. Status: {status_of_selection_stat
Text_to_speech("Failed to select mailbox.")
return
status_of_searching_mailbox, email_charset = mail_obj.search(None, 'ALL
email_byte_data = email_charset[0].split()
first_five_latest_email_byte_data = email_byte_data[-5:]

for email_ids in reversed(first_five_latest_email_byte_data):


status_of_fetch_operation_on_email_ids, msg_data = mail_obj.fetch(e
raw_byte_format_of_fetched_data = msg_data[0][1]
email_content_in_string_obj_format = message_from_bytes(raw_byte_fo

subject = decode_header(email_content_in_string_obj_format['Subject

if email_content_in_string_obj_format.is_multipart():
print("Subject: ", sanitize_gmail_subject(subject))
Text_to_speech(f"Subject: {sanitize_gmail_subject(subject)}")
print(f"From: {decode_header(email_content_in_string_obj_format
Text_to_speech(f"From: {decode_header(email_content_in_string_o
print(f"Date: {decode_header(email_content_in_string_obj_format
Text_to_speech(f"Date: {decode_header(email_content_in_string_o
for part in email_content_in_string_obj_format.walk():
content_disposition = part.get_content_disposition()

if content_disposition is not None and ('attachment' in con


filename = part.get_filename()
if filename:
filename = decode_header(filename)[0][0]
if isinstance(filename, bytes):
filename = filename.decode('utf-8')
output_location = os.path.join(default_path_to_save
os.makedirs(os.path.dirname(output_location), exist
with open(output_location, 'wb') as attachment_file
attachment_file.write(part.get_payload(decode=T
print(f'Sir, I encountered an attachment named "{fi
Text_to_speech(f'Sir, I encountered an attachment n
print("/" * 150)

if part.get_content_type() == 'text/plain' and (content_dis


body_text, links_present = filter_links(part.get_payloa
if links_present:
print("Sir, the following email contains links. Ple
Text_to_speech("Sir, the following email contains l
Text_to_speech("Now reading the body of the email w
print('Body:\n', body_text)
Text_to_speech(f'Body: {body_text}')
print("/" * 150)

else:
print("Subject: ", sanitize_gmail_subject(subject))
Text_to_speech(f"Subject: {sanitize_gmail_subject(subject)}")
print(f"From: {decode_header(email_content_in_string_obj_format
Text_to_speech(f"From: {decode_header(email_content_in_string_o
print(f"Date: {decode_header(email_content_in_string_obj_format
Text_to_speech(f"Date: {decode_header(email_content_in_string_o
Text_to_speech("Sir, I encountered a HTML integrated email, so
print("HTML INTEGRATED EMAIL")
file_name = f'{sanitize_gmail_subject(subject)}.html'
if file_name:
output_location = os.path.join(default_path_to_save_html_in
os.makedirs(os.path.dirname(output_location), exist_ok=True
with open(output_location, 'w', encoding='utf-8') as op:
op.write(email_content_in_string_obj_format.get_payload
print("/" * 150)

mail_obj.logout()

print("Sir, I'm done with this task")


Text_to_speech("Sir, I'm done with this task")
return

In [ ]:
# Driver Code
print('Welcome to the Voice Powered Gmail Assistant')
Text_to_speech('Welcome to the Voice Powered Gmail Assistant')
while(1):

print('Sir, Please listen to the following list of operations: ')


Text_to_speech('Sir, Please listen to the following list of operations:

print('Option 1: Compose an Email')


Text_to_speech('Option 1: Compose an Email')

print('Option 2: Read first five Emails')


Text_to_speech('Option 2: Read first five Emails')

print('Option 3: Exit the Program')


Text_to_speech('Option 3: Exit the Program')

print('Sir, I request you to speak out a valid operation.')


Text_to_speech('Sir, I request you to speak out a valid operation.')
user_input = Speech_to_text()

if('option 1' in user_input or 'option one' in user_input or 'option wo


sending_email()
elif('option 2' in user_input or 'option to' in user_input or 'option t
inspect_email()
elif('option 3' in user_input or 'option three' in user_input or 'free'
print('Exiting, please wait.....')
print('Thank You Sir, Please visit again.')
Text_to_speech('Thank You Sir, Please visit again, Have a great day
break
else:
print('Sir, You selected an invalid operation.')
Text_to_speech('Sir, You selected an invalid operation. So, ')

You might also like