-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
main.py
566 lines (492 loc) · 21.7 KB
/
main.py
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import base64
import sys
from pathlib import Path
import traceback
from typing import List, Optional, Tuple, Dict
import click
import inquirer
import yaml
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import re
from src.libs.resume_and_cover_builder import ResumeFacade, ResumeGenerator, StyleManager
from src.resume_schemas.job_application_profile import JobApplicationProfile
from src.resume_schemas.resume import Resume
from src.logging import logger
from src.utils.chrome_utils import init_browser
from src.utils.constants import (
PLAIN_TEXT_RESUME_YAML,
SECRETS_YAML,
WORK_PREFERENCES_YAML,
)
# from ai_hawk.bot_facade import AIHawkBotFacade
# from ai_hawk.job_manager import AIHawkJobManager
# from ai_hawk.llm.llm_manager import GPTAnswerer
class ConfigError(Exception):
"""Custom exception for configuration-related errors."""
pass
class ConfigValidator:
"""Validates configuration and secrets YAML files."""
EMAIL_REGEX = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
REQUIRED_CONFIG_KEYS = {
"remote": bool,
"experience_level": dict,
"job_types": dict,
"date": dict,
"positions": list,
"locations": list,
"location_blacklist": list,
"distance": int,
"company_blacklist": list,
"title_blacklist": list,
}
EXPERIENCE_LEVELS = [
"internship",
"entry",
"associate",
"mid_senior_level",
"director",
"executive",
]
JOB_TYPES = [
"full_time",
"contract",
"part_time",
"temporary",
"internship",
"other",
"volunteer",
]
DATE_FILTERS = ["all_time", "month", "week", "24_hours"]
APPROVED_DISTANCES = {0, 5, 10, 25, 50, 100}
@staticmethod
def validate_email(email: str) -> bool:
"""Validate the format of an email address."""
return bool(ConfigValidator.EMAIL_REGEX.match(email))
@staticmethod
def load_yaml(yaml_path: Path) -> dict:
"""Load and parse a YAML file."""
try:
with open(yaml_path, "r") as stream:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
raise ConfigError(f"Error reading YAML file {yaml_path}: {exc}")
except FileNotFoundError:
raise ConfigError(f"YAML file not found: {yaml_path}")
@classmethod
def validate_config(cls, config_yaml_path: Path) -> dict:
"""Validate the main configuration YAML file."""
parameters = cls.load_yaml(config_yaml_path)
# Check for required keys and their types
for key, expected_type in cls.REQUIRED_CONFIG_KEYS.items():
if key not in parameters:
if key in ["company_blacklist", "title_blacklist", "location_blacklist"]:
parameters[key] = []
else:
raise ConfigError(f"Missing required key '{key}' in {config_yaml_path}")
elif not isinstance(parameters[key], expected_type):
if key in ["company_blacklist", "title_blacklist", "location_blacklist"] and parameters[key] is None:
parameters[key] = []
else:
raise ConfigError(
f"Invalid type for key '{key}' in {config_yaml_path}. Expected {expected_type.__name__}."
)
cls._validate_experience_levels(parameters["experience_level"], config_yaml_path)
cls._validate_job_types(parameters["job_types"], config_yaml_path)
cls._validate_date_filters(parameters["date"], config_yaml_path)
cls._validate_list_of_strings(parameters, ["positions", "locations"], config_yaml_path)
cls._validate_distance(parameters["distance"], config_yaml_path)
cls._validate_blacklists(parameters, config_yaml_path)
return parameters
@classmethod
def _validate_experience_levels(cls, experience_levels: dict, config_path: Path):
"""Ensure experience levels are booleans."""
for level in cls.EXPERIENCE_LEVELS:
if not isinstance(experience_levels.get(level), bool):
raise ConfigError(
f"Experience level '{level}' must be a boolean in {config_path}"
)
@classmethod
def _validate_job_types(cls, job_types: dict, config_path: Path):
"""Ensure job types are booleans."""
for job_type in cls.JOB_TYPES:
if not isinstance(job_types.get(job_type), bool):
raise ConfigError(
f"Job type '{job_type}' must be a boolean in {config_path}"
)
@classmethod
def _validate_date_filters(cls, date_filters: dict, config_path: Path):
"""Ensure date filters are booleans."""
for date_filter in cls.DATE_FILTERS:
if not isinstance(date_filters.get(date_filter), bool):
raise ConfigError(
f"Date filter '{date_filter}' must be a boolean in {config_path}"
)
@classmethod
def _validate_list_of_strings(cls, parameters: dict, keys: list, config_path: Path):
"""Ensure specified keys are lists of strings."""
for key in keys:
if not all(isinstance(item, str) for item in parameters[key]):
raise ConfigError(
f"'{key}' must be a list of strings in {config_path}"
)
@classmethod
def _validate_distance(cls, distance: int, config_path: Path):
"""Validate the distance value."""
if distance not in cls.APPROVED_DISTANCES:
raise ConfigError(
f"Invalid distance value '{distance}' in {config_path}. Must be one of: {cls.APPROVED_DISTANCES}"
)
@classmethod
def _validate_blacklists(cls, parameters: dict, config_path: Path):
"""Ensure blacklists are lists."""
for blacklist in ["company_blacklist", "title_blacklist", "location_blacklist"]:
if not isinstance(parameters.get(blacklist), list):
raise ConfigError(
f"'{blacklist}' must be a list in {config_path}"
)
if parameters[blacklist] is None:
parameters[blacklist] = []
@staticmethod
def validate_secrets(secrets_yaml_path: Path) -> str:
"""Validate the secrets YAML file and retrieve the LLM API key."""
secrets = ConfigValidator.load_yaml(secrets_yaml_path)
mandatory_secrets = ["llm_api_key"]
for secret in mandatory_secrets:
if secret not in secrets:
raise ConfigError(f"Missing secret '{secret}' in {secrets_yaml_path}")
if not secrets[secret]:
raise ConfigError(f"Secret '{secret}' cannot be empty in {secrets_yaml_path}")
return secrets["llm_api_key"]
class FileManager:
"""Handles file system operations and validations."""
REQUIRED_FILES = [SECRETS_YAML, WORK_PREFERENCES_YAML, PLAIN_TEXT_RESUME_YAML]
@staticmethod
def validate_data_folder(app_data_folder: Path) -> Tuple[Path, Path, Path, Path]:
"""Validate the existence of the data folder and required files."""
if not app_data_folder.is_dir():
raise FileNotFoundError(f"Data folder not found: {app_data_folder}")
missing_files = [file for file in FileManager.REQUIRED_FILES if not (app_data_folder / file).exists()]
if missing_files:
raise FileNotFoundError(f"Missing files in data folder: {', '.join(missing_files)}")
output_folder = app_data_folder / "output"
output_folder.mkdir(exist_ok=True)
return (
app_data_folder / SECRETS_YAML,
app_data_folder / WORK_PREFERENCES_YAML,
app_data_folder / PLAIN_TEXT_RESUME_YAML,
output_folder,
)
@staticmethod
def get_uploads(plain_text_resume_file: Path) -> Dict[str, Path]:
"""Convert resume file paths to a dictionary."""
if not plain_text_resume_file.exists():
raise FileNotFoundError(f"Plain text resume file not found: {plain_text_resume_file}")
uploads = {"plainTextResume": plain_text_resume_file}
return uploads
def create_cover_letter(parameters: dict, llm_api_key: str):
"""
Logic to create a CV.
"""
try:
logger.info("Generating a CV based on provided parameters.")
# Carica il resume in testo semplice
with open(parameters["uploads"]["plainTextResume"], "r", encoding="utf-8") as file:
plain_text_resume = file.read()
style_manager = StyleManager()
style_manager = StyleManager()
available_styles = style_manager.get_styles()
if not available_styles:
logger.warning("No styles available. Proceeding without style selection.")
else:
# Present style choices to the user
choices = style_manager.format_choices(available_styles)
questions = [
inquirer.List(
"style",
message="Select a style for the resume:",
choices=choices,
)
]
style_answer = inquirer.prompt(questions)
if style_answer and "style" in style_answer:
selected_choice = style_answer["style"]
for style_name, (file_name, author_link) in available_styles.items():
if selected_choice.startswith(style_name):
style_manager.set_selected_style(style_name)
logger.info(f"Selected style: {style_name}")
break
else:
logger.warning("No style selected. Proceeding with default style.")
questions = [
inquirer.Text('job_url', message="Please enter the URL of the job description:")
]
answers = inquirer.prompt(questions)
job_url = answers.get('job_url')
resume_generator = ResumeGenerator()
resume_object = Resume(plain_text_resume)
driver = init_browser()
resume_generator.set_resume_object(resume_object)
resume_facade = ResumeFacade(
api_key=llm_api_key,
style_manager=style_manager,
resume_generator=resume_generator,
resume_object=resume_object,
output_path=Path("data_folder/output"),
)
resume_facade.set_driver(driver)
resume_facade.link_to_job(job_url)
result_base64, suggested_name = resume_facade.create_cover_letter()
# Decodifica Base64 in dati binari
try:
pdf_data = base64.b64decode(result_base64)
except base64.binascii.Error as e:
logger.error("Error decoding Base64: %s", e)
raise
# Definisci il percorso della cartella di output utilizzando `suggested_name`
output_dir = Path(parameters["outputFileDirectory"]) / suggested_name
# Crea la cartella se non esiste
try:
output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Cartella di output creata o già esistente: {output_dir}")
except IOError as e:
logger.error("Error creating output directory: %s", e)
raise
output_path = output_dir / "cover_letter_tailored.pdf"
try:
with open(output_path, "wb") as file:
file.write(pdf_data)
logger.info(f"CV salvato in: {output_path}")
except IOError as e:
logger.error("Error writing file: %s", e)
raise
except Exception as e:
logger.exception(f"An error occurred while creating the CV: {e}")
raise
def create_resume_pdf_job_tailored(parameters: dict, llm_api_key: str):
"""
Logic to create a CV.
"""
try:
logger.info("Generating a CV based on provided parameters.")
# Carica il resume in testo semplice
with open(parameters["uploads"]["plainTextResume"], "r", encoding="utf-8") as file:
plain_text_resume = file.read()
style_manager = StyleManager()
available_styles = style_manager.get_styles()
if not available_styles:
logger.warning("No styles available. Proceeding without style selection.")
else:
# Present style choices to the user
choices = style_manager.format_choices(available_styles)
questions = [
inquirer.List(
"style",
message="Select a style for the resume:",
choices=choices,
)
]
style_answer = inquirer.prompt(questions)
if style_answer and "style" in style_answer:
selected_choice = style_answer["style"]
for style_name, (file_name, author_link) in available_styles.items():
if selected_choice.startswith(style_name):
style_manager.set_selected_style(style_name)
logger.info(f"Selected style: {style_name}")
break
else:
logger.warning("No style selected. Proceeding with default style.")
questions = [inquirer.Text('job_url', message="Please enter the URL of the job description:")]
answers = inquirer.prompt(questions)
job_url = answers.get('job_url')
resume_generator = ResumeGenerator()
resume_object = Resume(plain_text_resume)
driver = init_browser()
resume_generator.set_resume_object(resume_object)
resume_facade = ResumeFacade(
api_key=llm_api_key,
style_manager=style_manager,
resume_generator=resume_generator,
resume_object=resume_object,
output_path=Path("data_folder/output"),
)
resume_facade.set_driver(driver)
resume_facade.link_to_job(job_url)
result_base64, suggested_name = resume_facade.create_resume_pdf_job_tailored()
# Decodifica Base64 in dati binari
try:
pdf_data = base64.b64decode(result_base64)
except base64.binascii.Error as e:
logger.error("Error decoding Base64: %s", e)
raise
# Definisci il percorso della cartella di output utilizzando `suggested_name`
output_dir = Path(parameters["outputFileDirectory"]) / suggested_name
# Crea la cartella se non esiste
try:
output_dir.mkdir(parents=True, exist_ok=True)
logger.info(f"Cartella di output creata o già esistente: {output_dir}")
except IOError as e:
logger.error("Error creating output directory: %s", e)
raise
output_path = output_dir / "resume_tailored.pdf"
try:
with open(output_path, "wb") as file:
file.write(pdf_data)
logger.info(f"CV salvato in: {output_path}")
except IOError as e:
logger.error("Error writing file: %s", e)
raise
except Exception as e:
logger.exception(f"An error occurred while creating the CV: {e}")
raise
def create_resume_pdf(parameters: dict, llm_api_key: str):
"""
Logic to create a CV.
"""
try:
logger.info("Generating a CV based on provided parameters.")
# Load the plain text resume
with open(parameters["uploads"]["plainTextResume"], "r", encoding="utf-8") as file:
plain_text_resume = file.read()
# Initialize StyleManager
style_manager = StyleManager()
available_styles = style_manager.get_styles()
if not available_styles:
logger.warning("No styles available. Proceeding without style selection.")
else:
# Present style choices to the user
choices = style_manager.format_choices(available_styles)
questions = [
inquirer.List(
"style",
message="Select a style for the resume:",
choices=choices,
)
]
style_answer = inquirer.prompt(questions)
if style_answer and "style" in style_answer:
selected_choice = style_answer["style"]
for style_name, (file_name, author_link) in available_styles.items():
if selected_choice.startswith(style_name):
style_manager.set_selected_style(style_name)
logger.info(f"Selected style: {style_name}")
break
else:
logger.warning("No style selected. Proceeding with default style.")
# Initialize the Resume Generator
resume_generator = ResumeGenerator()
resume_object = Resume(plain_text_resume)
driver = init_browser()
resume_generator.set_resume_object(resume_object)
# Create the ResumeFacade
resume_facade = ResumeFacade(
api_key=llm_api_key,
style_manager=style_manager,
resume_generator=resume_generator,
resume_object=resume_object,
output_path=Path("data_folder/output"),
)
resume_facade.set_driver(driver)
result_base64 = resume_facade.create_resume_pdf()
# Decode Base64 to binary data
try:
pdf_data = base64.b64decode(result_base64)
except base64.binascii.Error as e:
logger.error("Error decoding Base64: %s", e)
raise
# Define the output directory using `suggested_name`
output_dir = Path(parameters["outputFileDirectory"])
# Write the PDF file
output_path = output_dir / "resume_base.pdf"
try:
with open(output_path, "wb") as file:
file.write(pdf_data)
logger.info(f"Resume saved at: {output_path}")
except IOError as e:
logger.error("Error writing file: %s", e)
raise
except Exception as e:
logger.exception(f"An error occurred while creating the CV: {e}")
raise
def handle_inquiries(selected_actions: List[str], parameters: dict, llm_api_key: str):
"""
Decide which function to call based on the selected user actions.
:param selected_actions: List of actions selected by the user.
:param parameters: Configuration parameters dictionary.
:param llm_api_key: API key for the language model.
"""
try:
if selected_actions:
if "Generate Resume" == selected_actions:
logger.info("Crafting a standout professional resume...")
create_resume_pdf(parameters, llm_api_key)
if "Generate Resume Tailored for Job Description" == selected_actions:
logger.info("Customizing your resume to enhance your job application...")
create_resume_pdf_job_tailored(parameters, llm_api_key)
if "Generate Tailored Cover Letter for Job Description" == selected_actions:
logger.info("Designing a personalized cover letter to enhance your job application...")
create_cover_letter(parameters, llm_api_key)
else:
logger.warning("No actions selected. Nothing to execute.")
except Exception as e:
logger.exception(f"An error occurred while handling inquiries: {e}")
raise
def prompt_user_action() -> str:
"""
Use inquirer to ask the user which action they want to perform.
:return: Selected action.
"""
try:
questions = [
inquirer.List(
'action',
message="Select the action you want to perform:",
choices=[
"Generate Resume",
"Generate Resume Tailored for Job Description",
"Generate Tailored Cover Letter for Job Description",
],
),
]
answer = inquirer.prompt(questions)
if answer is None:
print("No answer provided. The user may have interrupted.")
return ""
return answer.get('action', "")
except Exception as e:
print(f"An error occurred: {e}")
return ""
def main():
"""Main entry point for the AIHawk Job Application Bot."""
try:
# Define and validate the data folder
data_folder = Path("data_folder")
secrets_file, config_file, plain_text_resume_file, output_folder = FileManager.validate_data_folder(data_folder)
# Validate configuration and secrets
config = ConfigValidator.validate_config(config_file)
llm_api_key = ConfigValidator.validate_secrets(secrets_file)
# Prepare parameters
config["uploads"] = FileManager.get_uploads(plain_text_resume_file)
config["outputFileDirectory"] = output_folder
# Interactive prompt for user to select actions
selected_actions = prompt_user_action()
# Handle selected actions and execute them
handle_inquiries(selected_actions, config, llm_api_key)
except ConfigError as ce:
logger.error(f"Configuration error: {ce}")
logger.error(
"Refer to the configuration guide for troubleshooting: "
"https://github.com/feder-cr/Auto_Jobs_Applier_AIHawk?tab=readme-ov-file#configuration"
)
except FileNotFoundError as fnf:
logger.error(f"File not found: {fnf}")
logger.error("Ensure all required files are present in the data folder.")
except RuntimeError as re:
logger.error(f"Runtime error: {re}")
logger.debug(traceback.format_exc())
except Exception as e:
logger.exception(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
main()