Spaces:
Running
Running
Commit ·
580986d
1
Parent(s): e48c284
Almost Done
Browse files
server.py
CHANGED
|
@@ -40,13 +40,23 @@ class GmailApiService:
|
|
| 40 |
try:
|
| 41 |
from google.oauth2 import service_account; from googleapiclient.discovery import build
|
| 42 |
base64_creds = os.getenv('GDRIVE_SA_KEY_BASE64')
|
| 43 |
-
if not
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
creds_json = base64.b64decode(base64_creds).decode('utf-8'); creds_dict = json.loads(creds_json)
|
| 45 |
-
credentials = service_account.Credentials.from_service_account_info(
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
self.service = build('gmail', 'v1', credentials=credentials)
|
| 48 |
-
logger.info("Gmail API Service initialized successfully")
|
| 49 |
-
except Exception:
|
|
|
|
| 50 |
|
| 51 |
def create_professional_email_template(self, subject, status_text, stats, custom_name):
|
| 52 |
status_color = "#28a745" if "completed" in status_text else "#ffc107" if "terminated" in status_text else "#dc3545"
|
|
@@ -85,7 +95,9 @@ class GmailApiService:
|
|
| 85 |
return html_template
|
| 86 |
|
| 87 |
def send_report(self, recipients, subject, body, attachments=None):
|
| 88 |
-
if not self.service or not recipients:
|
|
|
|
|
|
|
| 89 |
try:
|
| 90 |
from googleapiclient.errors import HttpError
|
| 91 |
message = MIMEMultipart(); message['From'] = self.sender_email; message['To'] = ', '.join(recipients); message['Subject'] = subject
|
|
@@ -99,7 +111,12 @@ class GmailApiService:
|
|
| 99 |
sent_message = self.service.users().messages().send(userId='me', body={'raw': raw_message}).execute()
|
| 100 |
logger.info(f"Email sent successfully! Message ID: {sent_message['id']}")
|
| 101 |
return True
|
| 102 |
-
except
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
class GoogleDriveService:
|
| 105 |
def __init__(self):
|
|
@@ -112,7 +129,7 @@ class GoogleDriveService:
|
|
| 112 |
self.creds = service_account.Credentials.from_service_account_info(creds_dict, scopes=['https://www.googleapis.com/auth/drive'])
|
| 113 |
self.service = build('drive', 'v3', credentials=self.creds)
|
| 114 |
logger.info("Google Drive Service initialized successfully.")
|
| 115 |
-
except Exception: logger.exception("G-Drive ERROR: Could not initialize service")
|
| 116 |
|
| 117 |
def upload_file(self, filename, file_content):
|
| 118 |
if not self.service: return False
|
|
@@ -138,13 +155,10 @@ def run_automation_process(session_id):
|
|
| 138 |
try:
|
| 139 |
logger.info(f"Starting automation thread for session: {session_id}")
|
| 140 |
data = session_data.get(session_id, {}); patient_data = data.get('patient_data'); workflow = data.get('workflow')
|
| 141 |
-
if not patient_data: raise ValueError("No patient data prepared.")
|
| 142 |
socketio.emit('initial_stats', {'total': len(patient_data)})
|
| 143 |
-
|
| 144 |
-
# --- Definitive API Alignment Fix ---
|
| 145 |
date_range = {'start_date': data.get('start_date'), 'end_date': data.get('end_date')}
|
| 146 |
results = bot_instance.process_patient_list(patient_data, workflow, date_range)
|
| 147 |
-
|
| 148 |
is_terminated = bot_instance.termination_event.is_set()
|
| 149 |
except Exception as e:
|
| 150 |
logger.exception("Fatal error in automation thread")
|
|
@@ -157,9 +171,9 @@ def run_automation_process(session_id):
|
|
| 157 |
if session_id in session_data: del session_data[session_id]
|
| 158 |
|
| 159 |
def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
|
| 160 |
-
logger.info(f"Preparing final reports
|
| 161 |
data = session_data.get(session_id, {})
|
| 162 |
-
if not data: logger.error("Session data not found
|
| 163 |
|
| 164 |
full_df = pd.DataFrame(data.get('patient_data_for_report'))
|
| 165 |
if results:
|
|
@@ -194,19 +208,20 @@ def generate_and_send_reports(session_id, results, is_crash_report=False, is_ter
|
|
| 194 |
}
|
| 195 |
subject = f"Automation Report [{status_text.upper()}]: {custom_name}"
|
| 196 |
professional_body = email_service.create_professional_email_template(subject, status_text, stats, custom_name)
|
|
|
|
|
|
|
| 197 |
email_service.send_report(data.get('emails'), subject, professional_body, attachments)
|
| 198 |
socketio.emit('process_complete', {'message': f'Process {status_text}. Report sent.'})
|
| 199 |
|
| 200 |
@app.route('/')
|
| 201 |
def status_page():
|
| 202 |
-
|
| 203 |
-
return Response(APP_STATUS_HTML)
|
| 204 |
|
| 205 |
@socketio.on('connect')
|
| 206 |
def handle_connect():
|
| 207 |
logger.info('Frontend connected.')
|
| 208 |
emit('email_list', {'emails': get_email_list()})
|
| 209 |
-
|
| 210 |
@socketio.on('get_email_list')
|
| 211 |
def handle_get_email_list():
|
| 212 |
emit('email_list', {'emails': get_email_list()})
|
|
@@ -259,9 +274,9 @@ def handle_init(data):
|
|
| 259 |
|
| 260 |
socketio.emit('data_processed')
|
| 261 |
logger.info(f"Data prepared. Total records: {len(master_df)}")
|
| 262 |
-
except Exception
|
| 263 |
logger.exception("Error preparing data")
|
| 264 |
-
emit('error', {'message': f'Error preparing data
|
| 265 |
|
| 266 |
@socketio.on('start_login')
|
| 267 |
def handle_login(credentials):
|
|
|
|
| 40 |
try:
|
| 41 |
from google.oauth2 import service_account; from googleapiclient.discovery import build
|
| 42 |
base64_creds = os.getenv('GDRIVE_SA_KEY_BASE64')
|
| 43 |
+
if not self.sender_email:
|
| 44 |
+
logger.warning("EMAIL_SENDER not found in secrets. Emailing will be disabled.")
|
| 45 |
+
return
|
| 46 |
+
if not base64_creds:
|
| 47 |
+
logger.warning("GDRIVE_SA_KEY_BASE64 not found in secrets. Emailing will be disabled.")
|
| 48 |
+
return
|
| 49 |
+
|
| 50 |
creds_json = base64.b64decode(base64_creds).decode('utf-8'); creds_dict = json.loads(creds_json)
|
| 51 |
+
credentials = service_account.Credentials.from_service_account_info(
|
| 52 |
+
creds_dict,
|
| 53 |
+
scopes=['https://www.googleapis.com/auth/gmail.send']
|
| 54 |
+
).with_subject(self.sender_email)
|
| 55 |
+
|
| 56 |
self.service = build('gmail', 'v1', credentials=credentials)
|
| 57 |
+
logger.info("Gmail API Service initialized successfully.")
|
| 58 |
+
except Exception:
|
| 59 |
+
logger.exception("CRITICAL ERROR: Gmail API Service initialization failed.")
|
| 60 |
|
| 61 |
def create_professional_email_template(self, subject, status_text, stats, custom_name):
|
| 62 |
status_color = "#28a745" if "completed" in status_text else "#ffc107" if "terminated" in status_text else "#dc3545"
|
|
|
|
| 95 |
return html_template
|
| 96 |
|
| 97 |
def send_report(self, recipients, subject, body, attachments=None):
|
| 98 |
+
if not self.service or not recipients:
|
| 99 |
+
logger.error("Email not sent. Service not initialized or no recipients.")
|
| 100 |
+
return False
|
| 101 |
try:
|
| 102 |
from googleapiclient.errors import HttpError
|
| 103 |
message = MIMEMultipart(); message['From'] = self.sender_email; message['To'] = ', '.join(recipients); message['Subject'] = subject
|
|
|
|
| 111 |
sent_message = self.service.users().messages().send(userId='me', body={'raw': raw_message}).execute()
|
| 112 |
logger.info(f"Email sent successfully! Message ID: {sent_message['id']}")
|
| 113 |
return True
|
| 114 |
+
except HttpError as error:
|
| 115 |
+
logger.exception(f"An HTTP error occurred while sending email: {error}")
|
| 116 |
+
return False
|
| 117 |
+
except Exception:
|
| 118 |
+
logger.exception("A general error occurred while sending email")
|
| 119 |
+
return False
|
| 120 |
|
| 121 |
class GoogleDriveService:
|
| 122 |
def __init__(self):
|
|
|
|
| 129 |
self.creds = service_account.Credentials.from_service_account_info(creds_dict, scopes=['https://www.googleapis.com/auth/drive'])
|
| 130 |
self.service = build('drive', 'v3', credentials=self.creds)
|
| 131 |
logger.info("Google Drive Service initialized successfully.")
|
| 132 |
+
except Exception: logger.exception("G-Drive CRITICAL ERROR: Could not initialize service")
|
| 133 |
|
| 134 |
def upload_file(self, filename, file_content):
|
| 135 |
if not self.service: return False
|
|
|
|
| 155 |
try:
|
| 156 |
logger.info(f"Starting automation thread for session: {session_id}")
|
| 157 |
data = session_data.get(session_id, {}); patient_data = data.get('patient_data'); workflow = data.get('workflow')
|
| 158 |
+
if not patient_data: raise ValueError("No patient data prepared for automation.")
|
| 159 |
socketio.emit('initial_stats', {'total': len(patient_data)})
|
|
|
|
|
|
|
| 160 |
date_range = {'start_date': data.get('start_date'), 'end_date': data.get('end_date')}
|
| 161 |
results = bot_instance.process_patient_list(patient_data, workflow, date_range)
|
|
|
|
| 162 |
is_terminated = bot_instance.termination_event.is_set()
|
| 163 |
except Exception as e:
|
| 164 |
logger.exception("Fatal error in automation thread")
|
|
|
|
| 171 |
if session_id in session_data: del session_data[session_id]
|
| 172 |
|
| 173 |
def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
|
| 174 |
+
logger.info(f"Preparing final reports for session {session_id}.")
|
| 175 |
data = session_data.get(session_id, {})
|
| 176 |
+
if not data: logger.error("Session data not found. Cannot generate report."); return
|
| 177 |
|
| 178 |
full_df = pd.DataFrame(data.get('patient_data_for_report'))
|
| 179 |
if results:
|
|
|
|
| 208 |
}
|
| 209 |
subject = f"Automation Report [{status_text.upper()}]: {custom_name}"
|
| 210 |
professional_body = email_service.create_professional_email_template(subject, status_text, stats, custom_name)
|
| 211 |
+
|
| 212 |
+
logger.info("Attempting to send final email report...")
|
| 213 |
email_service.send_report(data.get('emails'), subject, professional_body, attachments)
|
| 214 |
socketio.emit('process_complete', {'message': f'Process {status_text}. Report sent.'})
|
| 215 |
|
| 216 |
@app.route('/')
|
| 217 |
def status_page():
|
| 218 |
+
return Response("""<!DOCTYPE html>...""") # Omitted for brevity
|
|
|
|
| 219 |
|
| 220 |
@socketio.on('connect')
|
| 221 |
def handle_connect():
|
| 222 |
logger.info('Frontend connected.')
|
| 223 |
emit('email_list', {'emails': get_email_list()})
|
| 224 |
+
|
| 225 |
@socketio.on('get_email_list')
|
| 226 |
def handle_get_email_list():
|
| 227 |
emit('email_list', {'emails': get_email_list()})
|
|
|
|
| 274 |
|
| 275 |
socketio.emit('data_processed')
|
| 276 |
logger.info(f"Data prepared. Total records: {len(master_df)}")
|
| 277 |
+
except Exception:
|
| 278 |
logger.exception("Error preparing data")
|
| 279 |
+
emit('error', {'message': f'Error preparing data. See backend logs.'})
|
| 280 |
|
| 281 |
@socketio.on('start_login')
|
| 282 |
def handle_login(credentials):
|