-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
151 lines (123 loc) · 5.35 KB
/
main.py
File metadata and controls
151 lines (123 loc) · 5.35 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
import schedule
import time
import sys
import os
import logging
import config_manager
import core_processor
import debug_config
from database_manager import DatabaseManager
from imap_client import ImapClient
from translator import Translator
from deadline_detector import DeadlineDetector
def setup_logging():
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("pigeonhunter.log"),
logging.StreamHandler(sys.stdout)
]
)
logging.getLogger("openai").setLevel(logging.WARNING)
logging.getLogger("imapclient").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
def run_job(config, imap_client, translator, db_manager, deadline_detector=None):
logger = logging.getLogger(__name__)
logger.info("Running scheduled job...")
try:
if not imap_client.connect():
logger.error("Failed to connect to IMAP. Skipping this run.")
return
core_processor.process_emails(config, imap_client, translator, db_manager, deadline_detector)
except Exception as e:
logger.error("An unexpected error occurred during processing: %s", e, exc_info=True)
finally:
imap_client.disconnect()
logger.info("Job finished. Waiting for next run...")
def main():
setup_logging()
logger = logging.getLogger(__name__)
logger.info("--- PigeonHunter is starting up ---")
config_path = config_manager.get_config_file_path()
if "--reconfig" in sys.argv:
logger.info("Reconfiguration requested via --reconfig flag.")
if config_path.exists():
try:
os.remove(config_path)
logger.info("Existing config.json deleted.")
except OSError as e:
logger.error(f"Could not delete config file: {e}. Exiting.")
sys.exit()
else:
logger.info("No existing config file to delete.")
if not config_path.exists():
logger.warning("No config file found. Running first-time setup.")
if not config_manager.run_first_time_setup():
logger.error("Configuration setup FAILED. Exiting.")
sys.exit()
else:
logger.info("Setup complete! Configuration saved. Please restart the application to begin.")
sys.exit()
config = config_manager.load_config()
if not config:
logger.critical("Failed to load config. Exiting.")
sys.exit()
logger.debug("Configuration loaded successfully.")
try:
db_manager = DatabaseManager()
db_manager.create_table()
except Exception as e:
logger.critical("Failed to initialize database. Exiting. Error: %s", e)
sys.exit()
try:
imap = ImapClient(
config['imap']['server'],
config['imap']['user'],
config['imap']['password']
)
translator = Translator(config['openai']['api_key'])
deadline_detector = None
config_enabled = config.get('general', {}).get('enable_deadline_detection', False)
if config_enabled or debug_config.DEBUG_SCAN_DSPH:
deadline_detector = DeadlineDetector(config['openai']['api_key'])
if debug_config.DEBUG_SCAN_DSPH:
logger.warning("DEBUG MODE: ONLY processing DSPH-prefixed emails (ignoring all others)")
if config_enabled:
logger.info("Deadline detection enabled via configuration.")
if not config_enabled and debug_config.DEBUG_SCAN_DSPH:
logger.info("Deadline detection enabled for debug mode.")
else:
logger.info("Deadline detection disabled.")
except KeyError as e:
logger.critical("Config file is missing a required key: %s. Exiting.", e)
sys.exit()
interval = config['general']['check_interval_minutes']
should_run_initial_scan = config['general'].get('run_initial_scan', False) or debug_config.DEBUG_SCAN_DSPH
if should_run_initial_scan:
if debug_config.DEBUG_SCAN_DSPH:
logger.info("DEBUG MODE: Running initial scan to process DSPH emails...")
else:
logger.info("Performing one-time initial scan as requested by config...")
run_job(config, imap, translator, db_manager, deadline_detector)
if config['general'].get('run_initial_scan', False):
logger.debug("Disabling 'run_initial_scan' flag in config.")
config['general']['run_initial_scan'] = False
config_manager.save_config(config)
logger.info("Initial scan complete.")
logger.info(f"Scheduling job every {interval} minutes.")
print(f"--- PigeonHunter is running ---")
print(f"Checking folders every {interval} minutes. Press Ctrl+C to stop.")
print("Logs are being saved to 'pigeonhunter.log'")
schedule.every(interval).minutes.do(run_job, config, imap, translator, db_manager, deadline_detector)
try:
while True:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
logger.warning("\nShutdown signal received. Shutting down PigeonHunter...")
db_manager.close()
print("\nShutting down PigeonHunter...")
if __name__ == "__main__":
main()