-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_mail2cal.py
More file actions
424 lines (360 loc) · 14.9 KB
/
Copy pathrun_mail2cal.py
File metadata and controls
424 lines (360 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#!/usr/bin/env python3
"""
Mail2Cal - Single Entry Point
Unified script with all features accessible through command-line options
"""
import sys
import argparse
from core.mail2cal import Mail2Cal
from utils.preview_emails import EmailPreview
from utils.cleanup_duplicates import authenticate, find_school_events, find_duplicates, cleanup_duplicates
from utils.cleanup_duplicates_smart import main as cleanup_duplicates_smart
from utils.check_calendar import check_recent_events
from processors.file_event_processor import FileEventProcessor, check_file_processing_dependencies
from core.config import get_config, get_calendar_ids
def load_credentials():
"""Load credentials when actually needed"""
try:
cfg = get_config()
return (cfg['ai_service']['api_key'],
cfg['calendars']['calendar_id_1'],
cfg['calendars']['calendar_id_2'])
except Exception as e:
print(f"[!] Error loading credentials: {e}")
print("[!] Please ensure your Google Apps Script is deployed and accessible")
sys.exit(1)
def preview_emails():
"""Preview emails without using AI tokens"""
print("[*] PREVIEW MODE - No AI tokens will be used")
print("=" * 60)
preview = EmailPreview()
emails = preview.get_school_emails()
preview.display_email_summary(emails)
if emails:
print(f"\n[?] Would you like to see detailed preview of first 5 emails? (y/n): ", end="")
try:
response = input().lower().strip()
if response in ['y', 'yes']:
preview.display_detailed_preview(emails, 5)
except:
pass
print(f"\n[*] Ready to process with AI? You have {len(emails)} emails that will use API tokens.")
def test_limited(limit=3):
"""Test with limited number of emails"""
print(f"[*] TEST MODE - Processing only {limit} most recent emails")
print("=" * 60)
app = Mail2Cal()
app.run(max_emails=limit)
def cleanup_duplicates_cmd():
"""Clean up duplicate calendar events"""
print("[*] CLEANUP MODE - Removing duplicate calendar events")
print("=" * 60)
# Authenticate
service = authenticate()
# Find Mail2Cal events
events = find_school_events(service)
if not events:
print("[!] No Mail2Cal events found")
return
# Find duplicates
duplicates = find_duplicates(events)
if not duplicates:
print("[+] No duplicates found!")
return
# Ask for confirmation
print(f"\n[?] Found duplicates. Proceed with cleanup? (y/n): ", end="")
try:
response = input().lower().strip()
if response not in ['y', 'yes']:
print("[!] Cleanup cancelled")
return
except:
print("[!] Cleanup cancelled")
return
# Clean up duplicates
cleanup_duplicates(service, duplicates)
print("\n[+] Duplicate cleanup completed!")
def check_calendar():
"""Check current calendar events"""
print("[*] CALENDAR CHECK - Viewing current events")
print("=" * 60)
service = authenticate()
check_recent_events(service)
def process_files():
"""Process local files (PDFs and images) to create calendar events"""
print("[*] FILE PROCESSING MODE - Processing local files")
print("=" * 60)
# Check dependencies
available, status = check_file_processing_dependencies()
print("File Processing Dependencies:")
print(status)
if not available:
print("\n[-] Required libraries not available. Please install them to continue.")
return
# Initialize Mail2Cal and FileProcessor
try:
app = Mail2Cal()
app.authenticate()
processor = FileEventProcessor(app)
print(f"\n[*] Scanning for files in: {processor.base_directory}")
results = processor.scan_and_process_files()
# Display results
print("\n" + "=" * 60)
print("FILE PROCESSING RESULTS:")
print(f"Files processed: {results['files_processed']}")
print(f"Events created: {results['events_created']}")
print(f"Events updated: {results['events_updated']}")
print(f"Events enhanced: {results.get('events_enhanced', 0)}")
print(f"Files skipped (unchanged): {results['files_skipped']}")
if results.get('errors'):
print(f"Errors: {len(results['errors'])}")
for error in results['errors'][:3]: # Show first 3 errors
print(f" - {error}")
if len(results['errors']) > 3:
print(f" ... and {len(results['errors']) - 3} more errors")
# Show statistics
stats = processor.get_processing_statistics()
print(f"\nTotal statistics:")
print(f" Files tracked: {stats['total_files_processed']}")
print(f" Events created: {stats['total_events_created']}")
print(f" Avg events per file: {stats['average_events_per_file']:.1f}")
if stats['files_by_calendar']:
print(f" Files by calendar: {stats['files_by_calendar']}")
except Exception as e:
print(f"[!] Error during file processing: {e}")
def list_files():
"""List all processed files and their status"""
print("[*] FILE LIST - Showing processed files")
print("=" * 60)
try:
app = Mail2Cal()
app.authenticate()
processor = FileEventProcessor(app)
files = processor.list_processed_files()
if not files:
print("No files have been processed yet.")
print("Use --process-files to scan and process files in local_resources/")
return
print(f"Found {len(files)} processed files:")
print()
for i, file_info in enumerate(files, 1):
print(f"{i:2d}. {file_info['file_name']}")
print(f" Calendar: {file_info['calendar_name']}")
print(f" Events: {file_info['events_count']}")
print(f" Processed: {file_info['processed_at'][:19]}")
print(f" Content: {file_info['content_length']} chars")
print()
except Exception as e:
print(f"[!] Error listing files: {e}")
def check_file_dependencies():
"""Check file processing dependencies"""
print("[*] FILE DEPENDENCIES CHECK")
print("=" * 60)
available, status = check_file_processing_dependencies()
print(status)
if available:
print("\n[+] File processing is ready!")
print("\nDirectory structure expected:")
print("local_resources/")
print("|-- Calendar_1_Pre-Kinder_B/ # Files for Calendar 1 (Pre-Kinder B) only")
print("|-- Calendar_2_Kinder_C/ # Files for Calendar 2 (Kinder C) only")
print("|-- Both/ # Files for both calendars")
print("\nSupported formats: PDF, JPG, PNG, TIFF, BMP, EML")
else:
print("\n[-] File processing not available")
print("\nTo enable PDF processing:")
print(" pip install pdfplumber PyMuPDF")
print("\nTo enable image OCR:")
print(" pip install pillow pytesseract")
print(" (Also requires Tesseract binary installation)")
def recover_deleted_events():
"""Recover events that were incorrectly deleted due to over-aggressive duplicate detection"""
print("[*] EVENT RECOVERY - Restoring incorrectly deleted multi-calendar events")
print("=" * 60)
try:
from utils.recover_deleted_events import main as recovery_main
recovery_main()
except ImportError:
print("[!] Recovery module not found")
except Exception as e:
print(f"[!] Error during recovery: {e}")
def cleanup_teacher_events_dry_run():
"""Clean up misrouted teacher events (dry run)"""
print("[*] TEACHER EVENT CLEANUP (DRY RUN) - Finding misrouted events")
print("=" * 60)
try:
from utils.detect_all_misrouted_events import ComprehensiveMisrouteDetector
detector = ComprehensiveMisrouteDetector()
detector.run_analysis(days_back=30, dry_run=True)
except ImportError:
print("[!] Teacher cleanup tool not available")
except Exception as e:
print(f"[!] Error during cleanup: {e}")
def cleanup_teacher_events_live():
"""Clean up misrouted teacher events (live mode)"""
print("[*] TEACHER EVENT CLEANUP (LIVE) - Deleting misrouted events")
print("=" * 60)
print("[!] WARNING: This will permanently delete events from calendars!")
print("[!] Make sure to run dry-run mode first to review what will be deleted.")
print()
try:
response = input("Are you sure you want to proceed? Type 'DELETE' to confirm: ").strip()
if response != 'DELETE':
print("[!] Cleanup cancelled")
return
from utils.detect_all_misrouted_events import ComprehensiveMisrouteDetector
detector = ComprehensiveMisrouteDetector()
detector.run_analysis(days_back=30, dry_run=False)
except ImportError:
print("[!] Teacher cleanup tool not available")
except Exception as e:
print(f"[!] Error during cleanup: {e}")
def run_full_system():
"""Run the complete Mail2Cal system"""
# Get email count dynamically
try:
from utils.preview_emails import EmailPreview
preview = EmailPreview()
emails = preview.get_school_emails()
email_count = len(emails)
print(f"[*] FULL PROCESSING MODE - All {email_count} emails will be processed with AI")
except:
print("[*] FULL PROCESSING MODE - All emails will be processed with AI")
print("=" * 60)
# Load and validate credentials
ANTHROPIC_API_KEY, GOOGLE_CALENDAR_ID_1, GOOGLE_CALENDAR_ID_2 = load_credentials()
if not ANTHROPIC_API_KEY or not GOOGLE_CALENDAR_ID_1 or not GOOGLE_CALENDAR_ID_2:
print("[-] Error: Missing required credentials from secure storage")
return
print("[!] This will use Anthropic API tokens to process all emails.")
print("[?] Continue? (y/n): ", end="")
try:
response = input().lower().strip()
if response not in ['y', 'yes']:
print("[!] Processing cancelled")
return
except:
print("[!] Processing cancelled")
return
# Run the full system
mail2cal = Mail2Cal()
mail2cal.run()
def main():
"""Main entry point with command-line options"""
parser = argparse.ArgumentParser(
description='Mail2Cal - AI-powered email to calendar converter',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python run_mail2cal.py --preview # Preview emails without using AI tokens
python run_mail2cal.py --test # Test with 3 recent emails
python run_mail2cal.py --cleanup # Clean up duplicate calendar events (basic)
python run_mail2cal.py --check # View current calendar events
python run_mail2cal.py --full # Process all emails with AI
python run_mail2cal.py --recover-events # Recover deleted multi-calendar events
python run_mail2cal.py # Interactive mode (default)
"""
)
parser.add_argument('--preview', action='store_true',
help='Preview emails without using AI tokens')
parser.add_argument('--test', action='store_true',
help='Test with 3 most recent emails')
parser.add_argument('--cleanup', action='store_true',
help='Clean up duplicate calendar events (basic text matching)')
parser.add_argument('--check', action='store_true',
help='Check current calendar events')
parser.add_argument('--full', action='store_true',
help='Process all emails with AI (uses tokens)')
parser.add_argument('--process-files', action='store_true',
help='Process local files (PDFs and images) for calendar events')
parser.add_argument('--list-files', action='store_true',
help='List all processed files and their status')
parser.add_argument('--check-file-deps', action='store_true',
help='Check file processing dependencies')
parser.add_argument('--recover-events', action='store_true',
help='Recover incorrectly deleted multi-calendar events')
parser.add_argument('--limit', type=int, default=3,
help='Number of emails for test mode (default: 3)')
args = parser.parse_args()
# Handle command-line options
if args.preview:
preview_emails()
elif args.test:
test_limited(args.limit)
elif args.cleanup:
cleanup_duplicates_cmd()
elif args.check:
check_calendar()
elif args.full:
run_full_system()
elif args.process_files:
process_files()
elif args.list_files:
list_files()
elif args.check_file_deps:
check_file_dependencies()
elif args.recover_events:
recover_deleted_events()
else:
# Interactive mode
interactive_mode()
def interactive_mode():
"""Interactive mode for selecting options"""
print("""
[*] Mail2Cal - AI-powered Email to Calendar Converter
=====================================================
Select an option:
1. Preview emails (no AI tokens used)
2. Test with 3 recent emails (minimal tokens)
3. Clean up duplicate calendar events (basic)
4. Clean up duplicate calendar events (AI-enhanced)
5. Check current calendar events
6. Process ALL emails (full AI processing)
7. Process local files (PDFs and images)
8. List processed files
9. Check file processing dependencies
10. Recover deleted multi-calendar events
11. Clean up misrouted teacher events (dry-run)
12. Clean up misrouted teacher events (LIVE - deletes events)
13. Exit
""")
try:
choice = input("Enter choice (1-13): ").strip()
if choice == '1':
preview_emails()
elif choice == '2':
test_limited(3)
elif choice == '3':
cleanup_duplicates_cmd()
elif choice == '4':
cleanup_duplicates_smart()
elif choice == '5':
check_calendar()
elif choice == '6':
run_full_system()
elif choice == '7':
process_files()
elif choice == '8':
list_files()
elif choice == '9':
check_file_dependencies()
elif choice == '10':
recover_deleted_events()
elif choice == '11':
cleanup_teacher_events_dry_run()
elif choice == '12':
cleanup_teacher_events_live()
elif choice == '13':
print("Goodbye!")
sys.exit(0)
else:
print("Invalid choice. Please enter 1-13.")
interactive_mode()
except KeyboardInterrupt:
print("\nGoodbye!")
sys.exit(0)
except Exception as e:
print(f"Error: {e}")
interactive_mode()
if __name__ == "__main__":
main()