An intelligent email management system that uses Google's Gemma-3 AI model to automatically triage, categorize, and process your Gmail inbox. This project implements a phased approach to building a sophisticated, user-trusted email automation system.
- Smart Email Triage: Automatically classify emails by urgency (Urgent, To Respond, FYI, Meeting, Spam)
- Intelligent Categorization: Sort emails into meaningful categories (Work, Personal, Marketing, Security, etc.)
- Confidence Scoring: Each AI decision includes a confidence score and clear reasoning
- Learning System: Improves accuracy over time based on user corrections
- RHLF Personalization: Reinforcement Learning from Human Feedback adapts to your unique preferences and communication patterns
- Follow-up Tracking: Automatically identifies emails requiring follow-up action and tracks pending responses
- Overdue Detection: Highlights overdue tasks and missed deadlines with smart notifications
- Smart Reminders: AI-powered reminder system for important emails and upcoming deadlines
- Context-Aware Scheduling: Integrates with calendar to suggest optimal timing for follow-ups
- Modern GUI: Built with CustomTkinter for a clean, professional interface
- Priority Inbox: Emails automatically sorted by importance and urgency
- AI Analysis Dashboard: View detailed AI reasoning and confidence scores
- One-Click Corrections: Easy feedback system to train the AI
- Thread Summaries: AI-generated summaries of email conversations
- Task Management Panel: Dedicated views for follow-ups, overdue items, and reminders
- Feedback Collection System: Built-in report button for collecting user feedback and improving AI performance
- Personalization Dashboard: View and adjust RHLF learning preferences and AI behavior patterns
- OAuth2 Authentication: Secure Google Workspace integration
- Local Data Storage: All learning data stored locally in SQLite database
- Minimal Permissions: Only requests necessary Gmail and Calendar permissions
- Transparent AI: All AI decisions explained with clear reasoning
- Python 3.10 or higher
- Google Cloud Project with Gmail and Calendar APIs enabled
- Gemini API key from Google AI Studio (for Gemma-3 model access)
-
Clone and Setup Environment
git clone <your-repo-url> cd "Email & Calendar Management RPD" python -m venv ai_email_manager_env ai_email_manager_env\Scripts\Activate.ps1 # Windows PowerShell # or source ai_email_manager_env/bin/activate # Linux/Mac
-
Install Dependencies
pip install -r requirements.txt
-
Configure API Keys
copy .env.template .env # Edit .env with your API keys (see Configuration section below) -
Run the Application
python main.py
- Go to Google Cloud Console
- Create a new project or select existing one
- Enable Gmail API and Google Calendar API
- Create OAuth 2.0 credentials (Desktop application)
- Download the JSON file (not needed directly, but used for reference)
- Visit Google AI Studio
- Create a new API key (ensure Gemma-3 model access)
- Copy the key for use in configuration
# AI Configuration
GEMINI_API_KEY=your_gemini_api_key_here
# Google Workspace Configuration
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
GOOGLE_REDIRECT_URI=http://localhost:8080/callback
# Application Settings
APP_NAME=AI Email Manager
DEBUG=false
LOG_LEVEL=INFO
# AI Model Settings (Gemma-3)
AI_MODEL=gemma-3-27b-it
AI_CONFIDENCE_THRESHOLD=0.7
MAX_TOKENS=1000
TEMPERATURE=0.3
EMAIL_FETCH_COUNT=100
EMAIL_FETCH_DAYS=30
# GUI Settings
THEME=dark
WINDOW_WIDTH=1200
WINDOW_HEIGHT=800- Launch the application:
python main.py - Click "Authenticate" and follow the Google OAuth flow
- Grant permissions for Gmail and Calendar access
- Click "Refresh Emails" to load and analyze your inbox (fetches up to 100 emails from the past 30 days)
- Review Priority Inbox: Emails are automatically sorted by urgency
- Check Follow-ups: Review pending follow-ups and overdue items in the task management panel
- Manage Reminders: View and respond to AI-generated smart reminders
- Check AI Analysis: Click any email to see AI reasoning and recommendations
- Correct Mistakes: Use the correction interface to improve AI accuracy
- Take Actions: Mark as read, quick reply, or view thread summaries
- Provide Feedback: Use the report button to submit feedback and help improve the AI
- Review Personalization: Check RHLF learning progress and adjust preferences as needed
- Urgent: Requires immediate action (deadlines, VIPs, urgent keywords)
- To Respond: Needs a response but not urgent (questions, requests)
- FYI: Informational only, no action required
- Meeting: Meeting invitations and calendar requests
- Spam: Promotional content or suspicious emails
- Work: Business-related communications
- Personal: Personal correspondence
- Marketing: Newsletters and promotional content
- Security: Security alerts and notifications
- Meeting Request: Calendar invitations
- Task Assignment: Work assignments and tasks
- Information: General informational content
- Urgent Decision: Requires immediate decision-making
- Follow-up Required: Emails that need follow-up action
- Overdue: Past-due items requiring immediate attention
- Automatic Detection: AI identifies emails that require follow-up based on content and context
- Smart Scheduling: Suggests optimal follow-up timing based on email urgency and your calendar
- Progress Tracking: Monitors follow-up status and completion rates
- Customizable Rules: Set personal preferences for follow-up criteria and timing
- Deadline Detection: Automatically identifies deadlines from email content
- Priority Escalation: Escalates overdue items based on importance and sender
- Visual Indicators: Clear color-coding and alerts for overdue tasks
- Recovery Suggestions: AI-powered recommendations for handling overdue items
- Context-Aware Timing: Reminders scheduled based on your work patterns and availability
- Adaptive Frequency: Reminder frequency adjusts based on task importance and your response patterns
- Cross-Platform Sync: Reminders integrate with your calendar and notification system
- Snooze Intelligence: Smart snooze suggestions based on email content and your schedule
- Behavioral Adaptation: AI learns your communication patterns and preferences over time
- Context Understanding: Improves understanding of your specific work context and priorities
- Feedback Integration: Continuously improves based on your corrections and feedback
- Personal Workflow Optimization: Adapts to your unique email management style
- Report Button: Easy-to-access feedback collection for any AI decision or recommendation
- Structured Feedback: Multiple feedback types (accuracy, helpfulness, timing, etc.)
- Anonymous Analytics: Optional anonymous usage data to improve the system for all users
- Preference Learning: System learns from implicit feedback (actions taken, ignored suggestions, etc.)
src/
โโโ core/ # Core application logic
โ โโโ config.py # Configuration management
โ โโโ email_service.py # Gmail API integration
โโโ ai/ # AI services
โ โโโ gemini_service.py # Gemini AI integration
โ โโโ rhlf_service.py # RHLF personalization engine
โโโ auth/ # Authentication
โ โโโ google_auth.py # OAuth2 flow
โโโ database/ # Data persistence
โ โโโ learning_db.py # Learning database
โ โโโ feedback_db.py # Feedback and RHLF data
โโโ tasks/ # Task management
โ โโโ followup_manager.py # Follow-up tracking
โ โโโ overdue_detector.py # Overdue task detection
โ โโโ reminder_system.py # Smart reminder system
โโโ gui/ # User interface
โ โโโ main_app.py # Main GUI application
โ โโโ task_panel.py # Task management interface
โ โโโ feedback_widget.py # Feedback collection UI
โโโ utils/ # Utility functions
- GeminiEmailAI: Handles all AI operations using Google's Gemma-3 model via Gemini API
- RHLFService: Manages reinforcement learning from human feedback and personalization
- EmailService: Manages Gmail API operations and email processing
- GoogleAuthService: Handles secure OAuth2 authentication
- LearningDatabase: Stores user feedback and learning data
- FeedbackDatabase: Manages RHLF data and user feedback collection
- FollowupManager: Tracks and manages email follow-ups
- OverdueDetector: Identifies and manages overdue tasks and deadlines
- ReminderSystem: AI-powered smart reminder system
- EmailManagerApp: Main GUI application with CustomTkinter
- TaskPanel: User interface for task management features
- FeedbackWidget: UI component for collecting user feedback
- Email triage and classification
- User feedback and learning system
- Basic GUI with intelligent inbox
- Follow-up tracking and management system
- Overdue task detection and escalation
- Smart reminder system with context awareness
- RHLF-based personalization engine
- Comprehensive feedback collection system
- AI-powered response generation
- Email-to-calendar conversion
- Advanced thread summarization
- Workflow automation based on learned patterns
- Preview-before-execution framework
- Advanced learning algorithms
- Granular user controls
- Rollback capabilities
- Performance optimization
- Cross-platform integrations
- Productivity metrics
- Advanced workflow orchestration
- Enterprise-grade scalability
Run the built-in tests:
python -m pytest tests/Test individual components:
# Test AI service with Gemma-3 model (requires API key)
python -c "from src.ai.gemini_service import GeminiEmailAI; ai = GeminiEmailAI(); print('Gemma-3 AI service working!')"
# Test authentication (requires credentials)
python -c "from src.auth.google_auth import get_auth_service; auth = get_auth_service(); print('Auth service ready!')"The application has been enhanced with several critical fixes and improvements:
- Calendar Authentication: Fixed calendar refresh issues during startup by properly checking authentication state
- GUI Component Order: Improved status bar initialization to prevent component access errors
- Startup Flow: Enhanced application startup sequence for better reliability
- Authentication State: Better handling of authentication status across components
- Robust Datetime Processing: Fixed timezone-aware vs timezone-naive datetime comparison errors
- Enhanced Date Parsing: Added fallback mechanisms for various date formats and string dates
- UI Stability: Eliminated crashes during email display caused by datetime comparison issues
- Consistent Date Handling: All dates are now normalized to timezone-naive format for consistent processing
- Error Recovery: Improved parsing of AI batch analysis with robust error handling
- Enum Validation: Added validation and correction for EmailUrgency and EmailCategory values
- Common Mistake Mapping: Automatically corrects common AI classification mistakes (e.g., 'marketing' -> 'spam')
- Fallback Analysis: Provides default analysis when parsing fails, preventing application crashes
- Batch Processing Optimization: Enhanced batch size handling for improved processing efficiency
- Comprehensive Exception Handling: Added try-catch blocks throughout the application
- Graceful Degradation: Application continues to function even when individual components fail
- Detailed Logging: Enhanced error logging with context information for better debugging
- User-Friendly Error Messages: Improved error reporting for better user experience
- Optimized Batch Processing: Better handling of AI analysis batches to reduce processing time
- Memory Management: Improved memory usage during email fetching and processing
- Database Operations: Enhanced database query performance and error handling
These improvements significantly enhance the application's reliability, user experience, and overall stability.
"Authentication Failed"
- Verify your Google Client ID and Secret are correct
- Check that Gmail and Calendar APIs are enabled
- Ensure redirect URI matches exactly
"AI Analysis Failed"
- Verify your Gemini API key is valid and has Gemma-3 model access
- Check your internet connection
- Ensure Gemma-3 model is available in your region
- Review the logs in
data/app.log
"No Emails Loaded"
- Ensure you've completed OAuth authentication
- Check Gmail API permissions
- Verify your Gmail account has recent emails
Enable debug logging by setting DEBUG=true in your .env file. This will provide detailed logs in data/app.log.
The application tracks learning progress and provides insights:
- User Corrections: Number of AI classifications corrected
- Model Accuracy: Confidence scores and improvement over time
- Sender Patterns: Learned behaviors for frequent contacts
- Usage Statistics: Email processing and user interaction metrics
- Task Completion Rates: Follow-up completion and overdue task resolution metrics
- Reminder Effectiveness: Analysis of reminder timing and response rates
- RHLF Progress: Personalization learning progress and adaptation metrics
- Feedback Analytics: User satisfaction and system improvement insights
View statistics through the database:
from src.database.learning_db import get_learning_db
from src.database.feedback_db import get_feedback_db
# Learning statistics
learning_db = get_learning_db()
learning_stats = learning_db.get_learning_statistics()
print("Learning Stats:", learning_stats)
# RHLF and feedback statistics
feedback_db = get_feedback_db()
rhlf_stats = feedback_db.get_rhlf_statistics()
feedback_summary = feedback_db.get_feedback_summary()
print("RHLF Stats:", rhlf_stats)
print("Feedback Summary:", feedback_summary)
# Task management statistics
from src.tasks.followup_manager import FollowupManager
from src.tasks.reminder_system import ReminderSystem
followup_mgr = FollowupManager()
reminder_sys = ReminderSystem()
task_stats = {
'followups': followup_mgr.get_statistics(),
'reminders': reminder_sys.get_statistics()
}
print("Task Management Stats:", task_stats)We welcome contributions! Please see our contribution guidelines for details.
- Fork the repository
- Create a feature branch
- Set up development environment
- Make your changes
- Add tests
- Submit a pull request
- Use Black for formatting:
black src/ - Follow PEP 8 guidelines
- Add type hints where possible
- Include docstrings for functions and classes
This project is licensed under the MIT License. See LICENSE file for details.
- Google AI Team for the Gemini API and Gemma-3 model
- Google Cloud Team for Gmail and Calendar APIs
- CustomTkinter community for the modern GUI framework
- Open source contributors and testers
- Documentation: This README and inline code documentation
- Issues: Use GitHub Issues for bug reports and feature requests
- Discussions: Use GitHub Discussions for questions and ideas
Built with โค๏ธ using Python, Google AI, and modern development practices.