DevNumb commited on
Commit
1fcffd0
Β·
verified Β·
1 Parent(s): cb8f6e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -20
app.py CHANGED
@@ -5,15 +5,27 @@ import base64
5
  from PIL import Image
6
  import io
7
  import datetime
 
 
 
8
 
9
  # Configuration from environment variables
10
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
11
  DEFAULT_REPORT_EMAIL = os.getenv("REPORT_EMAIL")
12
- BREVO_API_KEY = os.getenv("BREVO_API_KEY")
 
 
 
 
 
13
  BREVO_FROM_EMAIL = os.getenv("BREVO_FROM_EMAIL", "noreply@yourdomain.com")
14
 
 
 
 
15
  # Testing/Demo Mode Configuration
16
- DEMO_MODE = os.getenv("DEMO_MODE", "true").lower() == "true" # Enable demo mode by default
 
17
 
18
  # Store conversation history and settings
19
  conversation_history = []
@@ -23,17 +35,17 @@ current_report_email = DEFAULT_REPORT_EMAIL
23
  departments = {
24
  "administration": {
25
  "name": "Administration",
26
- "email": os.getenv("ADMIN_EMAIL", "nahdi.hassene34+admin@gmail.com"),
27
  "responsibilities": "Overall management, decision making, and coordination"
28
  },
29
  "production": {
30
  "name": "Production",
31
- "email": os.getenv("PRODUCTION_EMAIL", "nahdi.hassene34+production@gmail.com"),
32
  "responsibilities": "Manufacturing, quality control, and production planning"
33
  },
34
  "magazine": {
35
  "name": "Magazine Management",
36
- "email": os.getenv("MAGAZINE_EMAIL", "nahdi.hassene34+magazine@demo.com"),
37
  "responsibilities": "Content creation, publishing, and distribution"
38
  }
39
  }
@@ -47,12 +59,38 @@ def update_report_email(new_email):
47
  else:
48
  return "❌ Please enter a valid email address"
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordination System"):
51
  """Send email using Brevo API"""
52
  try:
53
- # Demo mode: simulate email sending
54
- if DEMO_MODE or not BREVO_API_KEY:
55
- return f"πŸ§ͺ [DEMO MODE] Email simulated to {to_email}"
56
 
57
  response = requests.post(
58
  "https://api.brevo.com/v3/smtp/email",
@@ -74,13 +112,33 @@ def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordina
74
  )
75
 
76
  if response.status_code == 201:
77
- return f"βœ… Email sent to {to_email}"
78
  else:
79
  error_msg = response.json().get('message', 'Unknown error')
80
  return f"❌ Failed to send email: {error_msg}"
81
 
82
  except Exception as e:
83
- return f"❌ Email error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  def get_mock_ai_response(user_message, department, user_name, has_image=False):
86
  """Generate a mock AI response for demo/testing mode"""
@@ -473,9 +531,9 @@ def send_department_email(sender_dept, recipient_dept, subject, message, user_na
473
  </body>
474
  </html>"""
475
 
476
- # Send email using Brevo API
477
  from_name = f"{departments[sender_dept]['name']}"
478
- email_status = send_email_brevo_api(recipient_email, f"[{urgency}] {subject}", html_content, from_name)
479
  return email_status
480
 
481
  except Exception as e:
@@ -484,11 +542,14 @@ def send_department_email(sender_dept, recipient_dept, subject, message, user_na
484
  def send_email_report(conversation_data):
485
  """Send comprehensive coordination report to administration"""
486
  # Demo mode check
487
- if DEMO_MODE or not BREVO_API_KEY or not current_report_email:
488
- if DEMO_MODE:
489
- return "πŸ§ͺ [DEMO MODE] Report email simulated successfully"
490
- else:
491
- return "Email reporting not configured - missing Brevo API key or report email"
 
 
 
492
 
493
  try:
494
  # Calculate department activity
@@ -590,8 +651,8 @@ def send_email_report(conversation_data):
590
  </body>
591
  </html>"""
592
 
593
- # Send email using Brevo API
594
- email_status = send_email_brevo_api(current_report_email, subject, html_content, "AI Coordination System")
595
  return email_status
596
 
597
  except Exception as e:
@@ -768,7 +829,15 @@ def get_system_status():
768
  status_lines.append("**System Configuration:**")
769
  status_lines.append(f"β€’ Demo Mode: {'πŸ§ͺ ENABLED' if DEMO_MODE else 'βœ… DISABLED'}")
770
  status_lines.append(f"β€’ OpenRouter API: {'βœ… Configured' if OPENROUTER_API_KEY else '❌ Not configured (using demo)'}")
771
- status_lines.append(f"β€’ Brevo Email API: {'βœ… Configured' if BREVO_API_KEY else '❌ Not configured (simulated)'}")
 
 
 
 
 
 
 
 
772
  status_lines.append(f"β€’ Report Email: {current_report_email if current_report_email else '❌ Not set'}")
773
  return "\n".join(status_lines)
774
 
 
5
  from PIL import Image
6
  import io
7
  import datetime
8
+ import smtplib
9
+ from email.mime.text import MIMEText
10
+ from email.mime.multipart import MIMEMultipart
11
 
12
  # Configuration from environment variables
13
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
14
  DEFAULT_REPORT_EMAIL = os.getenv("REPORT_EMAIL")
15
+
16
+ # Email configuration - SMTP
17
+ BREVO_SMTP_SERVER = os.getenv("BREVO_SMTP_SERVER")
18
+ BREVO_SMTP_PORT = int(os.getenv("BREVO_SMTP_PORT", "587"))
19
+ BREVO_SMTP_USERNAME = os.getenv("BREVO_SMTP_USERNAME")
20
+ BREVO_SMTP_PASSWORD = os.getenv("BREVO_SMTP_PASSWORD")
21
  BREVO_FROM_EMAIL = os.getenv("BREVO_FROM_EMAIL", "noreply@yourdomain.com")
22
 
23
+ # Email configuration - API (fallback)
24
+ BREVO_API_KEY = os.getenv("BREVO_API_KEY")
25
+
26
  # Testing/Demo Mode Configuration
27
+ # Disable demo mode if SMTP or API is configured
28
+ DEMO_MODE = os.getenv("DEMO_MODE", "false").lower() == "true" if (BREVO_SMTP_SERVER or BREVO_API_KEY) else True
29
 
30
  # Store conversation history and settings
31
  conversation_history = []
 
35
  departments = {
36
  "administration": {
37
  "name": "Administration",
38
+ "email": os.getenv("ADMIN_EMAIL", "admin@demo.com"),
39
  "responsibilities": "Overall management, decision making, and coordination"
40
  },
41
  "production": {
42
  "name": "Production",
43
+ "email": os.getenv("PRODUCTION_EMAIL", "production@demo.com"),
44
  "responsibilities": "Manufacturing, quality control, and production planning"
45
  },
46
  "magazine": {
47
  "name": "Magazine Management",
48
+ "email": os.getenv("MAGAZINE_EMAIL", "magazine@demo.com"),
49
  "responsibilities": "Content creation, publishing, and distribution"
50
  }
51
  }
 
59
  else:
60
  return "❌ Please enter a valid email address"
61
 
62
+ def send_email_smtp(to_email, subject, html_content, from_name="AI Coordination System"):
63
+ """Send email using SMTP"""
64
+ try:
65
+ if not all([BREVO_SMTP_SERVER, BREVO_SMTP_USERNAME, BREVO_SMTP_PASSWORD]):
66
+ return "❌ SMTP not configured - missing server, username, or password"
67
+
68
+ # Create message
69
+ msg = MIMEMultipart('alternative')
70
+ msg['Subject'] = subject
71
+ msg['From'] = f"{from_name} <{BREVO_FROM_EMAIL}>"
72
+ msg['To'] = to_email
73
+
74
+ # Attach HTML content
75
+ html_part = MIMEText(html_content, 'html')
76
+ msg.attach(html_part)
77
+
78
+ # Send email
79
+ with smtplib.SMTP(BREVO_SMTP_SERVER, BREVO_SMTP_PORT) as server:
80
+ server.starttls()
81
+ server.login(BREVO_SMTP_USERNAME, BREVO_SMTP_PASSWORD)
82
+ server.send_message(msg)
83
+
84
+ return f"βœ… Email sent to {to_email} (via SMTP)"
85
+
86
+ except Exception as e:
87
+ return f"❌ SMTP error: {str(e)}"
88
+
89
  def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordination System"):
90
  """Send email using Brevo API"""
91
  try:
92
+ if not BREVO_API_KEY:
93
+ return "❌ Brevo API not configured"
 
94
 
95
  response = requests.post(
96
  "https://api.brevo.com/v3/smtp/email",
 
112
  )
113
 
114
  if response.status_code == 201:
115
+ return f"βœ… Email sent to {to_email} (via API)"
116
  else:
117
  error_msg = response.json().get('message', 'Unknown error')
118
  return f"❌ Failed to send email: {error_msg}"
119
 
120
  except Exception as e:
121
+ return f"❌ Email API error: {str(e)}"
122
+
123
+ def send_email(to_email, subject, html_content, from_name="AI Coordination System"):
124
+ """Send email using available method (SMTP or API)"""
125
+ # Demo mode: simulate email sending
126
+ if DEMO_MODE:
127
+ return f"πŸ§ͺ [DEMO MODE] Email simulated to {to_email}"
128
+
129
+ # Try SMTP first (preferred)
130
+ if BREVO_SMTP_SERVER:
131
+ result = send_email_smtp(to_email, subject, html_content, from_name)
132
+ # If SMTP fails, try API as fallback
133
+ if "❌" in result and BREVO_API_KEY:
134
+ return send_email_brevo_api(to_email, subject, html_content, from_name)
135
+ return result
136
+
137
+ # Fall back to API if SMTP not configured
138
+ if BREVO_API_KEY:
139
+ return send_email_brevo_api(to_email, subject, html_content, from_name)
140
+
141
+ return "❌ No email service configured (need SMTP or API credentials)"
142
 
143
  def get_mock_ai_response(user_message, department, user_name, has_image=False):
144
  """Generate a mock AI response for demo/testing mode"""
 
531
  </body>
532
  </html>"""
533
 
534
+ # Send email using SMTP or API
535
  from_name = f"{departments[sender_dept]['name']}"
536
+ email_status = send_email(recipient_email, f"[{urgency}] {subject}", html_content, from_name)
537
  return email_status
538
 
539
  except Exception as e:
 
542
  def send_email_report(conversation_data):
543
  """Send comprehensive coordination report to administration"""
544
  # Demo mode check
545
+ if DEMO_MODE:
546
+ return "πŸ§ͺ [DEMO MODE] Report email simulated successfully"
547
+
548
+ if not current_report_email:
549
+ return "❌ Report email not configured - please set report email address"
550
+
551
+ if not (BREVO_SMTP_SERVER or BREVO_API_KEY):
552
+ return "❌ Email service not configured - need SMTP or API credentials"
553
 
554
  try:
555
  # Calculate department activity
 
651
  </body>
652
  </html>"""
653
 
654
+ # Send email using SMTP or API
655
+ email_status = send_email(current_report_email, subject, html_content, "AI Coordination System")
656
  return email_status
657
 
658
  except Exception as e:
 
829
  status_lines.append("**System Configuration:**")
830
  status_lines.append(f"β€’ Demo Mode: {'πŸ§ͺ ENABLED' if DEMO_MODE else 'βœ… DISABLED'}")
831
  status_lines.append(f"β€’ OpenRouter API: {'βœ… Configured' if OPENROUTER_API_KEY else '❌ Not configured (using demo)'}")
832
+
833
+ # Email configuration status
834
+ if BREVO_SMTP_SERVER:
835
+ status_lines.append(f"β€’ Email (SMTP): βœ… Configured ({BREVO_SMTP_SERVER}:{BREVO_SMTP_PORT})")
836
+ elif BREVO_API_KEY:
837
+ status_lines.append(f"β€’ Email (API): βœ… Configured")
838
+ else:
839
+ status_lines.append(f"β€’ Email: ❌ Not configured (simulated)")
840
+
841
  status_lines.append(f"β€’ Report Email: {current_report_email if current_report_email else '❌ Not set'}")
842
  return "\n".join(status_lines)
843