DevNumb commited on
Commit
fcc9b36
Β·
verified Β·
1 Parent(s): 03227a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +297 -157
app.py CHANGED
@@ -19,6 +19,25 @@ resend.api_key = RESEND_API_KEY
19
  conversation_history = []
20
  current_report_email = DEFAULT_REPORT_EMAIL
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def update_report_email(new_email):
23
  """Update the report email address"""
24
  global current_report_email
@@ -28,76 +47,215 @@ def update_report_email(new_email):
28
  else:
29
  return "❌ Please enter a valid email address"
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def send_email_report(conversation_data):
32
- """Send conversation report directly via Resend"""
33
  if not RESEND_API_KEY or not current_report_email:
34
  return "Email reporting not configured - missing Resend API key or report email"
35
 
36
  try:
 
 
 
 
 
 
37
  # Format email content
38
- subject = f"Chat Conversation Report - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
39
 
40
- # Create HTML email content
41
  html_content = f"""
42
  <html>
43
  <head>
44
  <style>
45
  body {{ font-family: Arial, sans-serif; margin: 20px; }}
46
- .header {{ background-color: #f4f4f4; padding: 20px; border-radius: 8px; margin-bottom: 20px; }}
 
 
47
  .exchange {{ border: 1px solid #e0e0e0; margin: 15px 0; padding: 15px; border-radius: 8px; background-color: #fafafa; }}
48
  .user {{ color: #2563eb; font-weight: 600; }}
49
  .ai {{ color: #059669; }}
50
  .timestamp {{ color: #6b7280; font-size: 0.8em; font-style: italic; }}
51
- .image-info {{ background-color: #fef3c7; padding: 5px 10px; border-radius: 4px; display: inline-block; margin: 5px 0; }}
52
  </style>
53
  </head>
54
  <body>
55
  <div class="header">
56
- <h1 style="margin: 0; color: #1f2937;">πŸ€– Chat Conversation Report</h1>
57
- <p style="margin: 5px 0;"><strong>Date:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
58
- <p style="margin: 5px 0;"><strong>Total Exchanges:</strong> {len(conversation_data)}</p>
59
- <p style="margin: 5px 0;"><strong>Sent to:</strong> {current_report_email}</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  </div>
61
  """
62
 
63
- for i, entry in enumerate(conversation_data, 1):
 
 
 
 
 
 
 
 
 
 
64
  html_content += f"""
65
  <div class="exchange">
66
- <h3 style="margin-top: 0; color: #374151;">Exchange #{i}</h3>
67
- <p class="user"><strong>πŸ‘€ User:</strong> {entry['user_input']}</p>
68
- {f"<p class='image-info'>πŸ“· Image: {entry.get('image_filename', 'Uploaded image')}</p>" if entry.get('image_uploaded') else ""}
69
- <p class="ai"><strong>πŸ€– AI:</strong> {entry['ai_response']}</p>
 
 
70
  <p class="timestamp">{entry['timestamp']}</p>
71
  </div>
72
  """
73
 
74
- html_content += "</body></html>"
 
 
 
 
 
 
75
 
76
- # Send email directly using Resend
77
  params = {
78
- "from": "Chat App <onboarding@resend.dev>",
79
  "to": [current_report_email],
80
  "subject": subject,
81
  "html": html_content,
82
  }
83
 
84
  email = resend.Emails.send(params)
85
-
86
- return f"πŸ“§ Report sent successfully to {current_report_email}"
87
 
88
  except Exception as e:
89
- return f"Failed to send email: {str(e)}"
90
 
91
- def add_to_conversation_history(user_input, image, ai_response):
92
  """Add current exchange to conversation history"""
93
- image_filename = getattr(image, 'filename', 'uploaded_image') if image else None
94
-
95
  entry = {
96
  'timestamp': datetime.datetime.now().isoformat(),
97
  'user_input': user_input,
98
- 'image_uploaded': image is not None,
99
- 'image_filename': image_filename,
100
- 'ai_response': ai_response
101
  }
102
  conversation_history.append(entry)
103
 
@@ -105,134 +263,89 @@ def add_to_conversation_history(user_input, image, ai_response):
105
  if len(conversation_history) > 50:
106
  conversation_history.pop(0)
107
 
108
- def process_input(message, image, send_report=False):
 
109
  if not message.strip():
110
- return "Please enter a message."
111
 
112
- if image is None:
113
- # Text-only query
114
- ai_response = ask_llm(message)
115
- else:
116
- # Image + text query
117
- ai_response = ask_llm_with_image(message, image)
118
 
119
- # Add to conversation history
120
- add_to_conversation_history(message, image, ai_response)
121
 
122
- # Send email report if requested
123
- if send_report and conversation_history:
124
- email_status = send_email_report(conversation_history)
125
- return f"{ai_response}\n\n---\nπŸ“§ Email Status: {email_status}"
126
 
127
- return ai_response
128
-
129
- def ask_llm(message):
130
- """Text-only query to OpenRouter"""
131
- try:
132
- response = requests.post(
133
- "https://openrouter.ai/api/v1/chat/completions",
134
- headers={
135
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
136
- "Content-Type": "application/json",
137
- },
138
- json={
139
- "model": "google/gemma-3-27b-it:free",
140
- "messages": [{"role": "user", "content": message}]
141
- },
142
- timeout=30
143
- )
144
 
145
- if response.status_code == 200:
146
- data = response.json()
147
- return data["choices"][0]["message"]["content"]
148
- else:
149
- return f"API Error: {response.status_code} - {response.text}"
150
-
151
- except Exception as e:
152
- return f"Error: {str(e)}"
153
-
154
- def ask_llm_with_image(message, image):
155
- """Image + text query to OpenRouter"""
156
- # Convert image to base64
157
- buffered = io.BytesIO()
158
- image.save(buffered, format="PNG")
159
- img_base64 = base64.b64encode(buffered.getvalue()).decode()
160
 
161
- try:
162
- response = requests.post(
163
- "https://openrouter.ai/api/v1/chat/completions",
164
- headers={
165
- "Authorization": f"Bearer {OPENROUTER_API_KEY}",
166
- "Content-Type": "application/json",
167
- },
168
- json={
169
- "model": "google/gemini-flash-1.5:free", # Vision model
170
- "messages": [
171
- {
172
- "role": "user",
173
- "content": [
174
- {
175
- "type": "text",
176
- "text": message
177
- },
178
- {
179
- "type": "image_url",
180
- "image_url": {
181
- "url": f"data:image/png;base64,{img_base64}"
182
- }
183
- }
184
- ]
185
- }
186
- ]
187
- },
188
- timeout=30
189
- )
190
-
191
- if response.status_code == 200:
192
- data = response.json()
193
- return data["choices"][0]["message"]["content"]
194
- else:
195
- return f"API Error: {response.status_code} - {response.text}"
196
-
197
- except Exception as e:
198
- return f"Error processing image: {str(e)}"
199
-
200
- def clear_conversation():
201
- """Clear the conversation history"""
202
- global conversation_history
203
- conversation_history = []
204
- return "Conversation history cleared!"
205
 
206
  def get_conversation_stats():
207
- """Get statistics about current conversation"""
208
  if not conversation_history:
209
- return "No conversations yet"
210
 
211
  total_exchanges = len(conversation_history)
212
- image_uploads = sum(1 for entry in conversation_history if entry['image_uploaded'])
213
- last_time = conversation_history[-1]['timestamp'] if conversation_history else "N/A"
 
 
 
 
214
 
215
- return f"Exchanges: {total_exchanges} | Images: {image_uploads} | Last: {last_time}"
 
 
 
 
 
 
 
 
 
216
 
217
  def get_current_email():
218
  """Get the current report email address"""
219
  return current_report_email if current_report_email else "Not set"
220
 
221
  # Gradio Interface
222
- with gr.Blocks(theme=gr.themes.Soft()) as ui:
223
  gr.Markdown("""
224
- # πŸ€– OpenRouter Chat with Email Reports
225
- *Powered by OpenRouter API + Resend Email*
226
  """)
227
 
228
  with gr.Row():
229
  with gr.Column(scale=1):
230
- gr.Markdown("### πŸ“§ Email Settings")
231
  email_input = gr.Textbox(
232
- label="Report Email Address",
233
  value=get_current_email,
234
- placeholder="Enter email address for reports...",
235
- info="This email will receive conversation reports"
236
  )
237
  email_status = gr.Textbox(
238
  label="Email Status",
@@ -243,55 +356,83 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
243
  update_email_btn = gr.Button("πŸ’Ύ Update Email", variant="primary")
244
 
245
  gr.Markdown("---")
246
- gr.Markdown("### πŸ’¬ Chat Input")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  text_input = gr.Textbox(
248
- label="Your message:",
249
- lines=3,
250
- placeholder="Type your message here...",
251
- max_lines=5
252
  )
253
- image_input = gr.Image(
254
- label="πŸ“· Upload an image (optional)",
255
- type="pil",
256
- height=200
 
257
  )
258
 
259
  with gr.Row():
260
- submit_btn = gr.Button("πŸš€ Submit", variant="primary", size="lg")
261
- report_btn = gr.Button("πŸ“§ Submit & Email Report", variant="secondary")
262
 
263
  with gr.Row():
264
  clear_btn = gr.Button("πŸ—‘οΈ Clear History", variant="stop")
265
- stats_btn = gr.Button("πŸ“Š Get Stats")
266
 
267
  status_display = gr.Textbox(
268
- label="Status",
269
  interactive=False,
270
  max_lines=2
271
  )
272
 
273
  stats_display = gr.Textbox(
274
- label="Conversation Statistics",
275
  interactive=False,
276
- max_lines=2
277
  )
278
 
279
  with gr.Column(scale=2):
280
- gr.Markdown("### πŸ€– AI Response")
281
  output = gr.Textbox(
282
- label="Response",
283
- lines=12,
284
  show_copy_button=True
285
  )
286
 
287
- with gr.Accordion("πŸ“œ Conversation History (Last 10)", open=False):
 
 
 
 
 
 
 
288
  history_display = gr.JSON(
289
- label="Recent History",
290
  value=conversation_history[-10:] if conversation_history else [],
291
  every=2
292
  )
293
 
294
- # Event handlers for email management
295
  update_email_btn.click(
296
  fn=update_report_email,
297
  inputs=[email_input],
@@ -304,22 +445,21 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
304
  outputs=email_status
305
  )
306
 
307
- # Event handlers for chat functionality
308
  submit_btn.click(
309
- fn=process_input,
310
- inputs=[text_input, image_input, gr.Checkbox(value=False, visible=False)],
311
  outputs=output
312
  )
313
 
314
  report_btn.click(
315
- fn=process_input,
316
- inputs=[text_input, image_input, gr.Checkbox(value=True, visible=False)],
317
  outputs=output
318
  )
319
 
320
  text_input.submit(
321
- fn=process_input,
322
- inputs=[text_input, image_input, gr.Checkbox(value=False, visible=False)],
323
  outputs=output
324
  )
325
 
@@ -336,4 +476,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as ui:
336
  )
337
 
338
  if __name__ == "__main__":
339
- ui.launch(share=False)
 
19
  conversation_history = []
20
  current_report_email = DEFAULT_REPORT_EMAIL
21
 
22
+ # Department configurations
23
+ departments = {
24
+ "administration": {
25
+ "name": "Administration",
26
+ "email": os.getenv("ADMIN_EMAIL", ""),
27
+ "responsibilities": "Overall management, decision making, and coordination"
28
+ },
29
+ "production": {
30
+ "name": "Production",
31
+ "email": os.getenv("PRODUCTION_EMAIL", ""),
32
+ "responsibilities": "Manufacturing, quality control, and production planning"
33
+ },
34
+ "magazine": {
35
+ "name": "Magazine Management",
36
+ "email": os.getenv("MAGAZINE_EMAIL", ""),
37
+ "responsibilities": "Content creation, publishing, and distribution"
38
+ }
39
+ }
40
+
41
  def update_report_email(new_email):
42
  """Update the report email address"""
43
  global current_report_email
 
47
  else:
48
  return "❌ Please enter a valid email address"
49
 
50
+ def analyze_coordination_needs(user_message, department):
51
+ """Use LLM to analyze coordination needs and suggest actions"""
52
+ prompt = f"""
53
+ As an AI coordination agent, analyze this message from {department} department and suggest appropriate actions:
54
+
55
+ DEPARTMENT: {department}
56
+ MESSAGE: {user_message}
57
+
58
+ Consider:
59
+ 1. Which other departments need to be involved?
60
+ 2. What specific actions should be taken?
61
+ 3. What information needs to be shared?
62
+ 4. What are the priority levels?
63
+ 5. What follow-up is needed?
64
+
65
+ Provide a structured response with:
66
+ - Coordination needed with: [departments]
67
+ - Recommended actions: [bullet points]
68
+ - Priority: [High/Medium/Low]
69
+ - Next steps: [suggestions]
70
+ """
71
+
72
+ try:
73
+ response = requests.post(
74
+ "https://openrouter.ai/api/v1/chat/completions",
75
+ headers={
76
+ "Authorization": f"Bearer {OPENROUTER_API_KEY}",
77
+ "Content-Type": "application/json",
78
+ },
79
+ json={
80
+ "model": "google/gemma-3-27b-it:free",
81
+ "messages": [{"role": "user", "content": prompt}],
82
+ "temperature": 0.3
83
+ },
84
+ timeout=30
85
+ )
86
+
87
+ if response.status_code == 200:
88
+ data = response.json()
89
+ return data["choices"][0]["message"]["content"]
90
+ else:
91
+ return "AI analysis temporarily unavailable."
92
+
93
+ except Exception as e:
94
+ return f"Analysis error: {str(e)}"
95
+
96
+ def send_department_email(sender_dept, recipient_dept, subject, message, urgency="Normal"):
97
+ """Send email between departments"""
98
+ try:
99
+ # Determine recipient email
100
+ recipient_email = departments[recipient_dept]["email"]
101
+ if not recipient_email:
102
+ return f"❌ No email configured for {departments[recipient_dept]['name']}"
103
+
104
+ # Create professional email content
105
+ html_content = f"""
106
+ <html>
107
+ <head>
108
+ <style>
109
+ body {{ font-family: Arial, sans-serif; margin: 20px; }}
110
+ .header {{ background-color: #f4f4f4; padding: 20px; border-radius: 8px; margin-bottom: 20px; }}
111
+ .urgency-high {{ border-left: 5px solid #dc2626; background-color: #fef2f2; }}
112
+ .urgency-medium {{ border-left: 5px solid #d97706; background-color: #fffbeb; }}
113
+ .urgency-normal {{ border-left: 5px solid #2563eb; background-color: #eff6ff; }}
114
+ .message-content {{ padding: 20px; background-color: white; border-radius: 8px; margin: 15px 0; }}
115
+ </style>
116
+ </head>
117
+ <body>
118
+ <div class="header">
119
+ <h1 style="margin: 0; color: #1f2937;">🏒 Inter-Department Communication</h1>
120
+ <p style="margin: 5px 0;"><strong>From:</strong> {departments[sender_dept]['name']}</p>
121
+ <p style="margin: 5px 0;"><strong>To:</strong> {departments[recipient_dept]['name']}</p>
122
+ <p style="margin: 5px 0;"><strong>Date:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
123
+ <p style="margin: 5px 0;"><strong>Urgency:</strong> {urgency}</p>
124
+ </div>
125
+
126
+ <div class="message-content {f'urgency-{urgency.lower()}' if urgency.lower() in ['high', 'medium'] else 'urgency-normal'}">
127
+ <h3 style="margin-top: 0;">{subject}</h3>
128
+ <div style="white-space: pre-line;">{message}</div>
129
+ </div>
130
+
131
+ <div style="color: #6b7280; font-size: 0.9em; margin-top: 20px;">
132
+ <p>This is an automated message from the AI Coordination System.</p>
133
+ </div>
134
+ </body>
135
+ </html>
136
+ """
137
+
138
+ # Send email
139
+ params = {
140
+ "from": f"{departments[sender_dept]['name']} <onboarding@resend.dev>",
141
+ "to": [recipient_email],
142
+ "subject": f"[{urgency}] {subject}",
143
+ "html": html_content,
144
+ }
145
+
146
+ email = resend.Emails.send(params)
147
+ return f"βœ… Email sent to {departments[recipient_dept]['name']}"
148
+
149
+ except Exception as e:
150
+ return f"❌ Failed to send email: {str(e)}"
151
+
152
  def send_email_report(conversation_data):
153
+ """Send comprehensive coordination report to administration"""
154
  if not RESEND_API_KEY or not current_report_email:
155
  return "Email reporting not configured - missing Resend API key or report email"
156
 
157
  try:
158
+ # Calculate department activity
159
+ dept_activity = {}
160
+ for entry in conversation_data:
161
+ dept = entry.get('department', 'Unknown')
162
+ dept_activity[dept] = dept_activity.get(dept, 0) + 1
163
+
164
  # Format email content
165
+ subject = f"Coordination Report - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}"
166
 
167
+ # Create comprehensive HTML report
168
  html_content = f"""
169
  <html>
170
  <head>
171
  <style>
172
  body {{ font-family: Arial, sans-serif; margin: 20px; }}
173
+ .header {{ background-color: #1f2937; color: white; padding: 25px; border-radius: 8px; margin-bottom: 20px; }}
174
+ .stats {{ display: flex; justify-content: space-between; margin: 20px 0; }}
175
+ .stat-card {{ background-color: #f8fafc; padding: 15px; border-radius: 8px; text-align: center; flex: 1; margin: 0 10px; }}
176
  .exchange {{ border: 1px solid #e0e0e0; margin: 15px 0; padding: 15px; border-radius: 8px; background-color: #fafafa; }}
177
  .user {{ color: #2563eb; font-weight: 600; }}
178
  .ai {{ color: #059669; }}
179
  .timestamp {{ color: #6b7280; font-size: 0.8em; font-style: italic; }}
180
+ .department-badge {{ background-color: #3b82f6; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.8em; }}
181
  </style>
182
  </head>
183
  <body>
184
  <div class="header">
185
+ <h1 style="margin: 0;">πŸ€– AI Coordination System Report</h1>
186
+ <p style="margin: 5px 0; opacity: 0.9;">Comprehensive inter-department coordination summary</p>
187
+ <p style="margin: 5px 0;"><strong>Generated:</strong> {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
188
+ </div>
189
+
190
+ <div class="stats">
191
+ <div class="stat-card">
192
+ <h3 style="margin: 0; color: #3b82f6;">{len(conversation_data)}</h3>
193
+ <p style="margin: 5px 0;">Total Interactions</p>
194
+ </div>
195
+ <div class="stat-card">
196
+ <h3 style="margin: 0; color: #10b981;">{len(dept_activity)}</h3>
197
+ <p style="margin: 5px 0;">Active Departments</p>
198
+ </div>
199
+ <div class="stat-card">
200
+ <h3 style="margin: 0; color: #f59e0b;">{sum(1 for entry in conversation_data if entry.get('email_sent'))}</h3>
201
+ <p style="margin: 5px 0;">Emails Sent</p>
202
+ </div>
203
  </div>
204
  """
205
 
206
+ # Add department activity breakdown
207
+ html_content += "<h3>πŸ“Š Department Activity</h3>"
208
+ for dept, count in dept_activity.items():
209
+ html_content += f"<p><strong>{dept.title()}:</strong> {count} interactions</p>"
210
+
211
+ # Add recent exchanges
212
+ html_content += "<h3>πŸ”„ Recent Coordination Activities</h3>"
213
+ for i, entry in enumerate(conversation_data[-10:], 1): # Last 10 entries
214
+ dept_badge = f"<span class='department-badge'>{entry.get('department', 'General').title()}</span>" if entry.get('department') else ""
215
+ email_indicator = " πŸ“§" if entry.get('email_sent') else ""
216
+
217
  html_content += f"""
218
  <div class="exchange">
219
+ <div style="display: flex; justify-content: between; align-items: center;">
220
+ <h4 style="margin: 0; color: #374151;">Activity #{i}</h4>
221
+ {dept_badge}
222
+ </div>
223
+ <p class="user"><strong>πŸ‘€ {entry.get('department', 'User').title()}:</strong> {entry['user_input']}{email_indicator}</p>
224
+ <p class="ai"><strong>πŸ€– AI Coordination:</strong> {entry['ai_response']}</p>
225
  <p class="timestamp">{entry['timestamp']}</p>
226
  </div>
227
  """
228
 
229
+ html_content += """
230
+ <div style="margin-top: 30px; padding: 15px; background-color: #f0fdf4; border-radius: 8px;">
231
+ <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>
232
+ </div>
233
+ </body>
234
+ </html>
235
+ """
236
 
237
+ # Send email
238
  params = {
239
+ "from": "AI Coordination System <onboarding@resend.dev>",
240
  "to": [current_report_email],
241
  "subject": subject,
242
  "html": html_content,
243
  }
244
 
245
  email = resend.Emails.send(params)
246
+ return f"πŸ“§ Coordination report sent to {current_report_email}"
 
247
 
248
  except Exception as e:
249
+ return f"Failed to send report: {str(e)}"
250
 
251
+ def add_to_conversation_history(user_input, department, ai_response, email_sent=False):
252
  """Add current exchange to conversation history"""
 
 
253
  entry = {
254
  'timestamp': datetime.datetime.now().isoformat(),
255
  'user_input': user_input,
256
+ 'department': department,
257
+ 'ai_response': ai_response,
258
+ 'email_sent': email_sent
259
  }
260
  conversation_history.append(entry)
261
 
 
263
  if len(conversation_history) > 50:
264
  conversation_history.pop(0)
265
 
266
+ def process_coordination_request(message, department, recipient_dept, send_email, urgency):
267
+ """Process coordination requests between departments"""
268
  if not message.strip():
269
+ return "Please enter a coordination message."
270
 
271
+ if not department:
272
+ return "Please select your department."
 
 
 
 
273
 
274
+ # Get AI analysis and suggestions
275
+ ai_analysis = analyze_coordination_needs(message, department)
276
 
277
+ # Prepare response
278
+ response_parts = []
279
+ response_parts.append(f"**πŸ€– AI Coordination Analysis:**\n{ai_analysis}")
 
280
 
281
+ # Send email if requested
282
+ email_status = ""
283
+ if send_email and recipient_dept:
284
+ subject = f"Coordination Request from {departments[department]['name']}"
285
+ email_message = f"""{message}
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
+ ---
288
+ AI Coordination Suggestions:
289
+ {ai_analysis}
290
+ """
291
+ email_status = send_department_email(department, recipient_dept, subject, email_message, urgency)
292
+ response_parts.append(f"\n**πŸ“§ Email Status:** {email_status}")
 
 
 
 
 
 
 
 
 
293
 
294
+ full_response = "\n".join(response_parts)
295
+
296
+ # Add to conversation history
297
+ add_to_conversation_history(
298
+ user_input=message,
299
+ department=department,
300
+ ai_response=full_response,
301
+ email_sent=bool(send_email and recipient_dept)
302
+ )
303
+
304
+ return full_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
306
  def get_conversation_stats():
307
+ """Get statistics about current coordination activities"""
308
  if not conversation_history:
309
+ return "No coordination activities yet"
310
 
311
  total_exchanges = len(conversation_history)
312
+ dept_activity = {}
313
+ emails_sent = sum(1 for entry in conversation_history if entry.get('email_sent'))
314
+
315
+ for entry in conversation_history:
316
+ dept = entry.get('department', 'Unknown')
317
+ dept_activity[dept] = dept_activity.get(dept, 0) + 1
318
 
319
+ stats_text = f"Total Activities: {total_exchanges} | Emails Sent: {emails_sent}\n"
320
+ stats_text += "Department Activity: " + ", ".join([f"{k}: {v}" for k, v in dept_activity.items()])
321
+
322
+ return stats_text
323
+
324
+ def clear_conversation():
325
+ """Clear the conversation history"""
326
+ global conversation_history
327
+ conversation_history = []
328
+ return "Coordination history cleared!"
329
 
330
  def get_current_email():
331
  """Get the current report email address"""
332
  return current_report_email if current_report_email else "Not set"
333
 
334
  # Gradio Interface
335
+ with gr.Blocks(theme=gr.themes.Soft(), title="AI Coordination System") as ui:
336
  gr.Markdown("""
337
+ # 🏒 AI Department Coordination System
338
+ *Automated coordination between Administration, Production, and Magazine Management*
339
  """)
340
 
341
  with gr.Row():
342
  with gr.Column(scale=1):
343
+ gr.Markdown("### πŸ“§ System Configuration")
344
  email_input = gr.Textbox(
345
+ label="Administration Report Email",
346
  value=get_current_email,
347
+ placeholder="admin@company.com",
348
+ info="All coordination reports will be sent here"
349
  )
350
  email_status = gr.Textbox(
351
  label="Email Status",
 
356
  update_email_btn = gr.Button("πŸ’Ύ Update Email", variant="primary")
357
 
358
  gr.Markdown("---")
359
+ gr.Markdown("### πŸ’¬ Coordination Request")
360
+
361
+ department_dropdown = gr.Dropdown(
362
+ choices=["administration", "production", "magazine"],
363
+ label="Your Department",
364
+ info="Select which department you're representing"
365
+ )
366
+
367
+ recipient_dropdown = gr.Dropdown(
368
+ choices=["administration", "production", "magazine"],
369
+ label="Recipient Department (for email)",
370
+ info="Select which department to email"
371
+ )
372
+
373
+ urgency_dropdown = gr.Dropdown(
374
+ choices=["Normal", "Medium", "High"],
375
+ value="Normal",
376
+ label="Urgency Level",
377
+ info="Set email priority"
378
+ )
379
+
380
  text_input = gr.Textbox(
381
+ label="Coordination Message",
382
+ lines=4,
383
+ placeholder="Describe what you need from other departments...\nExample: 'We need production schedules for the next magazine issue by Friday.'",
384
+ max_lines=6
385
  )
386
+
387
+ send_email_checkbox = gr.Checkbox(
388
+ label="πŸ“§ Send email to recipient department",
389
+ value=True,
390
+ info="Automatically send coordination email"
391
  )
392
 
393
  with gr.Row():
394
+ submit_btn = gr.Button("πŸš€ Submit Coordination", variant="primary", size="lg")
395
+ report_btn = gr.Button("πŸ“Š Submit & Send Report", variant="secondary")
396
 
397
  with gr.Row():
398
  clear_btn = gr.Button("πŸ—‘οΈ Clear History", variant="stop")
399
+ stats_btn = gr.Button("πŸ“ˆ Get Stats")
400
 
401
  status_display = gr.Textbox(
402
+ label="System Status",
403
  interactive=False,
404
  max_lines=2
405
  )
406
 
407
  stats_display = gr.Textbox(
408
+ label="Coordination Statistics",
409
  interactive=False,
410
+ max_lines=3
411
  )
412
 
413
  with gr.Column(scale=2):
414
+ gr.Markdown("### πŸ€– AI Coordination Response")
415
  output = gr.Textbox(
416
+ label="Coordination Analysis & Actions",
417
+ lines=15,
418
  show_copy_button=True
419
  )
420
 
421
+ with gr.Accordion("🏒 Department Information", open=False):
422
+ gr.Markdown("""
423
+ **Administration**: Overall management, decision making, and coordination
424
+ **Production**: Manufacturing, quality control, and production planning
425
+ **Magazine Management**: Content creation, publishing, and distribution
426
+ """)
427
+
428
+ with gr.Accordion("πŸ“œ Recent Coordination Activities", open=False):
429
  history_display = gr.JSON(
430
+ label="Activity Log",
431
  value=conversation_history[-10:] if conversation_history else [],
432
  every=2
433
  )
434
 
435
+ # Event handlers
436
  update_email_btn.click(
437
  fn=update_report_email,
438
  inputs=[email_input],
 
445
  outputs=email_status
446
  )
447
 
 
448
  submit_btn.click(
449
+ fn=process_coordination_request,
450
+ inputs=[text_input, department_dropdown, recipient_dropdown, send_email_checkbox, urgency_dropdown],
451
  outputs=output
452
  )
453
 
454
  report_btn.click(
455
+ fn=lambda msg, dept, rec, send, urg: process_coordination_request(msg, dept, rec, send, urg) + "\n\n---\n" + send_email_report(conversation_history),
456
+ inputs=[text_input, department_dropdown, recipient_dropdown, send_email_checkbox, urgency_dropdown],
457
  outputs=output
458
  )
459
 
460
  text_input.submit(
461
+ fn=process_coordination_request,
462
+ inputs=[text_input, department_dropdown, recipient_dropdown, send_email_checkbox, urgency_dropdown],
463
  outputs=output
464
  )
465
 
 
476
  )
477
 
478
  if __name__ == "__main__":
479
+ ui.launch(share=True)