import gradio as gr import requests import os import base64 from PIL import Image import io import datetime # Configuration from environment variables OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") DEFAULT_REPORT_EMAIL = os.getenv("REPORT_EMAIL") BREVO_API_KEY = os.getenv("BREVO_API_KEY") BREVO_FROM_EMAIL = os.getenv("BREVO_FROM_EMAIL", "noreply@yourdomain.com") # Testing/Demo Mode Configuration DEMO_MODE = os.getenv("DEMO_MODE", "true").lower() == "true" # Enable demo mode by default # Store conversation history and settings conversation_history = [] current_report_email = DEFAULT_REPORT_EMAIL # Department configurations departments = { "administration": { "name": "Administration", "email": os.getenv("ADMIN_EMAIL", "admin@demo.com"), "responsibilities": "Overall management, decision making, and coordination" }, "production": { "name": "Production", "email": os.getenv("PRODUCTION_EMAIL", "production@demo.com"), "responsibilities": "Manufacturing, quality control, and production planning" }, "magazine": { "name": "Magazine Management", "email": os.getenv("MAGAZINE_EMAIL", "magazine@demo.com"), "responsibilities": "Content creation, publishing, and distribution" } } def update_report_email(new_email): """Update the report email address""" global current_report_email if new_email and "@" in new_email and "." in new_email: current_report_email = new_email.strip() return f"โ Report email updated to: {current_report_email}" else: return "โ Please enter a valid email address" def send_email_brevo_api(to_email, subject, html_content, from_name="AI Coordination System"): """Send email using Brevo API""" try: # Demo mode: simulate email sending if DEMO_MODE or not BREVO_API_KEY: return f"๐งช [DEMO MODE] Email simulated to {to_email}" response = requests.post( "https://api.brevo.com/v3/smtp/email", headers={ "accept": "application/json", "content-type": "application/json", "api-key": BREVO_API_KEY }, json={ "sender": { "name": from_name, "email": BREVO_FROM_EMAIL }, "to": [{"email": to_email}], "subject": subject, "htmlContent": html_content }, timeout=10 ) if response.status_code == 201: return f"โ Email sent to {to_email}" else: error_msg = response.json().get('message', 'Unknown error') return f"โ Failed to send email: {error_msg}" except Exception as e: return f"โ Email error: {str(e)}" def get_mock_ai_response(user_message, department, user_name, has_image=False): """Generate a mock AI response for demo/testing mode""" image_section = """ === IMAGE OBSERVATIONS === โข Mock analysis: Image appears to show office equipment โข Suggested action: Forward to relevant department for review """ if has_image else "" responses = { "administration": { "equipment": f""" === EXECUTIVE SUMMARY === Request from {user_name} regarding equipment needs requires coordination between Administration and Production departments for budget approval and implementation. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production This is primarily a production-related request that requires equipment or facility resources. === DEPARTMENTS INVOLVED === โข Production โ Equipment assessment and implementation โข Administration โ Budget approval and procurement authorization === ACTION PLAN === 1. Production department to assess equipment specifications and requirements 2. Administration to review budget implications and approve funding 3. Production to coordinate installation and training === PRIORITY === Medium โ Standard equipment request requiring normal procurement timeline === FOLLOW-UP === Weekly status updates until equipment is operational """, "default": f""" === EXECUTIVE SUMMARY === Administrative request from {user_name} requires internal review and possible coordination with other departments. {image_section} === RECOMMENDED TARGET DEPARTMENT === Administration This request should be handled within the Administration department. === DEPARTMENTS INVOLVED === โข Administration โ Primary responsibility for coordination and decision-making === ACTION PLAN === 1. Review request details and requirements 2. Determine resource allocation and timeline 3. Coordinate with relevant stakeholders === PRIORITY === Normal โ Standard administrative workflow === FOLLOW-UP === Monitor progress and provide status updates as needed """ }, "production": { "content": f""" === EXECUTIVE SUMMARY === Production request from {user_name} involves content creation, requiring Magazine department collaboration. {image_section} === RECOMMENDED TARGET DEPARTMENT === Magazine This request involves content creation and publishing activities. === DEPARTMENTS INVOLVED === โข Magazine โ Content development and design โข Production โ Material production and quality control === ACTION PLAN === 1. Magazine to develop content and design specifications 2. Production to review technical feasibility 3. Coordinate timeline for material production === PRIORITY === Medium โ Requires cross-departmental coordination === FOLLOW-UP === Bi-weekly alignment meetings until project completion """, "default": f""" === EXECUTIVE SUMMARY === Production request from {user_name} requires assessment of manufacturing capabilities and resource allocation. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production Internal production department matter requiring operational attention. === DEPARTMENTS INVOLVED === โข Production โ Manufacturing operations and quality assurance โข Administration โ Resource approval if needed === ACTION PLAN === 1. Assess current production capacity and requirements 2. Identify resource needs and constraints 3. Develop implementation timeline === PRIORITY === Normal โ Standard production workflow === FOLLOW-UP === Regular progress monitoring through production meetings """ }, "magazine": { "printing": f""" === EXECUTIVE SUMMARY === Magazine request from {user_name} regarding printing requires Production department involvement for manufacturing execution. {image_section} === RECOMMENDED TARGET DEPARTMENT === Production Printing and manufacturing activities fall under Production responsibility. === DEPARTMENTS INVOLVED === โข Magazine โ Content finalization and specifications โข Production โ Printing operations and quality control === ACTION PLAN === 1. Magazine to finalize all content and design specifications 2. Production to schedule printing resources 3. Coordinate delivery timeline and distribution === PRIORITY === High โ Publishing deadline-sensitive activity === FOLLOW-UP === Daily updates during production phase """, "default": f""" === EXECUTIVE SUMMARY === Magazine department request from {user_name} involves content development and publishing coordination. {image_section} === RECOMMENDED TARGET DEPARTMENT === Magazine Editorial and publishing matter for Magazine department handling. === DEPARTMENTS INVOLVED === โข Magazine โ Content creation and editorial oversight โข Production โ Technical production support if needed === ACTION PLAN === 1. Develop content strategy and editorial plan 2. Coordinate with relevant stakeholders 3. Execute publishing timeline === PRIORITY === Normal โ Standard editorial workflow === FOLLOW-UP === Editorial review meetings and publication tracking """ } } # Determine which mock response to use message_lower = user_message.lower() dept_responses = responses.get(department, responses["administration"]) for keyword, response in dept_responses.items(): if keyword != "default" and keyword in message_lower: return response return dept_responses["default"] def analyze_coordination_needs(user_message, department, user_name, image=None): """Use LLM to analyze coordination needs and suggest actions - with image support""" # Demo/Testing Mode: Use mock responses if DEMO_MODE or not OPENROUTER_API_KEY: return get_mock_ai_response(user_message, department, user_name, has_image=image is not None) if image: # Convert image to base64 for vision model buffered = io.BytesIO() image.save(buffered, format="PNG") img_base64 = base64.b64encode(buffered.getvalue()).decode() prompt = f""" You are an Enterprise Operations Coordination AI. Analyze the request AND the attached image to determine responsibility and next actions. Write formally and professionally. No casual tone. No emojis. AVAILABLE DEPARTMENTS: - Administration: approvals, management, coordination - Production: equipment, facilities, manufacturing, maintenance - Magazine: design, content, publishing REQUEST: Requestor: {user_name} Origin Department: {department} Message: {user_message} Provide: === EXECUTIVE SUMMARY === Short professional summary === IMAGE OBSERVATIONS === Important findings from the image === RECOMMENDED TARGET DEPARTMENT === Choose ONLY ONE: Administration | Production | Magazine Reason === ACTION PLAN === Numbered steps === PRIORITY === Low | Medium | High with reason === FOLLOW-UP === Monitoring or escalation steps """ try: response = requests.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json", }, json={ "model": "google/gemma-3-27b-it:free", # Vision model "messages": [ { "role": "user", "content": [ { "type": "text", "text": prompt }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{img_base64}" } } ] } ], "temperature": 0.3 }, timeout=60 ) if response.status_code == 200: data = response.json() return data["choices"][0]["message"]["content"] else: return "I'm having trouble analyzing the image right now. Please try again in a moment." except Exception as e: return f"Sorry, I couldn't process the image. Error: {str(e)}" else: # Text-only analysis prompt = f""" You are an Enterprise Operations Coordination AI used inside a professional organization. Your responsibility is to: โข analyze the request โข determine which department should handle it โข produce a concise, executive-style coordination plan Write formally and professionally. Do NOT use conversational tone. Do NOT use emojis. Be precise, structured, and action-oriented. AVAILABLE DEPARTMENTS: - Administration: management, approvals, policies, finance, coordination - Production: manufacturing, maintenance, equipment, operations, logistics - Magazine: content creation, publishing, marketing materials, communication REQUEST: Requestor: {user_name} Origin Department: {department} Message: {user_message} Return your answer STRICTLY using this format: === EXECUTIVE SUMMARY === 2โ3 sentence professional summary. === RECOMMENDED TARGET DEPARTMENT === Choose ONLY ONE: Administration | Production | Magazine Brief justification. === DEPARTMENTS INVOLVED === โข Department โ responsibility === ACTION PLAN === 1. Step 2. Step 3. Step === PRIORITY === Low | Medium | High with reason === FOLLOW-UP === Required monitoring or reporting actions """ try: response = requests.post( "https://openrouter.ai/api/v1/chat/completions", headers={ "Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json", }, json={ "model": "google/gemma-3-27b-it:free", "messages": [{"role": "user", "content": prompt}], "temperature": 0.3 }, timeout=30 ) if response.status_code == 200: data = response.json() return data["choices"][0]["message"]["content"] else: return "I'm having trouble analyzing your request right now. Please try again in a moment." except Exception as e: return f"Sorry, I couldn't process your request. Error: {str(e)}" def send_department_email(sender_dept, recipient_dept, subject, message, user_name, urgency="Normal", image=None): """Send email between departments with optional image attachment""" try: # Determine recipient email recipient_email = departments[recipient_dept]["email"] if not recipient_email: # If no department email configured, use the current report email recipient_email = current_report_email # Create professional email content image_note = "
๐ Attachment: Image included with request
" if image else "" urgency_class = f"urgency-{urgency.lower()}" if urgency.lower() in ['high', 'medium'] else "urgency-normal" image_footer = "Note: An image was included with this request. Please check the original system for image details.
" if image else "" html_content = f"""From: {departments[sender_dept]['name']}
Requested by: {user_name}
To: {departments[recipient_dept]['name']}
Date: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Urgency: {urgency}
{image_note}This is an automated message from the AI Coordination System.
{image_footer}{dept.title()}: {count} interactions
" # Create user activity HTML user_activity_html = "" for user, count in user_activity.items(): if user != 'Unknown': user_activity_html += f"{user}: {count} requests
" # Create recent activities HTML recent_activities_html = "" for i, entry in enumerate(conversation_data[-10:], 1): dept_badge = f"{entry.get('department', 'General').title()}" if entry.get('department') else "" user_badge = f"{entry.get('user_name', 'User')}" if entry.get('user_name') else "" image_indicator = " ๐ท" if entry.get('image_uploaded') else "" email_indicator = " ๐ง" if entry.get('email_sent') else "" recent_activities_html += f"""๐ฌ Message: {entry['user_input']}{email_indicator}
๐ค AI Coordination: {entry['ai_response']}
Comprehensive inter-department coordination summary
Generated: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Total Interactions
Active Departments
Emails Sent
No user activity data
"}No recent activities
"}๐ค AI Note: This report is automatically generated by the coordination system. All inter-department communications are logged and monitored for efficiency.