region:us
---
{}
---
pip install flask google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client transformers torch apscheduler

import os
import pickle
import base64
from email.mime.text import MIMEText
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from flask import Flask, request, jsonify
from apscheduler.schedulers.background import BackgroundScheduler
from transformers import pipeline

# Flask App Initialization
app = Flask(__name__)

# Initialize NLP models
generator = pipeline('text-generation', model='gpt2')  # Using GPT-2 for local text generation
summarizer = pipeline('summarization')

# Define important senders
important_senders = ['boss@example.com', 'vip_client@example.com']

# Gmail API setup
SCOPES = ['https://www.googleapis.com/auth/gmail.modify']

def get_gmail_service():
    creds = None
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)
    service = build('gmail', 'v1', credentials=creds)
    return service

# Email handling functions
def generate_reply(email_text):
    response = generator(email_text, max_length=100)[0]['generated_text']
    return response

def summarize_conversation(conversation_text):
    summary = summarizer(conversation_text, max_length=150, min_length=30, do_sample=False)[0]['summary_text']
    return summary

def check_for_human_intervention(summary):
    intervention_needed = 'urgent' in summary.lower() or 'immediate attention' in summary.lower()
    return intervention_needed

def prioritize_email(email_subject, email_body, email_sender):
    priority_score = 0
    if 'urgent' in email_subject.lower() or 'urgent' in email_body.lower():
        priority_score += 3
    if 'important' in email_subject.lower() or 'important' in email_body.lower():
        priority_score += 2
    if email_sender in important_senders:
        priority_score += 5
    return priority_score

def sort_emails_by_priority(emails):
    emails_with_priority = [(email, prioritize_email(email['subject'], email['body'], email['sender'])) for email in emails]
    sorted_emails = sorted(emails_with_priority, key=lambda x: x[1], reverse=True)
    return [email for email, priority in sorted_emails]

# Flask routes
@app.route('/send_reply', methods=['POST'])
def send_reply():
    email_text = request.json.get('email_text')
    reply = generate_reply(email_text)
    return jsonify({'reply': reply})

@app.route('/send_summary', methods=['POST'])
def send_summary():
    conversation_text = request.json.get('conversation_text')
    summary = summarize_conversation(conversation_text)
    intervention_needed = check_for_human_intervention(summary)
    return jsonify({'summary': summary, 'intervention_needed': intervention_needed})

@app.route('/sort_emails', methods=['POST'])
def sort_emails():
    emails = request.json.get('emails')
    sorted_emails = sort_emails_by_priority(emails)
    return jsonify({'sorted_emails': sorted_emails})

def fetch_emails(service):
    try:
        results = service.users().messages().list(userId='me', q='is:unread').execute()
        messages = results.get('messages', [])
        emails = []
        for msg in messages:
            msg_data = service.users().messages().get(userId='me', id=msg['id']).execute()
            email_data = {
                'id': msg['id'],
                'subject': next(header['value'] for header in msg_data['payload']['headers'] if header['name'] == 'Subject'),
                'body': base64.urlsafe_b64decode(msg_data['payload']['parts'][0]['body']['data']).decode('utf-8'),
                'sender': next(header['value'] for header in msg_data['payload']['headers'] if header['name'] == 'From')
            }
            emails.append(email_data)
        return emails
    except HttpError as error:
        print(f'An error occurred: {error}')
        return []

def send_summary_report(service, summary, intervention_needed, recipients):
    message = MIMEText(summary)
    message['to'] = ", ".join(recipients)
    message['subject'] = 'Summary Report'
    raw = base64.urlsafe_b64encode(message.as_bytes()).decode('utf-8')
    try:
        message = service.users().messages().send(userId='me', body={'raw': raw}).execute()
        print(f'Message Id: {message["id"]}')
    except HttpError as error:
        print(f'An error occurred: {error}')

def send_periodic_report():
    service = get_gmail_service()
    emails = fetch_emails(service)
    sorted_emails = sort_emails_by_priority(emails)
    for email in sorted_emails:
        reply = generate_reply(email['body'])
        summary = summarize_conversation(email['body'])
        intervention_needed = check_for_human_intervention(summary)
        send_summary_report(service, summary, intervention_needed, ['your_email@example.com'])

# Periodic report sending
scheduler = BackgroundScheduler()
scheduler.add_job(func=send_periodic_report, trigger="interval", hours=24)
scheduler.start()

@app.before_first_request
def initialize():
    scheduler.start()

@app.teardown_appcontext
def shutdown_scheduler(exception=None):
    scheduler.shutdown()

if __name__ == '__main__':
    app.run(debug=True)
