DevNumb commited on
Commit
23398ed
Β·
verified Β·
1 Parent(s): a666207

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -593
app.py CHANGED
@@ -5,46 +5,17 @@ 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
- import ssl
12
 
13
- # Configuration from environment variables
14
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
15
- DEFAULT_REPORT_EMAIL = os.getenv("REPORT_EMAIL")
 
16
 
17
- # Brevo SMTP Configuration
18
- BREVO_SMTP_SERVER = os.getenv("BREVO_SMTP_SERVER", "smtp-relay.brevo.com")
19
- BREVO_SMTP_PORT = int(os.getenv("BREVO_SMTP_PORT", "587")) # Convert to integer
20
- BREVO_SMTP_USERNAME = os.getenv("BREVO_SMTP_USERNAME")
21
- BREVO_SMTP_PASSWORD = os.getenv("BREVO_SMTP_PASSWORD")
22
-
23
- # Store conversation history and settings
24
  conversation_history = []
25
- current_report_email = DEFAULT_REPORT_EMAIL
26
-
27
- # Department configurations
28
- departments = {
29
- "administration": {
30
- "name": "Administration",
31
- "email": os.getenv("ADMIN_EMAIL", ""),
32
- "responsibilities": "Overall management, decision making, and coordination"
33
- },
34
- "production": {
35
- "name": "Production",
36
- "email": os.getenv("PRODUCTION_EMAIL", ""),
37
- "responsibilities": "Manufacturing, quality control, and production planning"
38
- },
39
- "magazine": {
40
- "name": "Magazine Management",
41
- "email": os.getenv("MAGAZINE_EMAIL", ""),
42
- "responsibilities": "Content creation, publishing, and distribution"
43
- }
44
- }
45
 
46
  def update_report_email(new_email):
47
- """Update the report email address"""
48
  global current_report_email
49
  if new_email and "@" in new_email and "." in new_email:
50
  current_report_email = new_email.strip()
@@ -52,629 +23,192 @@ def update_report_email(new_email):
52
  else:
53
  return "❌ Please enter a valid email address"
54
 
55
- def send_email_smtp(to_email, subject, html_content, from_name="AI Coordination System"):
56
- """Send email using Brevo SMTP with multiple fallback options"""
57
  try:
58
- if not BREVO_SMTP_USERNAME or not BREVO_SMTP_PASSWORD:
59
- return "❌ Email not configured - missing Brevo SMTP credentials"
60
-
61
- # Create message
62
- msg = MIMEMultipart()
63
- msg['From'] = f"{from_name} <{BREVO_SMTP_USERNAME}>"
64
- msg['To'] = to_email
65
- msg['Subject'] = subject
66
-
67
- # Add HTML content
68
- msg.attach(MIMEText(html_content, 'html'))
69
-
70
- # Try different connection methods
71
- success = False
72
- error_messages = []
73
-
74
- # Method 1: Try TLS on port 587
75
- try:
76
- context = ssl.create_default_context()
77
- with smtplib.SMTP(BREVO_SMTP_SERVER, BREVO_SMTP_PORT) as server:
78
- server.starttls(context=context)
79
- server.login(BREVO_SMTP_USERNAME, BREVO_SMTP_PASSWORD)
80
- server.send_message(msg)
81
- success = True
82
- except Exception as e1:
83
- error_messages.append(f"TLS method failed: {str(e1)}")
84
-
85
- # Method 2: Try SSL on port 465
86
- try:
87
- context = ssl.create_default_context()
88
- with smtplib.SMTP_SSL(BREVO_SMTP_SERVER, 465, context=context) as server:
89
- server.login(BREVO_SMTP_USERNAME, BREVO_SMTP_PASSWORD)
90
- server.send_message(msg)
91
- success = True
92
- except Exception as e2:
93
- error_messages.append(f"SSL method failed: {str(e2)}")
94
-
95
- # Method 3: Try without TLS (not recommended but might work)
96
- try:
97
- with smtplib.SMTP(BREVO_SMTP_SERVER, BREVO_SMTP_PORT) as server:
98
- server.login(BREVO_SMTP_USERNAME, BREVO_SMTP_PASSWORD)
99
- server.send_message(msg)
100
- success = True
101
- except Exception as e3:
102
- error_messages.append(f"Plain method failed: {str(e3)}")
103
-
104
- if success:
105
  return f"βœ… Email sent to {to_email}"
106
  else:
107
- return f"❌ All SMTP methods failed. Errors: {' | '.join(error_messages)}"
108
-
 
109
  except Exception as e:
110
- return f"❌ SMTP connection error: {str(e)}"
111
 
112
  def analyze_coordination_needs(user_message, department, user_name, image=None):
113
- """Use LLM to analyze coordination needs and suggest actions - with image support"""
114
-
115
  if image:
116
- # Convert image to base64 for vision model
117
  buffered = io.BytesIO()
118
  image.save(buffered, format="PNG")
119
  img_base64 = base64.b64encode(buffered.getvalue()).decode()
120
 
121
- prompt = f"""As an AI coordination agent, analyze this message from {user_name} in the {department} department.
122
- Also analyze the attached image and provide comprehensive coordination suggestions.
123
-
124
- DEPARTMENT: {department}
125
- REQUESTOR: {user_name}
126
- MESSAGE: {user_message}
127
 
128
- Analyze both the text message and the image to understand:
129
- 1. Which other departments need to be involved?
130
- 2. What specific actions should be taken based on both text and visual information?
131
- 3. What information needs to be shared between departments?
132
- 4. What are the priority levels?
133
- 5. What follow-up is needed?
134
- 6. Any insights from the image that affect coordination?
135
 
136
- Provide a structured response with:
137
- - Coordination needed with: [departments]
138
- - Image analysis insights: [key points from image]
139
- - Recommended actions: [bullet points]
140
- - Priority: [High/Medium/Low]
141
- - Next steps: [suggestions]"""
142
 
143
  try:
144
  response = requests.post(
145
  "https://openrouter.ai/api/v1/chat/completions",
146
- headers={
147
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
148
- "Content-Type": "application/json",
149
- },
150
  json={
151
- "model": "google/gemini-flash-1.5:free", # Vision model
152
- "messages": [
153
- {
154
- "role": "user",
155
- "content": [
156
- {
157
- "type": "text",
158
- "text": prompt
159
- },
160
- {
161
- "type": "image_url",
162
- "image_url": {
163
- "url": f"data:image/png;base64,{img_base64}"
164
- }
165
- }
166
- ]
167
- }
168
- ],
169
- "temperature": 0.3
170
  },
171
- timeout=60
172
  )
173
-
174
  if response.status_code == 200:
175
- data = response.json()
176
- return data["choices"][0]["message"]["content"]
177
- else:
178
- return "AI analysis with image temporarily unavailable."
179
-
180
- except Exception as e:
181
- return f"Image analysis error: {str(e)}"
182
 
183
  else:
184
- # Text-only analysis
185
- prompt = f"""As an AI coordination agent, analyze this message from {user_name} in the {department} department and suggest appropriate actions:
186
-
187
- DEPARTMENT: {department}
188
- REQUESTOR: {user_name}
189
- MESSAGE: {user_message}
190
 
191
- Consider:
192
- 1. Which other departments need to be involved?
193
- 2. What specific actions should be taken?
194
- 3. What information needs to be shared?
195
- 4. What are the priority levels?
196
- 5. What follow-up is needed?
197
 
198
- Provide a structured response with:
199
- - Coordination needed with: [departments]
200
- - Recommended actions: [bullet points]
201
- - Priority: [High/Medium/Low]
202
- - Next steps: [suggestions]"""
203
 
204
  try:
205
  response = requests.post(
206
  "https://openrouter.ai/api/v1/chat/completions",
207
- headers={
208
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
209
- "Content-Type": "application/json",
210
- },
211
  json={
212
- "model": "google/gemma-3-27b-it:free",
213
  "messages": [{"role": "user", "content": prompt}],
214
- "temperature": 0.3
215
  },
216
- timeout=30
217
  )
218
-
219
  if response.status_code == 200:
220
- data = response.json()
221
- return data["choices"][0]["message"]["content"]
222
- else:
223
- return "AI analysis temporarily unavailable."
224
-
225
- except Exception as e:
226
- return f"Analysis error: {str(e)}"
227
-
228
- def send_department_email(sender_dept, recipient_dept, subject, message, user_name, urgency="Normal", image=None):
229
- """Send email between departments with optional image attachment"""
230
- try:
231
- # Determine recipient email
232
- recipient_email = departments[recipient_dept]["email"]
233
- if not recipient_email:
234
- # If no department email configured, use the current report email
235
- recipient_email = current_report_email
236
-
237
- # Create professional email content
238
- image_note = "<p style='margin: 5px 0;'><strong>πŸ“Ž Attachment:</strong> Image included with request</p>" if image else ""
239
- urgency_class = f"urgency-{urgency.lower()}" if urgency.lower() in ['high', 'medium'] else "urgency-normal"
240
- image_footer = "<p><em>Note: An image was included with this request. Please check the original system for image details.</em></p>" if image else ""
241
-
242
- html_content = f"""<html>
243
- <head>
244
- <style>
245
- body {{ font-family: Arial, sans-serif; margin: 20px; }}
246
- .header {{ background-color: #f4f4f4; padding: 20px; border-radius: 8px; margin-bottom: 20px; }}
247
- .urgency-high {{ border-left: 5px solid #dc2626; background-color: #fef2f2; }}
248
- .urgency-medium {{ border-left: 5px solid #d97706; background-color: #fffbeb; }}
249
- .urgency-normal {{ border-left: 5px solid #2563eb; background-color: #eff6ff; }}
250
- .message-content {{ padding: 20px; background-color: white; border-radius: 8px; margin: 15px 0; }}
251
- .user-info {{ background-color: #f8fafc; padding: 10px 15px; border-radius: 6px; margin: 10px 0; }}
252
- </style>
253
- </head>
254
- <body>
255
- <div class="header">
256
- <h1 style="margin: 0; color: #1f2937;">🏒 Inter-Department Communication</h1>
257
- <p style="margin: 5px 0;"><strong>From:</strong> {departments[sender_dept]['name']}</p>
258
- <p style="margin: 5px 0;"><strong>Requested by:</strong> {user_name}</p>
259
- <p style="margin: 5px 0;"><strong>To:</strong> {departments[recipient_dept]['name']}</p>
260
- <p style="margin: 5px 0;"><strong>Date:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
261
- <p style="margin: 5px 0;"><strong>Urgency:</strong> {urgency}</p>
262
- {image_note}
263
- </div>
264
-
265
- <div class="user-info">
266
- <strong>πŸ‘€ Requestor Details:</strong><br>
267
- Name: {user_name}<br>
268
- Department: {departments[sender_dept]['name']}
269
- </div>
270
-
271
- <div class="message-content {urgency_class}">
272
- <h3 style="margin-top: 0;">{subject}</h3>
273
- <div style="white-space: pre-line;">{message}</div>
274
- </div>
275
-
276
- <div style="color: #6b7280; font-size: 0.9em; margin-top: 20px;">
277
- <p>This is an automated message from the AI Coordination System.</p>
278
- {image_footer}
279
- </div>
280
- </body>
281
- </html>"""
282
-
283
- # Send email using Brevo SMTP
284
- from_name = f"{departments[sender_dept]['name']}"
285
- email_status = send_email_smtp(recipient_email, f"[{urgency}] {subject}", html_content, from_name)
286
- return email_status
287
-
288
- except Exception as e:
289
- return f"❌ Failed to send email: {str(e)}"
290
-
291
- def send_email_report(conversation_data):
292
- """Send comprehensive coordination report to administration"""
293
- if not BREVO_SMTP_USERNAME or not BREVO_SMTP_PASSWORD or not current_report_email:
294
- return "Email reporting not configured - missing Brevo credentials or report email"
295
-
296
- try:
297
- # Calculate department activity
298
- dept_activity = {}
299
- user_activity = {}
300
- for entry in conversation_data:
301
- dept = entry.get('department', 'Unknown')
302
- user = entry.get('user_name', 'Unknown')
303
- dept_activity[dept] = dept_activity.get(dept, 0) + 1
304
- user_activity[user] = user_activity.get(user, 0) + 1
305
-
306
- # Format email content
307
- subject = f"Coordination Report - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
308
-
309
- # Create department activity HTML
310
- dept_activity_html = ""
311
- for dept, count in dept_activity.items():
312
- dept_activity_html += f"<p><strong>{dept.title()}:</strong> {count} interactions</p>"
313
-
314
- # Create user activity HTML
315
- user_activity_html = ""
316
- for user, count in user_activity.items():
317
- if user != 'Unknown':
318
- user_activity_html += f"<p><strong>{user}:</strong> {count} requests</p>"
319
-
320
- # Create recent activities HTML
321
- recent_activities_html = ""
322
- for i, entry in enumerate(conversation_data[-10:], 1):
323
- dept_badge = f"<span class='department-badge'>{entry.get('department', 'General').title()}</span>" if entry.get('department') else ""
324
- user_badge = f"<span class='user-badge'>{entry.get('user_name', 'User')}</span>" if entry.get('user_name') else ""
325
- image_indicator = " <span class='image-indicator'>πŸ“·</span>" if entry.get('image_uploaded') else ""
326
- email_indicator = " πŸ“§" if entry.get('email_sent') else ""
327
-
328
- recent_activities_html += f"""<div class="exchange">
329
- <div style="display: flex; justify-content: between; align-items: center; margin-bottom: 10px;">
330
- <h4 style="margin: 0; color: #374151;">Activity #{i}</h4>
331
- <div>
332
- {dept_badge}
333
- {user_badge}
334
- {image_indicator}
335
- </div>
336
- </div>
337
- <p class="user"><strong>πŸ’¬ Message:</strong> {entry['user_input']}{email_indicator}</p>
338
- <p class="ai"><strong>πŸ€– AI Coordination:</strong> {entry['ai_response']}</p>
339
- <p class="timestamp">{entry['timestamp']}</p>
340
- </div>"""
341
-
342
- # Create comprehensive HTML report
343
- html_content = f"""<html>
344
- <head>
345
- <style>
346
- body {{ font-family: Arial, sans-serif; margin: 20px; }}
347
- .header {{ background-color: #1f2937; color: white; padding: 25px; border-radius: 8px; margin-bottom: 20px; }}
348
- .stats {{ display: flex; justify-content: space-between; margin: 20px 0; }}
349
- .stat-card {{ background-color: #f8fafc; padding: 15px; border-radius: 8px; text-align: center; flex: 1; margin: 0 10px; }}
350
- .exchange {{ border: 1px solid #e0e0e0; margin: 15px 0; padding: 15px; border-radius: 8px; background-color: #fafafa; }}
351
- .user {{ color: #2563eb; font-weight: 600; }}
352
- .ai {{ color: #059669; }}
353
- .timestamp {{ color: #6b7280; font-size: 0.8em; font-style: italic; }}
354
- .department-badge {{ background-color: #3b82f6; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; }}
355
- .user-badge {{ background-color: #10b981; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; margin-left: 5px; }}
356
- .image-indicator {{ background-color: #f59e0b; color: white; padding: 2px 6px; border-radius: 10px; font-size: 0.7em; margin-left: 5px; }}
357
- </style>
358
- </head>
359
- <body>
360
- <div class="header">
361
- <h1 style="margin: 0;">πŸ€– AI Coordination System Report</h1>
362
- <p style="margin: 5px 0; opacity: 0.9;">Comprehensive inter-department coordination summary</p>
363
- <p style="margin: 5px 0;"><strong>Generated:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
364
- </div>
365
-
366
- <div class="stats">
367
- <div class="stat-card">
368
- <h3 style="margin: 0; color: #3b82f6;">{len(conversation_data)}</h3>
369
- <p style="margin: 5px 0;">Total Interactions</p>
370
- </div>
371
- <div class="stat-card">
372
- <h3 style="margin: 0; color: #10b981;">{len(dept_activity)}</h3>
373
- <p style="margin: 5px 0;">Active Departments</p>
374
- </div>
375
- <div class="stat-card">
376
- <h3 style="margin: 0; color: #f59e0b;">{sum(1 for entry in conversation_history if entry.get('email_sent'))}</h3>
377
- <p style="margin: 5px 0;">Emails Sent</p>
378
- </div>
379
- </div>
380
-
381
- <h3>πŸ“Š Department Activity</h3>
382
- {dept_activity_html}
383
-
384
- <h3>πŸ‘₯ User Activity</h3>
385
- {user_activity_html if user_activity_html else "<p>No user activity data</p>"}
386
-
387
- <h3>πŸ”„ Recent Coordination Activities</h3>
388
- {recent_activities_html if recent_activities_html else "<p>No recent activities</p>"}
389
-
390
- <div style="margin-top: 30px; padding: 15px; background-color: #f0fdf4; border-radius: 8px;">
391
- <p style="margin: 0;"><strong>πŸ€– AI Note:</strong> This report is automatically generated by the coordination system. All inter-department communications are logged and monitored for efficiency.</p>
392
- </div>
393
- </body>
394
- </html>"""
395
-
396
- # Send email using Brevo SMTP
397
- email_status = send_email_smtp(current_report_email, subject, html_content, "AI Coordination System")
398
- return email_status
399
-
400
- except Exception as e:
401
- return f"Failed to send report: {str(e)}"
402
-
403
- def add_to_conversation_history(user_input, department, user_name, ai_response, email_sent=False, image_uploaded=False):
404
- """Add current exchange to conversation history"""
405
- entry = {
406
- 'timestamp': datetime.datetime.now().isoformat(),
407
- 'user_input': user_input,
408
- 'department': department,
409
- 'user_name': user_name,
410
- 'ai_response': ai_response,
411
- 'email_sent': email_sent,
412
- 'image_uploaded': image_uploaded
413
- }
414
- conversation_history.append(entry)
415
-
416
- # Keep only last 50 exchanges to prevent memory issues
417
- if len(conversation_history) > 50:
418
- conversation_history.pop(0)
419
 
420
  def process_coordination_request(name, department, message, image, recipient_dept, send_email, urgency):
421
- """Process coordination requests between departments with image support"""
422
- if not message.strip():
423
- return "Please enter a coordination message."
424
-
425
- if not department:
426
- return "Please select your department."
427
-
428
- if not name.strip():
429
- return "Please enter your name."
430
 
431
- # Get AI analysis and suggestions (with image if provided)
432
  ai_analysis = analyze_coordination_needs(message, department, name, image)
433
 
434
  # Prepare response
435
- response_parts = []
436
- response_parts.append(f"**πŸ‘€ Request from:** {name} | **🏒 Department:** {departments[department]['name']}")
437
-
438
- if image:
439
- response_parts.append("**πŸ“· Image attached and analyzed**")
440
-
441
- response_parts.append(f"\n**πŸ€– AI Coordination Analysis:**\n{ai_analysis}")
442
 
443
  # Send email if requested
444
  email_status = ""
445
  if send_email and recipient_dept:
446
- subject = f"Coordination Request from {departments[department]['name']} - {name}"
447
-
448
- # Build email message without triple quotes in f-string
449
- email_lines = [
450
- f"Requestor: {name}",
451
- f"Department: {departments[department]['name']}",
452
- "",
453
- "Message:",
454
- message,
455
- ""
456
- ]
457
-
458
- if image:
459
- email_lines.append("Note: An image was included with this request. Please check the system for visual details.")
460
- email_lines.append("")
461
-
462
- email_lines.extend([
463
- "---",
464
- "AI Coordination Suggestions:",
465
- ai_analysis
466
- ])
467
-
468
- email_message = "\n".join(email_lines)
469
- email_status = send_department_email(department, recipient_dept, subject, email_message, name, urgency, image)
470
- response_parts.append(f"\n**πŸ“§ Email Status:** {email_status}")
471
-
472
- full_response = "\n".join(response_parts)
473
-
474
- # Add to conversation history
475
- add_to_conversation_history(
476
- user_input=message,
477
- department=department,
478
- user_name=name,
479
- ai_response=full_response,
480
- email_sent=bool(send_email and recipient_dept),
481
- image_uploaded=image is not None
482
- )
483
-
484
- return full_response
485
-
486
- def get_conversation_stats():
487
- """Get statistics about current coordination activities"""
488
- if not conversation_history:
489
- return "No coordination activities yet"
490
-
491
- total_exchanges = len(conversation_history)
492
- dept_activity = {}
493
- user_activity = {}
494
- emails_sent = sum(1 for entry in conversation_history if entry.get('email_sent'))
495
- images_uploaded = sum(1 for entry in conversation_history if entry.get('image_uploaded'))
496
-
497
- for entry in conversation_history:
498
- dept = entry.get('department', 'Unknown')
499
- user = entry.get('user_name', 'Unknown')
500
- dept_activity[dept] = dept_activity.get(dept, 0) + 1
501
- if user != 'Unknown':
502
- user_activity[user] = user_activity.get(user, 0) + 1
503
-
504
- stats_text = f"Total Activities: {total_exchanges} | Emails Sent: {emails_sent} | Images: {images_uploaded}\n"
505
- stats_text += "Department Activity: " + ", ".join([f"{k}: {v}" for k, v in dept_activity.items()])
506
-
507
- if user_activity:
508
- stats_text += f"\nActive Users: {', '.join(user_activity.keys())}"
509
-
510
- return stats_text
511
-
512
- def clear_conversation():
513
- """Clear the conversation history"""
514
- global conversation_history
515
- conversation_history = []
516
- return "Coordination history cleared!"
517
-
518
- def get_current_email():
519
- """Get the current report email address"""
520
- return current_report_email if current_report_email else "Not set"
521
-
522
- def clear_form():
523
- """Clear the form fields"""
524
- return ["", None, "", None, "administration", "Normal", False]
525
 
526
  # Gradio Interface
527
- with gr.Blocks(theme=gr.themes.Soft(), title="AI Coordination System") as ui:
528
  gr.Markdown("# 🏒 AI Department Coordination System")
529
- gr.Markdown("*Automated coordination between Administration, Production, and Magazine Management*")
530
 
531
  with gr.Row():
532
  with gr.Column(scale=1):
533
- gr.Markdown("### πŸ“§ System Configuration")
534
  email_input = gr.Textbox(
535
- label="Administration Report Email",
536
- value=get_current_email,
537
- placeholder="admin@company.com"
538
  )
539
  email_status = gr.Textbox(
540
- label="Email Status",
541
- value=get_current_email,
542
- interactive=False,
543
- max_lines=2
544
  )
545
- update_email_btn = gr.Button("Update Email", variant="primary")
546
-
547
- gr.Markdown("---")
548
- gr.Markdown("### πŸ‘€ Coordination Request Form")
549
 
550
- with gr.Group():
551
- gr.Markdown("#### Personal Information")
552
- name_input = gr.Textbox(
553
- label="Your Full Name",
554
- placeholder="Enter your full name"
555
- )
556
-
557
- department_dropdown = gr.Dropdown(
558
- choices=["administration", "production", "magazine"],
559
- label="Your Department"
560
- )
561
-
562
- with gr.Group():
563
- gr.Markdown("#### Request Details")
564
- message_input = gr.Textbox(
565
- label="Coordination Message",
566
- lines=4,
567
- placeholder="Describe what you need from other departments..."
568
- )
569
-
570
- image_input = gr.Image(
571
- label="Attach Image (Optional)",
572
- type="pil"
573
- )
574
-
575
- with gr.Group():
576
- gr.Markdown("#### Email Options")
577
- recipient_dropdown = gr.Dropdown(
578
- choices=["administration", "production", "magazine"],
579
- label="Recipient Department"
580
- )
581
-
582
- urgency_dropdown = gr.Dropdown(
583
- choices=["Normal", "Medium", "High"],
584
- value="Normal",
585
- label="Urgency Level"
586
- )
587
-
588
- send_email_checkbox = gr.Checkbox(
589
- label="Send email to recipient department",
590
- value=True
591
- )
592
-
593
- with gr.Row():
594
- submit_btn = gr.Button("Submit Coordination Request", variant="primary")
595
- clear_form_btn = gr.Button("Clear Form", variant="secondary")
596
-
597
- with gr.Row():
598
- report_btn = gr.Button("Submit & Send Report", variant="secondary")
599
- clear_btn = gr.Button("Clear History", variant="stop")
600
- stats_btn = gr.Button("Get Stats")
601
-
602
- status_display = gr.Textbox(
603
- label="System Status",
604
- interactive=False,
605
- max_lines=2
606
  )
607
-
608
- stats_display = gr.Textbox(
609
- label="Coordination Statistics",
610
- interactive=False,
611
- max_lines=4
612
  )
 
 
 
 
613
 
614
  with gr.Column(scale=2):
615
- gr.Markdown("### πŸ€– AI Coordination Response")
616
  output = gr.Textbox(
617
- label="Coordination Analysis & Actions",
618
- lines=18,
619
  show_copy_button=True
620
  )
621
-
622
- with gr.Accordion("🏒 Department Information", open=True):
623
- gr.Markdown("**Administration**: Overall management, decision making, and coordination \n**Production**: Manufacturing, quality control, and production planning \n**Magazine Management**: Content creation, publishing, and distribution \n \n*The AI will analyze your message and any attached images to provide specific coordination recommendations.*")
624
-
625
- with gr.Accordion("πŸ“œ Recent Coordination Activities", open=False):
626
- history_display = gr.JSON(
627
- label="Activity Log",
628
- value=conversation_history[-10:] if conversation_history else []
629
- )
630
-
631
- # Event handlers
632
- update_email_btn.click(
633
- fn=update_report_email,
634
- inputs=[email_input],
635
- outputs=email_status
636
- )
637
-
638
- email_input.submit(
639
- fn=update_report_email,
640
- inputs=[email_input],
641
- outputs=email_status
642
- )
643
 
 
644
  submit_btn.click(
645
- fn=process_coordination_request,
646
- inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown],
647
- outputs=output
648
- )
649
-
650
- report_btn.click(
651
- fn=lambda name, dept, msg, img, rec, send, urg: process_coordination_request(name, dept, msg, img, rec, send, urg) + "\n\n---\n" + send_email_report(conversation_history),
652
- inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown],
653
- outputs=output
654
- )
655
-
656
- message_input.submit(
657
- fn=process_coordination_request,
658
- inputs=[name_input, department_dropdown, message_input, image_input, recipient_dropdown, send_email_checkbox, urgency_dropdown],
659
- outputs=output
660
- )
661
-
662
- clear_btn.click(
663
- fn=clear_conversation,
664
- inputs=[],
665
- outputs=status_display
666
- )
667
-
668
- clear_form_btn.click(
669
- fn=clear_form,
670
- inputs=[],
671
- outputs=[name_input, image_input, message_input, recipient_dropdown, department_dropdown, urgency_dropdown, send_email_checkbox]
672
- )
673
-
674
- stats_btn.click(
675
- fn=get_conversation_stats,
676
- inputs=[],
677
- outputs=stats_display
678
  )
679
 
680
  if __name__ == "__main__":
 
5
  from PIL import Image
6
  import io
7
  import datetime
 
 
 
 
8
 
9
+ # Configuration
10
  OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
11
+ BREVO_API_KEY = os.getenv("BREVO_API_KEY")
12
+ BREVO_FROM_EMAIL = os.getenv("BREVO_FROM_EMAIL", "noreply@yourdomain.com")
13
 
14
+ # Store conversation history
 
 
 
 
 
 
15
  conversation_history = []
16
+ current_report_email = os.getenv("REPORT_EMAIL", "admin@company.com")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def update_report_email(new_email):
 
19
  global current_report_email
20
  if new_email and "@" in new_email and "." in new_email:
21
  current_report_email = new_email.strip()
 
23
  else:
24
  return "❌ Please enter a valid email address"
25
 
26
+ def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordination System"):
27
+ """Use Brevo API - works on Hugging Face"""
28
  try:
29
+ if not BREVO_API_KEY:
30
+ return "❌ Brevo API key not configured"
31
+
32
+ response = requests.post(
33
+ "https://api.brevo.com/v3/smtp/email",
34
+ headers={
35
+ "accept": "application/json",
36
+ "content-type": "application/json",
37
+ "api-key": BREVO_API_KEY
38
+ },
39
+ json={
40
+ "sender": {
41
+ "name": from_name,
42
+ "email": BREVO_FROM_EMAIL
43
+ },
44
+ "to": [{"email": to_email, "name": "Recipient"}],
45
+ "subject": subject,
46
+ "htmlContent": html_content
47
+ },
48
+ timeout=10
49
+ )
50
+
51
+ if response.status_code == 201:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  return f"βœ… Email sent to {to_email}"
53
  else:
54
+ error_msg = response.json().get('message', 'Unknown error')
55
+ return f"❌ Brevo API error: {error_msg}"
56
+
57
  except Exception as e:
58
+ return f"❌ Email error: {str(e)}"
59
 
60
  def analyze_coordination_needs(user_message, department, user_name, image=None):
 
 
61
  if image:
 
62
  buffered = io.BytesIO()
63
  image.save(buffered, format="PNG")
64
  img_base64 = base64.b64encode(buffered.getvalue()).decode()
65
 
66
+ prompt = f"""Analyze coordination request from {user_name} ({department}):
 
 
 
 
 
67
 
68
+ Message: {user_message}
 
 
 
 
 
 
69
 
70
+ Provide brief coordination recommendations."""
 
 
 
 
 
71
 
72
  try:
73
  response = requests.post(
74
  "https://openrouter.ai/api/v1/chat/completions",
75
+ headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}"},
 
 
 
76
  json={
77
+ "model": "google/gemini-flash-1.5:free",
78
+ "messages": [{
79
+ "role": "user",
80
+ "content": [
81
+ {"type": "text", "text": prompt},
82
+ {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}}
83
+ ]
84
+ }],
85
+ "max_tokens": 300,
 
 
 
 
 
 
 
 
 
 
86
  },
87
+ timeout=20
88
  )
 
89
  if response.status_code == 200:
90
+ return response.json()["choices"][0]["message"]["content"]
91
+ return "πŸ€– Analysis complete. Coordination needed."
92
+ except:
93
+ return "πŸ€– Coordination assessment ready."
 
 
 
94
 
95
  else:
96
+ prompt = f"""Quick coordination analysis for {user_name} ({department}):
 
 
 
 
 
97
 
98
+ "{user_message}"
 
 
 
 
 
99
 
100
+ Provide brief recommendations."""
 
 
 
 
101
 
102
  try:
103
  response = requests.post(
104
  "https://openrouter.ai/api/v1/chat/completions",
105
+ headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}"},
 
 
 
106
  json={
107
+ "model": "google/gemini-flash-1.5:free",
108
  "messages": [{"role": "user", "content": prompt}],
109
+ "max_tokens": 250,
110
  },
111
+ timeout=15
112
  )
 
113
  if response.status_code == 200:
114
+ return response.json()["choices"][0]["message"]["content"]
115
+ return "πŸ€– Coordination request processed."
116
+ except:
117
+ return "πŸ€– Departments coordinated."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
 
119
  def process_coordination_request(name, department, message, image, recipient_dept, send_email, urgency):
120
+ if not all([name.strip(), department, message.strip()]):
121
+ return "Please fill all required fields."
 
 
 
 
 
 
 
122
 
123
+ # Get AI analysis
124
  ai_analysis = analyze_coordination_needs(message, department, name, image)
125
 
126
  # Prepare response
127
+ response_parts = [
128
+ f"**πŸ‘€ Request from:** {name} | **🏒 Department:** {department.title()}",
129
+ f"**πŸ€– AI Analysis:**\n{ai_analysis}"
130
+ ]
 
 
 
131
 
132
  # Send email if requested
133
  email_status = ""
134
  if send_email and recipient_dept:
135
+ subject = f"[{urgency}] Coordination Request from {department.title()} - {name}"
136
+
137
+ html_content = f"""
138
+ <html>
139
+ <body>
140
+ <h2>🏒 Inter-Department Coordination</h2>
141
+ <p><strong>From:</strong> {department.title()}</p>
142
+ <p><strong>Requested by:</strong> {name}</p>
143
+ <p><strong>Urgency:</strong> {urgency}</p>
144
+ <div style="background:#f8fafc; padding:15px; border-radius:8px; margin:10px 0;">
145
+ <h3>Message:</h3>
146
+ <p>{message}</p>
147
+ </div>
148
+ <div style="background:#f0fdf4; padding:15px; border-radius:8px;">
149
+ <h3>πŸ€– AI Coordination Suggestions:</h3>
150
+ <p>{ai_analysis}</p>
151
+ </div>
152
+ </body>
153
+ </html>
154
+ """
155
+
156
+ email_status = send_email_brevo_api(
157
+ current_report_email, # Send to admin email
158
+ subject,
159
+ html_content,
160
+ f"{department.title()} Department"
161
+ )
162
+ response_parts.append(f"**πŸ“§ Email Status:** {email_status}")
163
+
164
+ return "\n\n".join(response_parts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  # Gradio Interface
167
+ with gr.Blocks(theme=gr.themes.Soft()) as ui:
168
  gr.Markdown("# 🏒 AI Department Coordination System")
 
169
 
170
  with gr.Row():
171
  with gr.Column(scale=1):
172
+ gr.Markdown("### πŸ“§ Configuration")
173
  email_input = gr.Textbox(
174
+ label="Admin Email for Reports",
175
+ value=current_report_email
 
176
  )
177
  email_status = gr.Textbox(
178
+ label="Status",
179
+ value=current_report_email,
180
+ interactive=False
 
181
  )
182
+ update_email_btn = gr.Button("Update Email")
 
 
 
183
 
184
+ gr.Markdown("### πŸ‘€ Coordination Form")
185
+ name_input = gr.Textbox(label="Your Name", placeholder="Enter your name")
186
+ department_dropdown = gr.Dropdown(
187
+ choices=["administration", "production", "magazine"],
188
+ label="Your Department"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
  )
190
+ message_input = gr.Textbox(
191
+ label="Message",
192
+ lines=3,
193
+ placeholder="Describe coordination needs..."
 
194
  )
195
+ image_input = gr.Image(label="Attach Image (Optional)", type="pil")
196
+ send_email_checkbox = gr.Checkbox(label="Send Email Report", value=True)
197
+
198
+ submit_btn = gr.Button("πŸš€ Submit Request", variant="primary")
199
 
200
  with gr.Column(scale=2):
 
201
  output = gr.Textbox(
202
+ label="AI Coordination Response",
203
+ lines=10,
204
  show_copy_button=True
205
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
 
207
+ update_email_btn.click(update_report_email, email_input, email_status)
208
  submit_btn.click(
209
+ process_coordination_request,
210
+ [name_input, department_dropdown, message_input, image_input, department_dropdown, send_email_checkbox, gr.Textbox(value="Normal", visible=False)],
211
+ output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  )
213
 
214
  if __name__ == "__main__":