Download components/fetch_emails.py from finding0/app: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/spaces/finding0/app/resolve/main/components/fetch_emails.py
- Command line
-
hf download hf://spaces/finding0/app/components/fetch_emails.py
-
curl -L -o fetch_emails.py https://huggingface.co/spaces/finding0/app/resolve/main/components/fetch_emails.py
12.6 kB
| import json | |
| from oauth2client import client | |
| from apiclient import discovery | |
| from httplib2 import Http | |
| import pandas as pd | |
| import dateutil.parser as parser | |
| from dateutil import tz | |
| import base64 | |
| import re | |
| import time | |
| import math | |
| from data.sample import ( | |
| LABEL_COLS, LABEL_DB, | |
| EMAIL_COLS, EMAIL_DB, | |
| EMAIL_SUMMARY_COLS, EMAIL_SUMMARY_DB, SENDER_SUMMARY_DB, | |
| UNSUB_COLS, UNSUB_DB, | |
| PROCESSING_ERRORS_COLS, PROCESSING_ERRORS_DB, | |
| ANALYSIS_TYPES, FILE_PATHS) | |
| from components.gradio.api import checkDB_api | |
| SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'] # we are using modify and not readonly, as we will be marking the messages Read | |
| A_TAG_REGEX = r'<a\s+(?:[^>]*?\s+)?href=["\']([^"\']*)["\']([^>]*)>(.*?)<\/a>' | |
| def authenticate_gmail(userinfo:dict=None, refresh:bool=False): | |
| """ Authenticates with Gmail API and returns the service object """ | |
| print("Initiating Gmail authentication flow....") | |
| curr_user = userinfo.get('user','') | |
| curr_user_email = curr_user.get('email','') | |
| creds_json = None | |
| response = checkDB_api(row_id_value=curr_user_email, column="gmail_token", table="users", row_id_type="email") | |
| if response: | |
| creds_json = response | |
| if creds_json: | |
| _missing_scopes = [] | |
| for _scope in SCOPES: | |
| if _scope not in creds_json['scopes']: | |
| _missing_scopes.append(_scope) | |
| if len(_missing_scopes) > 0: | |
| print(f"Required Scopes {_missing_scopes} are not present. Skipping..") | |
| # TODO - Trigger new signin with updated scopes | |
| else: | |
| creds = client.OAuth2Credentials.from_json(json.dumps(creds_json)) | |
| if not creds or creds.invalid or refresh: | |
| print("Credentials are invalid or force-refresh is triggered, attempting to refresh.") | |
| try: | |
| creds.refresh(Http()) | |
| if not creds.invalid: | |
| print("Credentials refreshed successfully.") | |
| creds_json = creds.to_json() | |
| # TODO - Update auth_response in the database | |
| except client.AccessTokenRefreshError: | |
| print("Failed to refresh access token.") | |
| return None | |
| service = discovery.build('gmail', 'v1', http=creds.authorize(Http())) | |
| return service | |
| return None | |
| def parse_email(service, msg_id, label_id): | |
| email = { | |
| 'id': msg_id, | |
| 'label':label_id, | |
| 'date': None, | |
| 'from': None, | |
| 'email': None, | |
| 'domain': None, | |
| 'subject': None, | |
| 'unsub_links': []} | |
| message_details = service.users().messages().get(userId='me', id=email['id']).execute() | |
| # pretty_print_blueprint(message_details) | |
| payload = message_details['payload'] | |
| headers = payload.get('headers', []) | |
| for header in headers: | |
| if header['name'] == 'From': | |
| from_ = header['value'] | |
| email['email'], email['domain'], email['from'] = extract_email_and_domain(from_) | |
| if header['name'] == 'Subject': | |
| email['subject'] = header['value'] | |
| if header['name'] == 'Date': | |
| # Valid date format: Tue, 04 Jun 2024 19:31:16 +0000 = "%a, %d %b %Y %H:%M:%S %z" | |
| date_ = header['value'] | |
| date_ = (parser.parse(date_,)) | |
| # print("Gmail Date: ", date_) | |
| date_ = date_.astimezone(tz.tzlocal()) | |
| # print("Local TimeZone Date: ", date_) | |
| date_ = date_.replace(tzinfo=None) | |
| # print("TimeZone Naive Date: ", date_) | |
| date_ = date_.strftime('%Y-%m-%dT%H:%M:%S') | |
| # print("JSON Serializable Date: ", date_) | |
| email['date'] = (date_) | |
| # email['snippet'] = message_details['snippet'] | |
| msg_parts = payload.get('parts', []) | |
| unsubscribe_links = [] | |
| for m_i, part in enumerate(msg_parts): | |
| part_body = part['body'] | |
| # pretty_print_blueprint(part_body) | |
| if 'data' in part_body: | |
| part_data = part_body['data'] # fetching data from the body | |
| # pretty_print_blueprint(part_data) | |
| clean_one = part_data.replace("-", "+") # decoding from Base64 to UTF-8 | |
| # pretty_print_blueprint(clean_one) | |
| clean_one = clean_one.replace("_", "/") # decoding from Base64 to UTF-8 | |
| # pretty_print_blueprint(clean_one) | |
| clean_two = base64.b64decode(bytes(clean_one, 'UTF-8')) # decoding from Base64 to UTF-8 | |
| # print(m_i, clean_two) | |
| a_tags = re.findall(A_TAG_REGEX, str(clean_two)) | |
| for tag in a_tags: | |
| href, attributes, link_text = tag | |
| # print(f'{link_text} Link: {href}') | |
| if 'unsubscribe' in link_text.lower(): | |
| # print(f'{link_text} Link: {href}') | |
| unsubscribe_links.append(href) | |
| email['unsub_links'] = list(set(unsubscribe_links)) | |
| return email | |
| # Function to extract email from the sender field | |
| def extract_email(sender): | |
| match = re.search(r'<(.+?)>|([^<>\s]+@[^<>\s]+)', sender) | |
| if match: | |
| email = match.group(1) if match.group(1) else match.group(2) | |
| return email | |
| return None | |
| # Function to extract domain from the sender field | |
| def extract_domain(sender): | |
| email = extract_email(sender) | |
| domain = email.split('@')[1] if email else None | |
| return domain | |
| def extract_email_and_domain(sender): | |
| email = extract_email(sender) | |
| domain = email.split('@')[1] if email else None | |
| sender_name = sender.replace(email,'') | |
| sender_name = sender_name.replace(' <','') | |
| sender_name = sender_name.replace('>','') | |
| return email, domain, sender_name | |
| def get_emails(label_id = 'INBOX', num_emails = 20, max_results = 10, userinfo = None): | |
| """ Fetches unread emails for a specific label """ | |
| print(f"Fetching '{num_emails}' unread emails for label '{label_id}'....") | |
| emails = [] | |
| emails_with_error = [] | |
| sender_counts = SENDER_SUMMARY_DB | |
| domain_counts = EMAIL_SUMMARY_DB | |
| df = EMAIL_DB | |
| unsub_db = UNSUB_DB | |
| error_db = PROCESSING_ERRORS_DB | |
| total_batches = math.ceil(num_emails/max_results) | |
| curr_batch = 1 | |
| start_time = time.time() | |
| rem_emails = num_emails | |
| update = f"π π Analysis initiated... for the selected label with id '{label_id}'" | |
| print(update) | |
| yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| service = authenticate_gmail(userinfo) | |
| if service: | |
| page_token = True | |
| while page_token and rem_emails > 0: | |
| if rem_emails < max_results: | |
| max_results = rem_emails | |
| if type(page_token) == str: | |
| if num_emails > 250: | |
| mini_update = update+f""" - Initializing auto-reconnect to Gmail API""" | |
| print(mini_update) | |
| yield mini_update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| service = authenticate_gmail(userinfo,refresh=True) | |
| mini_update = update+f""" - Completed auto-reconnect to Gmail API""" | |
| print(mini_update) | |
| yield mini_update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| response = service.users().messages().list( | |
| userId='me', | |
| maxResults=max_results, | |
| pageToken=page_token | |
| ).execute() | |
| else: | |
| response = service.users().messages().list( | |
| userId='me', | |
| labelIds=[label_id, 'UNREAD'], | |
| maxResults=max_results | |
| ).execute() | |
| messages = response.get('messages', []) # Handle case where no unread emails exist | |
| # print(page_token, len(messages)) | |
| for idx_, message in enumerate(messages): | |
| # print(len(emails)) | |
| email = { | |
| 'id': None, | |
| 'label':label_id, | |
| 'date': None, | |
| 'from': None, | |
| 'email': None, | |
| 'domain': None, | |
| 'subject': None, | |
| 'unsub_links': []} | |
| try: | |
| email = parse_email(service, message['id'], label_id) | |
| except Exception as error: | |
| emails_with_error.append({'error': error, **email}) | |
| update = f"""π΄ Error '{error}' while processing email having id '{email['id']}' with subject '{email['subject']}' received from '{email['from']}' on '{email['date']}'""" | |
| print(update) | |
| yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| emails.append(email) | |
| if len(emails) % 10 == 0: | |
| elapsed_time = time.time() - start_time | |
| update = f"π‘ β³ Loading, please wait... Analysis in progress [#Emails Processed - {len(emails)}/{num_emails}] [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins] [{curr_batch}/{total_batches}] [Current Batch-size - {max_results}]" | |
| print(update) | |
| yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| page_token = response.get('nextPageToken', False) | |
| rem_emails = num_emails - len(emails) | |
| elapsed_time = time.time() - start_time | |
| if rem_emails > 0: | |
| curr_batch += 1 | |
| update = f"π‘ β³ Loading, please wait... Analysis in progress [#Emails Processed - {len(emails)}/{num_emails}] [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins] [{curr_batch}/{total_batches}] [Current Batch-size - {max_results}]" | |
| print(update) | |
| yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| # Create analyses - Sender-wise, Domain-wise, Unsubscribe links | |
| df = pd.DataFrame(emails) | |
| sender_counts = df.groupby(['label','email'])['id'].count().reset_index(name='emailCount') | |
| sender_counts = sender_counts.sort_values(by='emailCount', ascending=False) | |
| sender_counts.columns = EMAIL_SUMMARY_COLS | |
| domain_counts = df.groupby(['label','domain'])['id'].count().reset_index(name='emailCount') | |
| domain_counts = domain_counts.sort_values(by='emailCount', ascending=False) | |
| domain_counts.columns = EMAIL_SUMMARY_COLS | |
| total_count = pd.DataFrame([['ALL', 'ALL', sender_counts['emailCount'].sum()]], columns=EMAIL_SUMMARY_COLS) | |
| sender_counts = pd.concat([total_count, sender_counts]).reset_index(drop=True) | |
| total_count = pd.DataFrame([['ALL', 'ALL', domain_counts['emailCount'].sum()]], columns=EMAIL_SUMMARY_COLS) | |
| domain_counts = pd.concat([total_count, domain_counts]).reset_index(drop=True) | |
| unsub_db_ = df.copy(deep=True) | |
| unsub_db_['unsub_link'] = unsub_db_['unsub_links'].apply(lambda x: x[0] if len(x) > 0 else None) | |
| unsub_db = unsub_db_.groupby(['label','domain','email','from']).size().reset_index(name='emailCount') | |
| unsub_db_ = unsub_db_.groupby(['label','domain', 'email', 'from']).first().reset_index() | |
| unsub_db = pd.merge(unsub_db, unsub_db_[['label','domain', 'email', 'from', 'unsub_link']], on=['label','domain', 'email', 'from'], how='left') | |
| unsub_db = unsub_db.sort_values(by='emailCount', ascending=False) | |
| # TODO: unsub_link validation - Add "Suspicious Unsubscription Link" if invalid & "Unsubscription Link - Not Found" if empty | |
| error_db = pd.DataFrame(emails_with_error, columns=PROCESSING_ERRORS_COLS) | |
| # print(error_db) | |
| update = f"""π’ π Success! {len(emails)}/{num_emails} emails processed for the selected label with id '{label_id}' [Elapsed time: {int(elapsed_time // 60):02d}:{(elapsed_time % 60):05.2f} mins]""" | |
| print(update) | |
| yield update, sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |
| else: | |
| yield "π΄ Error! No connection with GmailAPI. Please reconnect & try again.", sender_counts.head(25), domain_counts.head(25), df.head(25), unsub_db.head(25), error_db.head(25) | |