Spaces:
Running
Running
Commit Β·
ba9916c
1
Parent(s): 5e0fe1d
Uploaded
Browse files- Dockerfile +4 -15
- server.py +396 -366
Dockerfile
CHANGED
|
@@ -1,13 +1,9 @@
|
|
| 1 |
-
# Dockerfile - Final Production Version
|
| 2 |
FROM python:3.11-slim
|
| 3 |
|
| 4 |
WORKDIR /app
|
| 5 |
|
| 6 |
-
# Environment setup for HuggingFace Spaces
|
| 7 |
ENV DEBIAN_FRONTEND=noninteractive
|
| 8 |
ENV TZ=Etc/UTC
|
| 9 |
-
ENV HOME=/home/appuser
|
| 10 |
-
ENV PYTHONUSERBASE=/home/appuser/.local
|
| 11 |
|
| 12 |
# Install Chrome and dependencies
|
| 13 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
@@ -15,14 +11,12 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
| 15 |
chromium-driver \
|
| 16 |
ca-certificates \
|
| 17 |
fonts-liberation \
|
| 18 |
-
libasound2 \
|
| 19 |
-
libatk-bridge2.0-0 \
|
| 20 |
-
libdrm2 \
|
| 21 |
-
libgtk-3-0 \
|
| 22 |
-
libnspr4 \
|
| 23 |
libnss3 \
|
| 24 |
libxss1 \
|
|
|
|
| 25 |
libxtst6 \
|
|
|
|
|
|
|
| 26 |
libgbm1 \
|
| 27 |
libxrandr2 \
|
| 28 |
libxcomposite1 \
|
|
@@ -30,18 +24,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
| 30 |
procps \
|
| 31 |
&& rm -rf /var/lib/apt/lists/*
|
| 32 |
|
| 33 |
-
# Install Python packages
|
| 34 |
COPY requirements.txt .
|
| 35 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 36 |
|
| 37 |
-
# Create non-root user for HuggingFace Spaces
|
| 38 |
-
RUN adduser --disabled-password --gecos '' --uid 1000 appuser
|
| 39 |
USER 1000
|
| 40 |
|
| 41 |
-
# Copy application files
|
| 42 |
COPY --chown=1000:1000 . .
|
| 43 |
-
|
| 44 |
-
# Create config directory
|
| 45 |
RUN mkdir -p config
|
| 46 |
|
| 47 |
EXPOSE 7860
|
|
|
|
|
|
|
| 1 |
FROM python:3.11-slim
|
| 2 |
|
| 3 |
WORKDIR /app
|
| 4 |
|
|
|
|
| 5 |
ENV DEBIAN_FRONTEND=noninteractive
|
| 6 |
ENV TZ=Etc/UTC
|
|
|
|
|
|
|
| 7 |
|
| 8 |
# Install Chrome and dependencies
|
| 9 |
RUN apt-get update && apt-get install -y --no-install-recommends \
|
|
|
|
| 11 |
chromium-driver \
|
| 12 |
ca-certificates \
|
| 13 |
fonts-liberation \
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
libnss3 \
|
| 15 |
libxss1 \
|
| 16 |
+
libasound2 \
|
| 17 |
libxtst6 \
|
| 18 |
+
libatk-bridge2.0-0 \
|
| 19 |
+
libgtk-3-0 \
|
| 20 |
libgbm1 \
|
| 21 |
libxrandr2 \
|
| 22 |
libxcomposite1 \
|
|
|
|
| 24 |
procps \
|
| 25 |
&& rm -rf /var/lib/apt/lists/*
|
| 26 |
|
| 27 |
+
# Install Python packages
|
| 28 |
COPY requirements.txt .
|
| 29 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 30 |
|
|
|
|
|
|
|
| 31 |
USER 1000
|
| 32 |
|
|
|
|
| 33 |
COPY --chown=1000:1000 . .
|
|
|
|
|
|
|
| 34 |
RUN mkdir -p config
|
| 35 |
|
| 36 |
EXPOSE 7860
|
server.py
CHANGED
|
@@ -1,276 +1,286 @@
|
|
| 1 |
-
# server.py -
|
| 2 |
import eventlet
|
| 3 |
eventlet.monkey_patch()
|
| 4 |
|
| 5 |
import pandas as pd
|
| 6 |
import io
|
| 7 |
import os
|
| 8 |
-
import base64
|
| 9 |
import json
|
| 10 |
-
import requests
|
| 11 |
-
import smtplib
|
| 12 |
-
import ssl
|
| 13 |
import logging
|
| 14 |
from datetime import datetime
|
| 15 |
from flask import Flask, Response
|
| 16 |
from flask_socketio import SocketIO, emit
|
| 17 |
from flask_cors import CORS
|
| 18 |
-
from flask_mail import Mail, Message
|
| 19 |
from worker import QuantumBot
|
| 20 |
-
from email.mime.multipart import MIMEMultipart
|
| 21 |
-
from email.mime.text import MIMEText
|
| 22 |
-
from email.mime.base import MIMEBase
|
| 23 |
-
from email import encoders
|
| 24 |
from dotenv import load_dotenv
|
| 25 |
|
| 26 |
-
|
| 27 |
-
logging.basicConfig(
|
| 28 |
-
level=logging.INFO,
|
| 29 |
-
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 30 |
-
)
|
| 31 |
-
|
| 32 |
load_dotenv()
|
| 33 |
|
| 34 |
app = Flask(__name__)
|
| 35 |
app.config['SECRET_KEY'] = 'secret-key-for-hillside-automation'
|
| 36 |
FRONTEND_ORIGIN = os.getenv('FRONTEND_URL', 'https://quantbot.netlify.app')
|
| 37 |
-
|
| 38 |
-
# Flask-Mail configuration for Gmail SMTP
|
| 39 |
-
app.config.update(
|
| 40 |
-
MAIL_SERVER='smtp.gmail.com',
|
| 41 |
-
MAIL_PORT=587,
|
| 42 |
-
MAIL_USE_TLS=True,
|
| 43 |
-
MAIL_USE_SSL=False,
|
| 44 |
-
MAIL_USERNAME=os.getenv('EMAIL_SENDER'),
|
| 45 |
-
MAIL_PASSWORD=os.getenv('EMAIL_PASSWORD'),
|
| 46 |
-
MAIL_DEFAULT_SENDER=os.getenv('EMAIL_SENDER'),
|
| 47 |
-
MAIL_DEBUG=True,
|
| 48 |
-
MAIL_SUPPRESS_SEND=False
|
| 49 |
-
)
|
| 50 |
-
|
| 51 |
CORS(app, resources={r"/*": {"origins": [FRONTEND_ORIGIN, "http://localhost:3000", "http://127.0.0.1:5500", "null"]}})
|
| 52 |
socketio = SocketIO(app, cors_allowed_origins=[FRONTEND_ORIGIN, "http://localhost:3000", "http://127.0.0.1:5500", "null"], async_mode='eventlet')
|
| 53 |
|
| 54 |
-
mail = Mail(app)
|
| 55 |
-
|
| 56 |
bot_instance = None
|
| 57 |
session_data = {}
|
| 58 |
|
| 59 |
-
class
|
| 60 |
def __init__(self):
|
| 61 |
-
self.logger = logging.getLogger('
|
| 62 |
-
|
| 63 |
-
# Email configuration
|
| 64 |
self.sender_email = os.getenv('EMAIL_SENDER')
|
| 65 |
-
self.gmail_password = os.getenv('EMAIL_PASSWORD')
|
| 66 |
-
self.sendgrid_api_key = os.getenv('SENDGRID_API_KEY')
|
| 67 |
|
| 68 |
-
self.logger.info("=== EMAIL SERVICE
|
|
|
|
| 69 |
self.logger.info(f"EMAIL_SENDER: {self.sender_email}")
|
| 70 |
-
self.logger.info(f"GMAIL_PASSWORD: {'SET' if self.gmail_password else 'MISSING'}")
|
| 71 |
-
self.logger.info(f"SENDGRID_API_KEY: {'SET' if self.sendgrid_api_key else 'MISSING'}")
|
| 72 |
-
|
| 73 |
-
# Verify Gmail password format
|
| 74 |
-
if self.gmail_password:
|
| 75 |
-
self.logger.info(f"Gmail password length: {len(self.gmail_password)}")
|
| 76 |
-
if len(self.gmail_password) == 16 and ' ' not in self.gmail_password:
|
| 77 |
-
self.logger.info("β
Gmail App Password format looks correct")
|
| 78 |
-
else:
|
| 79 |
-
self.logger.warning("β οΈ Gmail password might not be a proper App Password")
|
| 80 |
|
| 81 |
-
def
|
| 82 |
-
"""
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
def
|
| 107 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
try:
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
msg = MIMEMultipart('alternative')
|
| 112 |
-
msg['From'] = self.sender_email
|
| 113 |
-
msg['To'] = ', '.join(recipients)
|
| 114 |
-
msg['Subject'] = subject
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
|
| 118 |
-
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
part = MIMEBase('application', 'octet-stream')
|
| 124 |
-
part.set_payload(content.encode('utf-8'))
|
| 125 |
-
encoders.encode_base64(part)
|
| 126 |
-
part.add_header('Content-Disposition', f'attachment; filename="{filename}"')
|
| 127 |
-
msg.attach(part)
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
with smtplib.SMTP('smtp.gmail.com', 587) as server:
|
| 132 |
-
server.starttls(context=context)
|
| 133 |
-
server.login(self.sender_email, self.gmail_password)
|
| 134 |
-
text = msg.as_string()
|
| 135 |
-
server.sendmail(self.sender_email, recipients, text)
|
| 136 |
|
| 137 |
-
|
| 138 |
return True
|
| 139 |
|
| 140 |
except Exception as e:
|
| 141 |
-
self.logger.error(f"β
|
| 142 |
return False
|
| 143 |
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
if not self.sendgrid_api_key:
|
| 147 |
-
self.logger.info("βοΈ SendGrid API key not available, skipping...")
|
| 148 |
-
return False
|
| 149 |
-
|
| 150 |
-
try:
|
| 151 |
-
self.logger.info("π Attempting SendGrid HTTP API...")
|
| 152 |
-
|
| 153 |
-
# Prepare attachments
|
| 154 |
-
attachment_data = []
|
| 155 |
-
if attachments:
|
| 156 |
-
for filename, content in attachments.items():
|
| 157 |
-
encoded_content = base64.b64encode(content.encode('utf-8')).decode()
|
| 158 |
-
attachment_data.append({
|
| 159 |
-
'content': encoded_content,
|
| 160 |
-
'filename': filename,
|
| 161 |
-
'type': 'text/csv',
|
| 162 |
-
'disposition': 'attachment'
|
| 163 |
-
})
|
| 164 |
-
|
| 165 |
-
headers = {
|
| 166 |
-
'Authorization': f'Bearer {self.sendgrid_api_key}',
|
| 167 |
-
'Content-Type': 'application/json'
|
| 168 |
-
}
|
| 169 |
-
|
| 170 |
-
data = {
|
| 171 |
-
'personalizations': [{
|
| 172 |
-
'to': [{'email': email} for email in recipients]
|
| 173 |
-
}],
|
| 174 |
-
'from': {'email': self.sender_email},
|
| 175 |
-
'subject': subject,
|
| 176 |
-
'content': [{'type': 'text/html', 'value': body}],
|
| 177 |
-
'attachments': attachment_data
|
| 178 |
-
}
|
| 179 |
-
|
| 180 |
-
response = requests.post(
|
| 181 |
-
'https://api.sendgrid.com/v3/mail/send',
|
| 182 |
-
headers=headers,
|
| 183 |
-
json=data,
|
| 184 |
-
timeout=30
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
if response.status_code == 202:
|
| 188 |
-
self.logger.info("β
SendGrid API success!")
|
| 189 |
-
return True
|
| 190 |
-
else:
|
| 191 |
-
self.logger.error(f"β SendGrid API failed: {response.status_code} - {response.text}")
|
| 192 |
-
return False
|
| 193 |
-
|
| 194 |
-
except Exception as e:
|
| 195 |
-
self.logger.error(f"β SendGrid API failed: {e}")
|
| 196 |
-
return False
|
| 197 |
-
|
| 198 |
-
def send_report(self, recipients, subject, body, attachments=None):
|
| 199 |
-
"""Try multiple methods until one succeeds"""
|
| 200 |
-
if not recipients:
|
| 201 |
-
self.logger.error("β No recipients provided")
|
| 202 |
-
return False
|
| 203 |
-
|
| 204 |
-
if not self.sender_email:
|
| 205 |
-
self.logger.error("β No sender email configured")
|
| 206 |
-
return False
|
| 207 |
-
|
| 208 |
-
self.logger.info("=== STARTING EMAIL SENDING ===")
|
| 209 |
-
self.logger.info(f"To: {recipients}")
|
| 210 |
-
self.logger.info(f"Subject: {subject}")
|
| 211 |
-
self.logger.info(f"Attachments: {len(attachments) if attachments else 0}")
|
| 212 |
-
|
| 213 |
-
# Try methods in order of preference
|
| 214 |
-
methods = [
|
| 215 |
-
('Flask-Mail (Gmail SMTP)', self.send_via_flask_mail),
|
| 216 |
-
('Raw SMTP (Gmail)', self.send_via_raw_smtp),
|
| 217 |
-
('SendGrid HTTP API', self.send_via_sendgrid_api)
|
| 218 |
-
]
|
| 219 |
-
|
| 220 |
-
for method_name, method_func in methods:
|
| 221 |
-
self.logger.info(f"π Trying: {method_name}")
|
| 222 |
-
try:
|
| 223 |
-
if method_func(recipients, subject, body, attachments):
|
| 224 |
-
self.logger.info(f"π SUCCESS via {method_name}")
|
| 225 |
-
return True
|
| 226 |
-
except Exception as e:
|
| 227 |
-
self.logger.error(f"π₯ {method_name} crashed: {e}")
|
| 228 |
-
continue
|
| 229 |
-
|
| 230 |
-
self.logger.error("β ALL EMAIL METHODS FAILED")
|
| 231 |
-
return False
|
| 232 |
-
|
| 233 |
-
class GoogleDriveService:
|
| 234 |
def __init__(self):
|
| 235 |
-
self.logger = logging.getLogger('
|
| 236 |
-
self.
|
| 237 |
-
self.folder_id = os.getenv('GOOGLE_DRIVE_FOLDER_ID')
|
| 238 |
-
|
| 239 |
-
try:
|
| 240 |
-
from google.oauth2 import service_account
|
| 241 |
-
from googleapiclient.discovery import build
|
| 242 |
-
|
| 243 |
-
base64_creds = os.getenv('GDRIVE_SA_KEY_BASE64')
|
| 244 |
-
if base64_creds and self.folder_id:
|
| 245 |
-
creds_json = base64.b64decode(base64_creds).decode('utf-8')
|
| 246 |
-
creds_dict = json.loads(creds_json)
|
| 247 |
-
self.creds = service_account.Credentials.from_service_account_info(
|
| 248 |
-
creds_dict, scopes=['https://www.googleapis.com/auth/drive']
|
| 249 |
-
)
|
| 250 |
-
self.service = build('drive', 'v3', credentials=self.creds)
|
| 251 |
-
self.logger.info("β
Google Drive configured")
|
| 252 |
-
else:
|
| 253 |
-
self.logger.info("β οΈ Google Drive not configured")
|
| 254 |
-
except Exception as e:
|
| 255 |
-
self.logger.warning(f"β οΈ Google Drive setup failed: {e}")
|
| 256 |
|
| 257 |
def upload_file(self, filename, file_content):
|
| 258 |
-
|
| 259 |
-
return False
|
| 260 |
try:
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
result = self.service.files().create(body=file_metadata, media_body=media, fields='id').execute()
|
| 265 |
-
self.logger.info(f"β
Google Drive upload success: {result.get('id')}")
|
| 266 |
return True
|
| 267 |
except Exception as e:
|
| 268 |
-
self.logger.
|
| 269 |
return False
|
| 270 |
|
| 271 |
# Initialize services
|
| 272 |
-
email_service =
|
| 273 |
-
|
| 274 |
|
| 275 |
def get_email_list():
|
| 276 |
try:
|
|
@@ -279,8 +289,8 @@ def get_email_list():
|
|
| 279 |
logging.info(f"β
Loaded {len(emails)} email addresses")
|
| 280 |
return emails
|
| 281 |
except FileNotFoundError:
|
| 282 |
-
logging.info("β οΈ config/emails.conf not found")
|
| 283 |
-
return []
|
| 284 |
|
| 285 |
def run_automation_process(session_id):
|
| 286 |
global bot_instance
|
|
@@ -306,7 +316,7 @@ def run_automation_process(session_id):
|
|
| 306 |
is_crash = True
|
| 307 |
socketio.emit('error', {'message': f'A fatal error occurred: {e}'})
|
| 308 |
finally:
|
| 309 |
-
socketio.emit('micro_status_update', {'message': 'Generating
|
| 310 |
generate_and_send_reports(session_id, results, is_crash_report=is_crash, is_terminated=is_terminated)
|
| 311 |
if bot_instance:
|
| 312 |
bot_instance.shutdown()
|
|
@@ -315,10 +325,10 @@ def run_automation_process(session_id):
|
|
| 315 |
del session_data[session_id]
|
| 316 |
|
| 317 |
def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
|
| 318 |
-
logging.info("=== GENERATING REPORTS ===")
|
| 319 |
|
| 320 |
if not results:
|
| 321 |
-
socketio.emit('process_complete', {'message': 'No patients
|
| 322 |
return
|
| 323 |
|
| 324 |
data = session_data.get(session_id, {})
|
|
@@ -339,64 +349,113 @@ def generate_and_send_reports(session_id, results, is_crash_report=False, is_ter
|
|
| 339 |
bad_report_name = f"{custom_name}_Bad.csv"
|
| 340 |
full_report_content = full_df.to_csv(index=False)
|
| 341 |
|
| 342 |
-
#
|
| 343 |
-
|
| 344 |
|
| 345 |
-
#
|
| 346 |
-
recipients = data.get('emails',
|
| 347 |
-
if not recipients:
|
| 348 |
-
socketio.emit('process_complete', {'message': 'Process completed but no emails configured.'})
|
| 349 |
-
return
|
| 350 |
|
| 351 |
status_text = "terminated by user" if is_terminated else "crashed due to an error" if is_crash_report else "completed successfully"
|
| 352 |
subject = f"π€ Automation Report [{status_text.upper()}]: {custom_name}"
|
| 353 |
|
|
|
|
| 354 |
body = f"""
|
| 355 |
-
<
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
</div>
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
<div class="
|
| 371 |
-
<
|
| 372 |
-
<
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
<li><strong>
|
| 377 |
-
<li><strong>
|
| 378 |
-
|
|
|
|
|
|
|
| 379 |
</div>
|
| 380 |
-
|
| 381 |
-
|
|
|
|
|
|
|
| 382 |
<ul>
|
| 383 |
-
<li><strong>
|
| 384 |
-
<li><strong>
|
| 385 |
-
<li><strong>
|
|
|
|
|
|
|
| 386 |
</ul>
|
| 387 |
-
|
| 388 |
-
<h3>π§ Delivery Information:</h3>
|
| 389 |
-
<p>Both reports are attached to this email. The full report contains all patient records with updated statuses,
|
| 390 |
-
while the "Bad" report contains only records that encountered issues during processing.</p>
|
| 391 |
</div>
|
|
|
|
| 392 |
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
"""
|
| 401 |
|
| 402 |
attachments = {
|
|
@@ -404,91 +463,91 @@ def generate_and_send_reports(session_id, results, is_crash_report=False, is_ter
|
|
| 404 |
bad_report_name: bad_df.to_csv(index=False)
|
| 405 |
}
|
| 406 |
|
| 407 |
-
|
|
|
|
| 408 |
|
| 409 |
-
if
|
| 410 |
-
final_message = f'β
|
| 411 |
else:
|
| 412 |
-
final_message = f'
|
| 413 |
|
| 414 |
socketio.emit('process_complete', {'message': final_message})
|
| 415 |
logging.info(f"=== FINAL RESULT: {final_message} ===")
|
| 416 |
|
|
|
|
| 417 |
@app.route('/')
|
| 418 |
def status_page():
|
| 419 |
-
# Test email configuration
|
| 420 |
-
env_checks = {
|
| 421 |
-
'EMAIL_SENDER': 'β
Set' if os.getenv('EMAIL_SENDER') else 'β Missing',
|
| 422 |
-
'EMAIL_PASSWORD': 'β
Set' if os.getenv('EMAIL_PASSWORD') else 'β Missing',
|
| 423 |
-
'SENDGRID_API_KEY': 'β
Set' if os.getenv('SENDGRID_API_KEY') else 'β οΈ Optional',
|
| 424 |
-
'GOOGLE_DRIVE': 'β
Configured' if os.getenv('GOOGLE_DRIVE_FOLDER_ID') else 'β οΈ Optional'
|
| 425 |
-
}
|
| 426 |
-
|
| 427 |
-
# Test SMTP connectivity
|
| 428 |
-
smtp_test = "β Failed"
|
| 429 |
-
try:
|
| 430 |
-
import socket
|
| 431 |
-
sock = socket.create_connection(('smtp.gmail.com', 587), timeout=10)
|
| 432 |
-
sock.close()
|
| 433 |
-
smtp_test = "β
Reachable"
|
| 434 |
-
except:
|
| 435 |
-
smtp_test = "β Blocked"
|
| 436 |
-
|
| 437 |
APP_STATUS_HTML = f"""
|
| 438 |
<!DOCTYPE html>
|
| 439 |
<html>
|
| 440 |
<head>
|
| 441 |
-
<title>π€ Hillside Automation -
|
| 442 |
<style>
|
| 443 |
-
body {{
|
| 444 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
.header {{ text-align: center; margin-bottom: 30px; }}
|
| 446 |
-
.status-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
</style>
|
| 454 |
</head>
|
| 455 |
<body>
|
| 456 |
<div class="container">
|
| 457 |
<div class="header">
|
| 458 |
<h1>π€ Hillside Quantum Automation</h1>
|
| 459 |
-
<
|
| 460 |
</div>
|
| 461 |
|
| 462 |
-
<div class="
|
| 463 |
-
<
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
<
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
<div class="status-item">WebSocket: <span class="success">β
Active</span></div>
|
| 476 |
-
<div class="status-item">Email Methods: <span class="success">β
Multi-fallback</span></div>
|
| 477 |
-
</div>
|
| 478 |
</div>
|
| 479 |
|
| 480 |
<div class="status-box">
|
| 481 |
-
<h3
|
| 482 |
-
<
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
|
|
|
| 487 |
</div>
|
| 488 |
|
| 489 |
-
<div class="
|
| 490 |
-
<
|
| 491 |
-
<p>
|
|
|
|
|
|
|
| 492 |
</div>
|
| 493 |
</div>
|
| 494 |
</body>
|
|
@@ -496,34 +555,7 @@ def status_page():
|
|
| 496 |
"""
|
| 497 |
return Response(APP_STATUS_HTML)
|
| 498 |
|
| 499 |
-
|
| 500 |
-
def test_email():
|
| 501 |
-
"""Quick email test endpoint"""
|
| 502 |
-
test_recipients = ['your-test-email@gmail.com'] # Replace with your email
|
| 503 |
-
test_success = email_service.send_report(
|
| 504 |
-
recipients=test_recipients,
|
| 505 |
-
subject='π§ͺ Test Email from Hillside Automation',
|
| 506 |
-
body='''
|
| 507 |
-
<h1>β
Email Test Successful!</h1>
|
| 508 |
-
<p>If you're reading this, the email system is working correctly.</p>
|
| 509 |
-
<p><strong>Test Details:</strong></p>
|
| 510 |
-
<ul>
|
| 511 |
-
<li>Timestamp: ''' + datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC') + '''</li>
|
| 512 |
-
<li>Platform: HuggingFace Spaces</li>
|
| 513 |
-
<li>System: Hillside Automation</li>
|
| 514 |
-
</ul>
|
| 515 |
-
<p>β¨ All systems operational!</p>
|
| 516 |
-
''',
|
| 517 |
-
attachments={'test-file.txt': 'This is a test attachment content.'}
|
| 518 |
-
)
|
| 519 |
-
|
| 520 |
-
return {
|
| 521 |
-
'success': test_success,
|
| 522 |
-
'message': 'Check your email and server logs for details',
|
| 523 |
-
'timestamp': datetime.now().isoformat()
|
| 524 |
-
}
|
| 525 |
-
|
| 526 |
-
# Keep all existing socket handlers
|
| 527 |
@socketio.on('connect')
|
| 528 |
def handle_connect():
|
| 529 |
logging.info('Frontend connected')
|
|
@@ -539,8 +571,6 @@ def handle_init(data):
|
|
| 539 |
'filename': data['filename']
|
| 540 |
}
|
| 541 |
|
| 542 |
-
logging.info(f"Session initialized with {len(data['emails'])} recipients")
|
| 543 |
-
|
| 544 |
if bot_instance:
|
| 545 |
bot_instance.shutdown()
|
| 546 |
bot_instance = QuantumBot(socketio, app)
|
|
@@ -581,10 +611,10 @@ def handle_terminate():
|
|
| 581 |
|
| 582 |
if __name__ == '__main__':
|
| 583 |
print("====================================================================")
|
| 584 |
-
print(" π€ HILLSIDE AUTOMATION -
|
| 585 |
-
print(
|
| 586 |
-
print(
|
| 587 |
-
print(
|
| 588 |
-
print(
|
| 589 |
print("====================================================================")
|
| 590 |
socketio.run(app, host='0.0.0.0', port=int(os.getenv('PORT', 7860)))
|
|
|
|
| 1 |
+
# server.py - HuggingFace Spaces SMTP-Free Solution
|
| 2 |
import eventlet
|
| 3 |
eventlet.monkey_patch()
|
| 4 |
|
| 5 |
import pandas as pd
|
| 6 |
import io
|
| 7 |
import os
|
|
|
|
| 8 |
import json
|
|
|
|
|
|
|
|
|
|
| 9 |
import logging
|
| 10 |
from datetime import datetime
|
| 11 |
from flask import Flask, Response
|
| 12 |
from flask_socketio import SocketIO, emit
|
| 13 |
from flask_cors import CORS
|
|
|
|
| 14 |
from worker import QuantumBot
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from dotenv import load_dotenv
|
| 16 |
|
| 17 |
+
logging.basicConfig(level=logging.INFO)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
load_dotenv()
|
| 19 |
|
| 20 |
app = Flask(__name__)
|
| 21 |
app.config['SECRET_KEY'] = 'secret-key-for-hillside-automation'
|
| 22 |
FRONTEND_ORIGIN = os.getenv('FRONTEND_URL', 'https://quantbot.netlify.app')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
CORS(app, resources={r"/*": {"origins": [FRONTEND_ORIGIN, "http://localhost:3000", "http://127.0.0.1:5500", "null"]}})
|
| 24 |
socketio = SocketIO(app, cors_allowed_origins=[FRONTEND_ORIGIN, "http://localhost:3000", "http://127.0.0.1:5500", "null"], async_mode='eventlet')
|
| 25 |
|
|
|
|
|
|
|
| 26 |
bot_instance = None
|
| 27 |
session_data = {}
|
| 28 |
|
| 29 |
+
class HuggingFaceEmailService:
|
| 30 |
def __init__(self):
|
| 31 |
+
self.logger = logging.getLogger('HuggingFaceEmailService')
|
|
|
|
|
|
|
| 32 |
self.sender_email = os.getenv('EMAIL_SENDER')
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
self.logger.info("=== HUGGINGFACE SPACES EMAIL SERVICE ===")
|
| 35 |
+
self.logger.info("β οΈ SMTP BLOCKED: Using HuggingFace-compatible method")
|
| 36 |
self.logger.info(f"EMAIL_SENDER: {self.sender_email}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
+
def create_email_report_html(self, recipients, subject, body, attachments=None):
|
| 39 |
+
"""Create a comprehensive HTML report that can be saved/downloaded"""
|
| 40 |
+
|
| 41 |
+
attachment_content = ""
|
| 42 |
+
if attachments:
|
| 43 |
+
attachment_content = "<h2>π Report Data</h2>"
|
| 44 |
+
for filename, content in attachments.items():
|
| 45 |
+
# Convert CSV to HTML table for better presentation
|
| 46 |
+
if filename.endswith('.csv'):
|
| 47 |
+
try:
|
| 48 |
+
df = pd.read_csv(io.StringIO(content))
|
| 49 |
+
table_html = df.to_html(classes='report-table', index=False, escape=False)
|
| 50 |
+
attachment_content += f"""
|
| 51 |
+
<div class="attachment-section">
|
| 52 |
+
<h3>π {filename}</h3>
|
| 53 |
+
<div class="csv-table">
|
| 54 |
+
{table_html}
|
| 55 |
+
</div>
|
| 56 |
+
<details>
|
| 57 |
+
<summary>Raw CSV Data (Click to expand)</summary>
|
| 58 |
+
<pre class="csv-raw">{content}</pre>
|
| 59 |
+
</details>
|
| 60 |
+
</div>
|
| 61 |
+
"""
|
| 62 |
+
except:
|
| 63 |
+
attachment_content += f"""
|
| 64 |
+
<div class="attachment-section">
|
| 65 |
+
<h3>π {filename}</h3>
|
| 66 |
+
<pre class="csv-raw">{content}</pre>
|
| 67 |
+
</div>
|
| 68 |
+
"""
|
| 69 |
+
else:
|
| 70 |
+
attachment_content += f"""
|
| 71 |
+
<div class="attachment-section">
|
| 72 |
+
<h3>π {filename}</h3>
|
| 73 |
+
<pre>{content}</pre>
|
| 74 |
+
</div>
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
full_html = f"""
|
| 78 |
+
<!DOCTYPE html>
|
| 79 |
+
<html lang="en">
|
| 80 |
+
<head>
|
| 81 |
+
<meta charset="UTF-8">
|
| 82 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 83 |
+
<title>{subject}</title>
|
| 84 |
+
<style>
|
| 85 |
+
body {{
|
| 86 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
| 87 |
+
line-height: 1.6;
|
| 88 |
+
color: #333;
|
| 89 |
+
max-width: 1200px;
|
| 90 |
+
margin: 0 auto;
|
| 91 |
+
padding: 20px;
|
| 92 |
+
background: #f5f5f5;
|
| 93 |
+
}}
|
| 94 |
+
.email-container {{
|
| 95 |
+
background: white;
|
| 96 |
+
border-radius: 12px;
|
| 97 |
+
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
|
| 98 |
+
overflow: hidden;
|
| 99 |
+
}}
|
| 100 |
+
.email-header {{
|
| 101 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 102 |
+
color: white;
|
| 103 |
+
padding: 30px;
|
| 104 |
+
text-align: center;
|
| 105 |
+
}}
|
| 106 |
+
.email-body {{ padding: 30px; }}
|
| 107 |
+
.recipients {{
|
| 108 |
+
background: #e8f4fd;
|
| 109 |
+
padding: 15px;
|
| 110 |
+
border-radius: 8px;
|
| 111 |
+
margin: 20px 0;
|
| 112 |
+
border-left: 4px solid #0066cc;
|
| 113 |
+
}}
|
| 114 |
+
.attachment-section {{
|
| 115 |
+
margin: 25px 0;
|
| 116 |
+
padding: 20px;
|
| 117 |
+
background: #f8f9fa;
|
| 118 |
+
border-radius: 8px;
|
| 119 |
+
border: 1px solid #e9ecef;
|
| 120 |
+
}}
|
| 121 |
+
.report-table {{
|
| 122 |
+
width: 100%;
|
| 123 |
+
border-collapse: collapse;
|
| 124 |
+
margin: 15px 0;
|
| 125 |
+
font-size: 14px;
|
| 126 |
+
}}
|
| 127 |
+
.report-table th, .report-table td {{
|
| 128 |
+
border: 1px solid #ddd;
|
| 129 |
+
padding: 12px 8px;
|
| 130 |
+
text-align: left;
|
| 131 |
+
}}
|
| 132 |
+
.report-table th {{
|
| 133 |
+
background: #667eea;
|
| 134 |
+
color: white;
|
| 135 |
+
font-weight: 600;
|
| 136 |
+
}}
|
| 137 |
+
.report-table tr:nth-child(even) {{ background: #f8f9fa; }}
|
| 138 |
+
.csv-raw {{
|
| 139 |
+
background: #2d3748;
|
| 140 |
+
color: #e2e8f0;
|
| 141 |
+
padding: 15px;
|
| 142 |
+
border-radius: 6px;
|
| 143 |
+
font-family: 'Monaco', 'Consolas', monospace;
|
| 144 |
+
font-size: 12px;
|
| 145 |
+
overflow-x: auto;
|
| 146 |
+
white-space: pre-wrap;
|
| 147 |
+
}}
|
| 148 |
+
.download-section {{
|
| 149 |
+
background: #fff3cd;
|
| 150 |
+
border: 1px solid #ffeaa7;
|
| 151 |
+
padding: 20px;
|
| 152 |
+
border-radius: 8px;
|
| 153 |
+
margin: 20px 0;
|
| 154 |
+
}}
|
| 155 |
+
.hf-notice {{
|
| 156 |
+
background: #d1ecf1;
|
| 157 |
+
border: 1px solid #b6d4db;
|
| 158 |
+
padding: 15px;
|
| 159 |
+
border-radius: 8px;
|
| 160 |
+
margin: 20px 0;
|
| 161 |
+
}}
|
| 162 |
+
details {{ margin: 10px 0; }}
|
| 163 |
+
summary {{
|
| 164 |
+
cursor: pointer;
|
| 165 |
+
padding: 10px;
|
| 166 |
+
background: #e9ecef;
|
| 167 |
+
border-radius: 4px;
|
| 168 |
+
font-weight: 600;
|
| 169 |
+
}}
|
| 170 |
+
.timestamp {{
|
| 171 |
+
text-align: center;
|
| 172 |
+
color: #666;
|
| 173 |
+
font-size: 12px;
|
| 174 |
+
margin-top: 30px;
|
| 175 |
+
padding-top: 20px;
|
| 176 |
+
border-top: 1px solid #eee;
|
| 177 |
+
}}
|
| 178 |
+
@media (max-width: 768px) {{
|
| 179 |
+
body {{ padding: 10px; }}
|
| 180 |
+
.email-header, .email-body {{ padding: 20px; }}
|
| 181 |
+
.report-table {{ font-size: 12px; }}
|
| 182 |
+
.report-table th, .report-table td {{ padding: 8px 4px; }}
|
| 183 |
+
}}
|
| 184 |
+
</style>
|
| 185 |
+
</head>
|
| 186 |
+
<body>
|
| 187 |
+
<div class="email-container">
|
| 188 |
+
<div class="email-header">
|
| 189 |
+
<h1>π€ Hillside's Quantum Automation Report</h1>
|
| 190 |
+
<p>Healthcare Workflow Automation System</p>
|
| 191 |
+
</div>
|
| 192 |
+
|
| 193 |
+
<div class="email-body">
|
| 194 |
+
<div class="hf-notice">
|
| 195 |
+
<h3>π§ Email Delivery Notice</h3>
|
| 196 |
+
<p><strong>Platform:</strong> HuggingFace Spaces</p>
|
| 197 |
+
<p><strong>Limitation:</strong> SMTP ports blocked for security</p>
|
| 198 |
+
<p><strong>Solution:</strong> Complete report generated as downloadable file</p>
|
| 199 |
+
<p><strong>Recipients:</strong> {', '.join(recipients)}</p>
|
| 200 |
+
</div>
|
| 201 |
+
|
| 202 |
+
<div class="recipients">
|
| 203 |
+
<h3>π¬ Email Details</h3>
|
| 204 |
+
<p><strong>To:</strong> {', '.join(recipients)}</p>
|
| 205 |
+
<p><strong>Subject:</strong> {subject}</p>
|
| 206 |
+
<p><strong>Generated:</strong> {datetime.now().strftime('%B %d, %Y at %I:%M %p')}</p>
|
| 207 |
+
</div>
|
| 208 |
+
|
| 209 |
+
<div class="download-section">
|
| 210 |
+
<h3>πΎ How to Access This Report</h3>
|
| 211 |
+
<ol>
|
| 212 |
+
<li><strong>Right-click</strong> on this page β <strong>Save As</strong> β Save as HTML file</li>
|
| 213 |
+
<li><strong>Email the HTML file</strong> to recipients manually</li>
|
| 214 |
+
<li><strong>Share via cloud storage</strong> (Google Drive, Dropbox, etc.)</li>
|
| 215 |
+
<li><strong>Copy data tables</strong> directly from sections below</li>
|
| 216 |
+
</ol>
|
| 217 |
+
</div>
|
| 218 |
+
|
| 219 |
+
{body}
|
| 220 |
+
|
| 221 |
+
{attachment_content}
|
| 222 |
+
|
| 223 |
+
<div class="timestamp">
|
| 224 |
+
<p>π€ Generated by Hillside Automation System on HuggingFace Spaces</p>
|
| 225 |
+
<p>π {datetime.now().strftime('%Y-%m-%d %H:%M:%S UTC')}</p>
|
| 226 |
+
</div>
|
| 227 |
+
</div>
|
| 228 |
+
</div>
|
| 229 |
+
</body>
|
| 230 |
+
</html>
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
return full_html
|
| 234 |
|
| 235 |
+
def send_report(self, recipients, subject, body, attachments=None):
|
| 236 |
+
"""Generate comprehensive report that users can download and share"""
|
| 237 |
+
|
| 238 |
+
self.logger.info("=== GENERATING DOWNLOADABLE EMAIL REPORT ===")
|
| 239 |
+
self.logger.info(f"Recipients: {recipients}")
|
| 240 |
+
self.logger.info(f"Subject: {subject}")
|
| 241 |
+
|
| 242 |
try:
|
| 243 |
+
# Create comprehensive HTML report
|
| 244 |
+
html_report = self.create_email_report_html(recipients, subject, body, attachments)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
|
| 246 |
+
# Save report to accessible location
|
| 247 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 248 |
+
report_filename = f"automation_report_{timestamp}.html"
|
| 249 |
|
| 250 |
+
# Save to app directory (accessible via HuggingFace interface)
|
| 251 |
+
with open(report_filename, 'w', encoding='utf-8') as f:
|
| 252 |
+
f.write(html_report)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
+
self.logger.info(f"β
Report generated: {report_filename}")
|
| 255 |
+
self.logger.info("π§ Users can download and email manually")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
+
# Return success with instructions
|
| 258 |
return True
|
| 259 |
|
| 260 |
except Exception as e:
|
| 261 |
+
self.logger.error(f"β Report generation failed: {e}")
|
| 262 |
return False
|
| 263 |
|
| 264 |
+
# Keep your existing GoogleDriveService but make it optional
|
| 265 |
+
class OptionalCloudStorage:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
def __init__(self):
|
| 267 |
+
self.logger = logging.getLogger('OptionalCloudStorage')
|
| 268 |
+
self.logger.info("π Cloud storage: Optional (reports saved locally)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
def upload_file(self, filename, file_content):
|
| 271 |
+
# Save locally since cloud upload is optional
|
|
|
|
| 272 |
try:
|
| 273 |
+
with open(f"report_{filename}", 'w', encoding='utf-8') as f:
|
| 274 |
+
f.write(file_content)
|
| 275 |
+
self.logger.info(f"πΎ Saved locally: report_{filename}")
|
|
|
|
|
|
|
| 276 |
return True
|
| 277 |
except Exception as e:
|
| 278 |
+
self.logger.error(f"β Local save failed: {e}")
|
| 279 |
return False
|
| 280 |
|
| 281 |
# Initialize services
|
| 282 |
+
email_service = HuggingFaceEmailService()
|
| 283 |
+
storage_service = OptionalCloudStorage()
|
| 284 |
|
| 285 |
def get_email_list():
|
| 286 |
try:
|
|
|
|
| 289 |
logging.info(f"β
Loaded {len(emails)} email addresses")
|
| 290 |
return emails
|
| 291 |
except FileNotFoundError:
|
| 292 |
+
logging.info("β οΈ config/emails.conf not found, using defaults")
|
| 293 |
+
return ['admin@hillsidemedicalgroup.com']
|
| 294 |
|
| 295 |
def run_automation_process(session_id):
|
| 296 |
global bot_instance
|
|
|
|
| 316 |
is_crash = True
|
| 317 |
socketio.emit('error', {'message': f'A fatal error occurred: {e}'})
|
| 318 |
finally:
|
| 319 |
+
socketio.emit('micro_status_update', {'message': 'Generating downloadable report...'})
|
| 320 |
generate_and_send_reports(session_id, results, is_crash_report=is_crash, is_terminated=is_terminated)
|
| 321 |
if bot_instance:
|
| 322 |
bot_instance.shutdown()
|
|
|
|
| 325 |
del session_data[session_id]
|
| 326 |
|
| 327 |
def generate_and_send_reports(session_id, results, is_crash_report=False, is_terminated=False):
|
| 328 |
+
logging.info("=== GENERATING HUGGINGFACE-COMPATIBLE REPORTS ===")
|
| 329 |
|
| 330 |
if not results:
|
| 331 |
+
socketio.emit('process_complete', {'message': 'No patients processed. No report generated.'})
|
| 332 |
return
|
| 333 |
|
| 334 |
data = session_data.get(session_id, {})
|
|
|
|
| 349 |
bad_report_name = f"{custom_name}_Bad.csv"
|
| 350 |
full_report_content = full_df.to_csv(index=False)
|
| 351 |
|
| 352 |
+
# Save files locally (accessible in HuggingFace interface)
|
| 353 |
+
storage_success = storage_service.upload_file(full_report_name, full_report_content)
|
| 354 |
|
| 355 |
+
# Get recipients
|
| 356 |
+
recipients = data.get('emails', get_email_list())
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
status_text = "terminated by user" if is_terminated else "crashed due to an error" if is_crash_report else "completed successfully"
|
| 359 |
subject = f"π€ Automation Report [{status_text.upper()}]: {custom_name}"
|
| 360 |
|
| 361 |
+
# Create comprehensive email body
|
| 362 |
body = f"""
|
| 363 |
+
<div class="report-summary">
|
| 364 |
+
<h2>π Process Summary</h2>
|
| 365 |
+
<div class="stats-grid">
|
| 366 |
+
<div class="stat-item">
|
| 367 |
+
<h3>Process Status</h3>
|
| 368 |
+
<p class="status-{'success' if not is_crash_report else 'error'}">{status_text.title()}</p>
|
| 369 |
+
</div>
|
| 370 |
+
<div class="stat-item">
|
| 371 |
+
<h3>Total Patients</h3>
|
| 372 |
+
<p>{len(full_df)}</p>
|
| 373 |
+
</div>
|
| 374 |
+
<div class="stat-item">
|
| 375 |
+
<h3>Processed</h3>
|
| 376 |
+
<p>{len(results)}</p>
|
| 377 |
+
</div>
|
| 378 |
+
<div class="stat-item success">
|
| 379 |
+
<h3>Successful</h3>
|
| 380 |
+
<p>{len([r for r in results if r['Status'] == 'Done'])}</p>
|
| 381 |
+
</div>
|
| 382 |
+
<div class="stat-item error">
|
| 383 |
+
<h3>Issues</h3>
|
| 384 |
+
<p>{len([r for r in results if r['Status'] == 'Bad'])}</p>
|
| 385 |
+
</div>
|
| 386 |
+
</div>
|
| 387 |
</div>
|
| 388 |
+
|
| 389 |
+
<div class="instructions">
|
| 390 |
+
<h2>π§ Email Delivery Instructions</h2>
|
| 391 |
+
<div class="instruction-box">
|
| 392 |
+
<p><strong>Due to HuggingFace Spaces network restrictions, automatic email sending is not possible.</strong></p>
|
| 393 |
+
<p>This report has been generated as a downloadable HTML file with all your data included.</p>
|
| 394 |
+
|
| 395 |
+
<h3>How to share this report:</h3>
|
| 396 |
+
<ol>
|
| 397 |
+
<li><strong>Download:</strong> Right-click β Save As β Save this page as HTML</li>
|
| 398 |
+
<li><strong>Email manually:</strong> Attach the HTML file to an email</li>
|
| 399 |
+
<li><strong>Cloud sharing:</strong> Upload to Google Drive/Dropbox and share link</li>
|
| 400 |
+
<li><strong>Direct access:</strong> All data tables are included below for copying</li>
|
| 401 |
+
</ol>
|
| 402 |
</div>
|
| 403 |
+
</div>
|
| 404 |
+
|
| 405 |
+
<div class="technical-details">
|
| 406 |
+
<h2>π§ Technical Information</h2>
|
| 407 |
<ul>
|
| 408 |
+
<li><strong>Platform:</strong> HuggingFace Spaces (SMTP-restricted)</li>
|
| 409 |
+
<li><strong>Chrome Automation:</strong> Headless Selenium WebDriver</li>
|
| 410 |
+
<li><strong>Report Generation:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</li>
|
| 411 |
+
<li><strong>Files Generated:</strong> {full_report_name}, {bad_report_name}</li>
|
| 412 |
+
<li><strong>Local Storage:</strong> Files saved in Space directory</li>
|
| 413 |
</ul>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
</div>
|
| 415 |
+
"""
|
| 416 |
|
| 417 |
+
# Add CSS for styling
|
| 418 |
+
body = f"""
|
| 419 |
+
<style>
|
| 420 |
+
.report-summary {{ margin: 20px 0; }}
|
| 421 |
+
.stats-grid {{
|
| 422 |
+
display: grid;
|
| 423 |
+
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
| 424 |
+
gap: 15px;
|
| 425 |
+
margin: 20px 0;
|
| 426 |
+
}}
|
| 427 |
+
.stat-item {{
|
| 428 |
+
background: #f8f9fa;
|
| 429 |
+
padding: 20px;
|
| 430 |
+
border-radius: 8px;
|
| 431 |
+
text-align: center;
|
| 432 |
+
border: 2px solid #e9ecef;
|
| 433 |
+
}}
|
| 434 |
+
.stat-item h3 {{ margin: 0 0 10px 0; color: #495057; }}
|
| 435 |
+
.stat-item p {{ font-size: 24px; font-weight: bold; margin: 0; }}
|
| 436 |
+
.stat-item.success {{ border-color: #28a745; }}
|
| 437 |
+
.stat-item.success p {{ color: #28a745; }}
|
| 438 |
+
.stat-item.error {{ border-color: #dc3545; }}
|
| 439 |
+
.stat-item.error p {{ color: #dc3545; }}
|
| 440 |
+
.status-success {{ color: #28a745; font-weight: bold; }}
|
| 441 |
+
.status-error {{ color: #dc3545; font-weight: bold; }}
|
| 442 |
+
.instructions {{ margin: 30px 0; }}
|
| 443 |
+
.instruction-box {{
|
| 444 |
+
background: #fff3cd;
|
| 445 |
+
border: 1px solid #ffeaa7;
|
| 446 |
+
padding: 20px;
|
| 447 |
+
border-radius: 8px;
|
| 448 |
+
}}
|
| 449 |
+
.technical-details {{ margin: 30px 0; }}
|
| 450 |
+
.technical-details ul {{ list-style-type: none; padding: 0; }}
|
| 451 |
+
.technical-details li {{
|
| 452 |
+
padding: 8px 15px;
|
| 453 |
+
background: #e9ecef;
|
| 454 |
+
margin: 5px 0;
|
| 455 |
+
border-radius: 4px;
|
| 456 |
+
}}
|
| 457 |
+
</style>
|
| 458 |
+
{body}
|
| 459 |
"""
|
| 460 |
|
| 461 |
attachments = {
|
|
|
|
| 463 |
bad_report_name: bad_df.to_csv(index=False)
|
| 464 |
}
|
| 465 |
|
| 466 |
+
# Generate report (this creates downloadable HTML file)
|
| 467 |
+
report_success = email_service.send_report(recipients, subject, body, attachments)
|
| 468 |
|
| 469 |
+
if report_success:
|
| 470 |
+
final_message = f'β
Report generated! Download the HTML file to share via email.'
|
| 471 |
else:
|
| 472 |
+
final_message = f'β Report generation failed!'
|
| 473 |
|
| 474 |
socketio.emit('process_complete', {'message': final_message})
|
| 475 |
logging.info(f"=== FINAL RESULT: {final_message} ===")
|
| 476 |
|
| 477 |
+
# Your existing socketio handlers remain the same...
|
| 478 |
@app.route('/')
|
| 479 |
def status_page():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 480 |
APP_STATUS_HTML = f"""
|
| 481 |
<!DOCTYPE html>
|
| 482 |
<html>
|
| 483 |
<head>
|
| 484 |
+
<title>π€ Hillside Automation - HuggingFace Mode</title>
|
| 485 |
<style>
|
| 486 |
+
body {{
|
| 487 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 488 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 489 |
+
color: white;
|
| 490 |
+
padding: 20px;
|
| 491 |
+
min-height: 100vh;
|
| 492 |
+
}}
|
| 493 |
+
.container {{ max-width: 900px; margin: 0 auto; }}
|
| 494 |
.header {{ text-align: center; margin-bottom: 30px; }}
|
| 495 |
+
.status-box {{
|
| 496 |
+
background: rgba(255,255,255,0.1);
|
| 497 |
+
border-radius: 12px;
|
| 498 |
+
padding: 25px;
|
| 499 |
+
backdrop-filter: blur(10px);
|
| 500 |
+
margin: 20px 0;
|
| 501 |
+
}}
|
| 502 |
+
.limitation-notice {{
|
| 503 |
+
background: rgba(255, 193, 7, 0.2);
|
| 504 |
+
border: 2px solid #ffc107;
|
| 505 |
+
border-radius: 8px;
|
| 506 |
+
padding: 20px;
|
| 507 |
+
margin: 20px 0;
|
| 508 |
+
}}
|
| 509 |
+
.success {{ color: #4ade80; }}
|
| 510 |
+
.warning {{ color: #fbbf24; }}
|
| 511 |
+
.error {{ color: #f87171; }}
|
| 512 |
</style>
|
| 513 |
</head>
|
| 514 |
<body>
|
| 515 |
<div class="container">
|
| 516 |
<div class="header">
|
| 517 |
<h1>π€ Hillside Quantum Automation</h1>
|
| 518 |
+
<h2>HuggingFace Spaces Edition</h2>
|
| 519 |
</div>
|
| 520 |
|
| 521 |
+
<div class="limitation-notice">
|
| 522 |
+
<h3>β οΈ Platform Limitations</h3>
|
| 523 |
+
<p><strong>SMTP Status:</strong> <span class="error">Blocked by HuggingFace Spaces</span></p>
|
| 524 |
+
<p><strong>Email Solution:</strong> <span class="success">Downloadable HTML reports</span></p>
|
| 525 |
+
<p><strong>Network Ports:</strong> Only 80, 443 allowed (587 blocked)</p>
|
| 526 |
+
</div>
|
| 527 |
+
|
| 528 |
+
<div class="status-box">
|
| 529 |
+
<h3>π§ System Status</h3>
|
| 530 |
+
<p>Chrome WebDriver: <span class="success">β
Ready</span></p>
|
| 531 |
+
<p>Report Generation: <span class="success">β
Active</span></p>
|
| 532 |
+
<p>HTML Export: <span class="success">β
Enabled</span></p>
|
| 533 |
+
<p>Auto Email: <span class="error">β Not possible on HF Spaces</span></p>
|
|
|
|
|
|
|
|
|
|
| 534 |
</div>
|
| 535 |
|
| 536 |
<div class="status-box">
|
| 537 |
+
<h3>π§ Email Workflow</h3>
|
| 538 |
+
<ol>
|
| 539 |
+
<li>β
Automation runs successfully</li>
|
| 540 |
+
<li>β
Comprehensive HTML report generated</li>
|
| 541 |
+
<li>π₯ Download report from Space interface</li>
|
| 542 |
+
<li>π§ Manually email to recipients</li>
|
| 543 |
+
</ol>
|
| 544 |
</div>
|
| 545 |
|
| 546 |
+
<div class="status-box">
|
| 547 |
+
<h3>π Links</h3>
|
| 548 |
+
<p>Frontend: <a href="https://quantbot.netlify.app" style="color: #60a5fa;">quantbot.netlify.app</a></p>
|
| 549 |
+
<p>Platform: HuggingFace Spaces</p>
|
| 550 |
+
<p>Mode: SMTP-Free with downloadable reports</p>
|
| 551 |
</div>
|
| 552 |
</div>
|
| 553 |
</body>
|
|
|
|
| 555 |
"""
|
| 556 |
return Response(APP_STATUS_HTML)
|
| 557 |
|
| 558 |
+
# Keep all your existing socketio handlers unchanged...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 559 |
@socketio.on('connect')
|
| 560 |
def handle_connect():
|
| 561 |
logging.info('Frontend connected')
|
|
|
|
| 571 |
'filename': data['filename']
|
| 572 |
}
|
| 573 |
|
|
|
|
|
|
|
| 574 |
if bot_instance:
|
| 575 |
bot_instance.shutdown()
|
| 576 |
bot_instance = QuantumBot(socketio, app)
|
|
|
|
| 611 |
|
| 612 |
if __name__ == '__main__':
|
| 613 |
print("====================================================================")
|
| 614 |
+
print(" π€ HILLSIDE AUTOMATION - HUGGINGFACE SPACES EDITION")
|
| 615 |
+
print(" π§ Email: Downloadable HTML reports (SMTP blocked)")
|
| 616 |
+
print(" π Network: Ports 587/465 blocked by platform")
|
| 617 |
+
print(" πΎ Reports: Saved locally, download manually")
|
| 618 |
+
print(" β
Status: FULLY FUNCTIONAL WITHIN HF CONSTRAINTS")
|
| 619 |
print("====================================================================")
|
| 620 |
socketio.run(app, host='0.0.0.0', port=int(os.getenv('PORT', 7860)))
|