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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -86
app.py CHANGED
@@ -5,27 +5,16 @@ import base64
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 = []
@@ -59,38 +48,12 @@ def update_report_email(new_email):
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,33 +75,13 @@ def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordina
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"""
@@ -391,17 +334,19 @@ Monitoring or escalation steps
391
  ],
392
  "temperature": 0.3
393
  },
394
- timeout=60
395
  )
396
 
397
  if response.status_code == 200:
398
  data = response.json()
399
  return data["choices"][0]["message"]["content"]
400
  else:
401
- return "I'm having trouble analyzing the image right now. Please try again in a moment."
 
402
 
403
  except Exception as e:
404
- return f"Sorry, I couldn't process the image. Error: {str(e)}"
 
405
 
406
  else:
407
  # Text-only analysis
@@ -464,17 +409,19 @@ Required monitoring or reporting actions
464
  "messages": [{"role": "user", "content": prompt}],
465
  "temperature": 0.3
466
  },
467
- timeout=30
468
  )
469
 
470
  if response.status_code == 200:
471
  data = response.json()
472
  return data["choices"][0]["message"]["content"]
473
  else:
474
- return "I'm having trouble analyzing your request right now. Please try again in a moment."
 
475
 
476
  except Exception as e:
477
- return f"Sorry, I couldn't process your request. Error: {str(e)}"
 
478
 
479
  def send_department_email(sender_dept, recipient_dept, subject, message, user_name, urgency="Normal", image=None):
480
  """Send email between departments with optional image attachment"""
@@ -542,15 +489,12 @@ def send_department_email(sender_dept, recipient_dept, subject, message, user_na
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
556
  dept_activity = {}
@@ -829,15 +773,7 @@ def get_system_status():
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
 
@@ -1063,4 +999,4 @@ with gr.Blocks(
1063
  )
1064
 
1065
  if __name__ == "__main__":
1066
- ui.launch(share=True)
 
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
+ # Auto-disable demo mode if API key is configured
17
+ DEMO_MODE = os.getenv("DEMO_MODE", "false").lower() == "true" if BREVO_API_KEY else True
18
 
19
  # Store conversation history and settings
20
  conversation_history = []
 
48
  else:
49
  return "❌ Please enter a valid email address"
50
 
51
+ def send_email(to_email, subject, html_content, from_name="AI Coordination System"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  """Send email using Brevo API"""
53
  try:
54
+ # Demo mode: simulate email sending
55
+ if DEMO_MODE or not BREVO_API_KEY:
56
+ return f"πŸ§ͺ [DEMO MODE] Email simulated to {to_email}"
57
 
58
  response = requests.post(
59
  "https://api.brevo.com/v3/smtp/email",
 
75
  )
76
 
77
  if response.status_code == 201:
78
+ return f"βœ… Email sent to {to_email}"
79
  else:
80
  error_msg = response.json().get('message', 'Unknown error')
81
  return f"❌ Failed to send email: {error_msg}"
82
 
83
  except Exception as e:
84
+ return f"❌ Email error: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  def get_mock_ai_response(user_message, department, user_name, has_image=False):
87
  """Generate a mock AI response for demo/testing mode"""
 
334
  ],
335
  "temperature": 0.3
336
  },
337
+ timeout=30 # Reduced from 60 seconds
338
  )
339
 
340
  if response.status_code == 200:
341
  data = response.json()
342
  return data["choices"][0]["message"]["content"]
343
  else:
344
+ # Fallback to mock response if API fails
345
+ return get_mock_ai_response(user_message, department, user_name, has_image=True)
346
 
347
  except Exception as e:
348
+ # Fallback to mock response on error
349
+ return get_mock_ai_response(user_message, department, user_name, has_image=True)
350
 
351
  else:
352
  # Text-only analysis
 
409
  "messages": [{"role": "user", "content": prompt}],
410
  "temperature": 0.3
411
  },
412
+ timeout=20 # Reduced from 30 seconds
413
  )
414
 
415
  if response.status_code == 200:
416
  data = response.json()
417
  return data["choices"][0]["message"]["content"]
418
  else:
419
+ # Fallback to mock response if API fails
420
+ return get_mock_ai_response(user_message, department, user_name, has_image=False)
421
 
422
  except Exception as e:
423
+ # Fallback to mock response on error
424
+ return get_mock_ai_response(user_message, department, user_name, has_image=False)
425
 
426
  def send_department_email(sender_dept, recipient_dept, subject, message, user_name, urgency="Normal", image=None):
427
  """Send email between departments with optional image attachment"""
 
489
  def send_email_report(conversation_data):
490
  """Send comprehensive coordination report to administration"""
491
  # Demo mode check
492
+ if DEMO_MODE or not BREVO_API_KEY:
493
  return "πŸ§ͺ [DEMO MODE] Report email simulated successfully"
494
 
495
  if not current_report_email:
496
  return "❌ Report email not configured - please set report email address"
497
 
 
 
 
498
  try:
499
  # Calculate department activity
500
  dept_activity = {}
 
773
  status_lines.append("**System Configuration:**")
774
  status_lines.append(f"β€’ Demo Mode: {'πŸ§ͺ ENABLED' if DEMO_MODE else 'βœ… DISABLED'}")
775
  status_lines.append(f"β€’ OpenRouter API: {'βœ… Configured' if OPENROUTER_API_KEY else '❌ Not configured (using demo)'}")
776
+ status_lines.append(f"β€’ Brevo Email API: {'βœ… Configured' if BREVO_API_KEY else '❌ Not configured (simulated)'}")
 
 
 
 
 
 
 
 
777
  status_lines.append(f"β€’ Report Email: {current_report_email if current_report_email else '❌ Not set'}")
778
  return "\n".join(status_lines)
779
 
 
999
  )
1000
 
1001
  if __name__ == "__main__":
1002
+ ui.launch(share=True)