-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoutput.txt
1745 lines (1432 loc) · 65.9 KB
/
output.txt
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
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
File: datamanger.py
==================================================
import mysql.connector
from mysql.connector import Error
import os
import sys
# current_dir = os.path.dirname(os.path.abspath(__file__))
# sys.path.insert(0, current_dir)
class DataManager:
def __init__(self, host, user, password, database):
self.host = host
self.user = user
self.password = password
self.database = database
self.connection = None
self.cursor = None
def connect(self):
try:
# First, connect to MySQL server without specifying a database
self.connection = mysql.connector.connect(
host=self.host,
user=self.user,
password=self.password
)
if self.connection.is_connected():
self.cursor = self.connection.cursor()
# Check if the database exists
self.cursor.execute(f"SHOW DATABASES LIKE '{self.database}'")
result = self.cursor.fetchone()
if not result:
# Create the database if it doesn't exist
self.cursor.execute(f"CREATE DATABASE {self.database}")
print(f"Database '{self.database}' created successfully.")
# Connect to the specific database
self.connection.database = self.database
print(f"Connected to database '{self.database}'.")
except Error as e:
print(f"Error connecting to MySQL: {e}")
def disconnect(self):
if self.connection and self.connection.is_connected():
if self.cursor:
self.cursor.close()
self.connection.close()
print("MySQL connection closed.")
def execute_query(self, query):
try:
self.cursor.execute(query)
self.connection.commit()
print("Query executed successfully.")
except Error as e:
print(f"Error executing query: {e}")
# Add more methods for database operations as needed
==================================================
File: main.py
==================================================
# from g4f.client import Client
# import os.path
# from g4f.cookies import set_cookies_dir, read_cookie_files
# from g4f.Provider import (Liaobots)
# import g4f
# import g4f.debug
# g4f.debug.logging = True
# cookies_dir = os.path.join(os.path.dirname(__file__), "har_and_cookies")
# set_cookies_dir(cookies_dir)
# read_cookie_files(cookies_dir)
# client = Client(Liaobots)
# response = client.chat.completions.create(
# model=g4f.models.gpt_4o,
# messages=[{"role": "user", "content": "Tell me about Coveo company for my interview"}],
# )
# print(response.choices[0].message.content)
# from LinkedIn.linkedIn import LinkedIn
# linkedin = LinkedIn("krishnavalliappan02@gmail.com", "YE$35A!GJjn@AQ!3")
# linkedin.search_jobs_runner("data analyst", time_filter=2)
# from datamanger import DataManager
# dm = DataManager("localhost", "root", "welcome123", "linkedin_data")
# # Connect to the database (creates it if it doesn't exist)
# dm.connect()
# # Execute a sample query (e.g., create a table)
# # dm.execute_query("""
# # CREATE TABLE IF NOT EXISTS users (
# # id INT AUTO_INCREMENT PRIMARY KEY,
# # name VARCHAR(255),
# # email VARCHAR(255)
# # )
# # """)
# # Disconnect when done
# dm.disconnect()
# In main.py:
# from processData import ProcessData
# import asyncio
# from linkedin.linkedIn import LinkedIn
# from ResumeManager.resumeManager import ResumeManager
# import os
# import pandas as pd
# from dotenv import load_dotenv
# from notion_manager import NotionManager
# load_dotenv()
# async def main():
# linkedin_email = os.environ.get('LINKEDIN_EMAIL')
# linkedin_password = os.environ.get('LINKEDIN_PASSWORD')
# database_id = "7585377689d14a70bce0e38935403a1b"
# if not linkedin_email or not linkedin_password:
# raise ValueError("LinkedIn credentials not set in environment variables")
# try:
# linkedin = LinkedIn(linkedin_email, linkedin_password)
# linkedin.search_jobs_runner("Data Analyst", time_filter=1)
# data = linkedin.scraped_job_data
# # data = pd.read_csv("job_application_pre_processing.csv")
# process_data = ProcessData(data)
# await process_data.analyze_job()
# # create resumes and cover_letters
# new_df = process_data.df_new
# ResumeManager(new_df)
# notion = NotionManager(database_id=database_id)
# notion.one_way_sync(new_df)
# except Exception as e:
# print(f"An error occurred: {e}")
# if __name__ == "__main__":
# asyncio.run(main())
from src.scraper_linkedin import LinkedIn
from src.processor import DataProcessor
import logging
import asyncio
import pandas as pd
from src.document_generator import ResumeManager
from src.notion_integration import NotionManager
from src.utilities import duration_to_seconds
async def main():
logging.basicConfig(
filename='linkedin_search.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# linkedin = LinkedIn()
# linkedin.search_jobs_runner("full stack developer", experience_level="2", time_filter="1 day")
# scraped_data = linkedin.get_scraped_data()
scraped_data = pd.read_csv("job_application_pre_processing.csv")
data_processor = DataProcessor(scraped_data)
await data_processor.analyze_jobs()
data = data_processor.get_processed_data()
ResumeManager(data)
NotionManager(data)
if __name__ == "__main__":
asyncio.run(main())
==================================================
File: src/__init__.py
==================================================
# src/__init__.py
# You can leave this file empty if you don't need any initialization code
# Optionally, you can import and expose specific modules or functions
from .scraper_linkedin import LinkedIn
# from .processor import DataProcessor, GPTProcessor
# from .document_generator import WordGenerator, PDFGenerator
# from .notion_integration import NotionManager
# If you want to define a version for your package
__version__ = "0.1.0"
# You can also include any initialization code here if needed
# For example, setting up logging for the entire package
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
==================================================
File: src/config/__init__.py
==================================================
from .settings import *
==================================================
File: src/config/settings.py
==================================================
import os
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# LinkedIn credentials
LINKEDIN_EMAIL = os.getenv("LINKEDIN_EMAIL")
LINKEDIN_PASSWORD = os.getenv("LINKEDIN_PASSWORD")
# Notion settings
NOTION_API_KEY = os.getenv("NOTION_API_KEY")
NOTION_DATABASE_ID = os.getenv("NOTION_DATABASE_ID")
# File paths
RESUME_PDF_PATH = os.path.join("templates", "resume.pdf")
RESUME_TEMPLATES_DIR = os.path.join("templates")
OUTPUT_RESUMES_DIR = os.path.join("output", "resumes")
# LinkedIn scraper settings
COOKIE_FILE = "cookies/linkedin_cookies.pkl"
# Job search settings
DEFAULT_SORT_BY = "DD"
DEFAULT_TIME_FILTER = "1 day" # in days
DEFAULT_EXPERIENCE_LEVEL = "2,3"
DEFAULT_DISTANCE = 25
"""
LinkedIn GeoID Configuration
The `geo_id` parameter is used to filter job listings by geographic location in LinkedIn's job search.
Default is set to Canada (geo_id: 101174742).
To customize the geo_id for a different location:
1. Open an incognito/private browsing window to avoid personalized results.
2. Navigate to LinkedIn's job search page (https://www.linkedin.com/jobs/).
3. In the location filter input, enter your desired region.
4. Select the appropriate option from the autocomplete dialog.
5. After the results load, examine the URL in the address bar.
6. Locate the `geoId` parameter in the URL. For example:
https://www.linkedin.com/jobs/search?keywords=&location=Canada&geoId=101174742&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0
In this example, the geo_id for Canada is 101174742.
Note: LinkedIn may update their URL structure or geo_id values over time.
Always verify the current format and values before use.
"""
DEFAULT_GEO_ID = "101174742"
DEFAULT_JOB_FUNCTION = "it%2Canls"
DEFAULT_INDUSTRY = None
# Logging settings
LOG_FILE = os.path.join("logs", "app.log")
LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s'
# GPT settings
GPT_MODEL_PRIMARY = "gpt-4o-mini"
GPT_MODEL_SECONDARY = "gpt-3.5-turbo"
# Proxy settings
PROXY_URL = "https://free-proxy-list.net/"
# Notion schema
NOTION_SCHEMA = {
"job_position_title": {
"type": "title",
"notion_prop_name": "Job Role"
},
"job_id": {
"type": "number",
"notion_prop_name": "Job ID"
},
"job_position_link": {
"type": "url",
"notion_prop_name": "Job Link"
},
"company_name": {
"type": "select",
"notion_prop_name": "Company"
},
"location": {
"type": "select",
"notion_prop_name": "Location"
},
"days_ago": {
"type": "rich_text",
"notion_prop_name": "Posted"
},
"no_of_applicants": {
"type": "number",
"notion_prop_name": "Applicants"
},
"salary": {
"type": "rich_text",
"notion_prop_name": "Salary"
},
"workplace": {
"type": "select",
"notion_prop_name": "Workplace"
},
"job_type": {
"type": "select",
"notion_prop_name": "Job Type"
},
"experience_level": {
"type": "select",
"notion_prop_name": "Experience Level"
},
"industry": {
"type": "select",
"notion_prop_name": "Industry"
},
"is_easy_apply": {
"type": "checkbox",
"notion_prop_name": "Easy Apply"
},
"apply_link": {
"type": "url",
"notion_prop_name": "Apply Link"
},
"posted_date": {
"type": "date",
"notion_prop_name": "Posted Date"
},
"top_skills": {
"type": "multi_select",
"notion_prop_name": "Top Skills"
},
"job_category": {
"type": "select",
"notion_prop_name": "Job Category"
}
}
# Add any other configuration variables here
==================================================
File: src/processor/data_processor.py
==================================================
import pandas as pd
import PyPDF2
from typing import List, Dict, Any
from src.utilities import calculate_posted_time
from src.processor.gpt_processor import JobAnalyzer
from src.config import RESUME_PDF_PATH
class DataProcessor:
def __init__(self, data: List[Dict[str, Any]], resume_path: str = RESUME_PDF_PATH):
self.df_new = self._create_df(data)
self.resume = self._read_pdf_resume(resume_path)
# self._preprocess_data()
def _create_df(self, data: List[Dict[str, Any]]) -> pd.DataFrame:
return pd.DataFrame(data)
def _preprocess_data(self) -> None:
self._remove_duplicates()
self._add_posted_date()
self._compare_with_existing_data()
self._save_preprocessed_data()
def _remove_duplicates(self) -> None:
self.df_new = self.df_new.drop_duplicates(subset=['job_id'], keep='first')
self.df_new = self._custom_drop_duplicates('apply_link')
def _custom_drop_duplicates(self, column: str) -> pd.DataFrame:
seen = set()
return self.df_new[self.df_new[column].apply(lambda x: x == "" or (x not in seen and not seen.add(x)))]
def _add_posted_date(self) -> None:
self.df_new['posted_date'] = self.df_new['days_ago'].apply(calculate_posted_time)
def _compare_with_existing_data(self) -> None:
try:
old_df = pd.read_csv("job_application.csv")
existing_job_ids = set(old_df['job_id'])
self.df_new = self.df_new[~self.df_new['job_id'].isin(existing_job_ids)]
except FileNotFoundError:
print("No existing job_application.csv found. Processing all data as new.")
def _save_preprocessed_data(self) -> None:
self.df_new.to_csv("job_application_pre_processing.csv", index=False)
async def analyze_jobs(self) -> None:
try:
analyzer = JobAnalyzer(self.df_new, self.resume)
df_new, df_update = await analyzer.process_jobs()
self.df_new = pd.merge(self.df_new, df_new, on='job_id', how='left')
self.df_new.update(df_update)
self._append_data_to_csv()
except Exception as e:
print(f"An error occurred during job analysis: {str(e)}")
def _append_data_to_csv(self) -> None:
try:
with open('job_application.csv', 'a') as f:
f.write('\n')
self.df_new.to_csv('job_application.csv', mode='a', header=False, index=False)
except Exception as e:
print(f"Error appending data to CSV: {str(e)}")
@staticmethod
def _read_pdf_resume(file_path: str) -> str:
try:
with open(file_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
return " ".join(page.extract_text() for page in reader.pages)
except Exception as e:
print(f"Error reading PDF resume: {str(e)}")
return ""
def get_processed_data(self) -> pd.DataFrame:
return self.df_new
==================================================
File: src/processor/__init__.py
==================================================
from .data_processor import DataProcessor
from .gpt_processor import JobAnalyzer
==================================================
File: src/processor/gpt_processor.py
==================================================
from http import client
import json
import asyncio
from enum import Enum
from typing import List, Optional, Dict, Tuple, Any
from pydantic import BaseModel, Field
from langchain.llms.base import LLM
import g4f
from langchain.prompts import PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from g4f.client import Client
import os
import re
import pandas as pd
from src.utilities.proxies import ProxyRotator
from src.config import GPT_MODEL_PRIMARY, GPT_MODEL_SECONDARY
class JobCategory(str, Enum):
DATA = "data analyst role"
BUSINESS = "business analyst role"
WEB = "SDE role"
class JobAnalysisOutput(BaseModel):
skills_in_priority_order: List[str] = Field(description="Top 3 technical tools and tech stack mentioned in job description which I know as per my resume")
job_category: JobCategory = Field(description="Categorization of the job role")
why_this_company: str = Field(description="Personalized 'Why This Company' paragraph")
why_me: str = Field(description="Personalized 'Why Me' paragraph")
job_position_title: str = Field(description="Formatted job position title in English")
company_name: str = Field(description="Formatted company name in English")
location: str = Field(description="Location of company who posted job post")
# proxy_rotator = ProxyRotator()
class EducationalLLM(LLM):
@property
def _llm_type(self) -> str:
return "custom"
def _call(self, prompt: str, stop: Optional[List[str]] = None, run_manager=None, **kwargs) -> str:
max_retries = 2
for attempt in range(max_retries):
try:
return self._attempt_call(prompt, stop)
except Exception as e:
self._handle_call_exception(e, attempt)
return self._fallback_call(prompt, stop)
def _attempt_call(self, prompt: str, stop: Optional[List[str]]) -> str:
# client = Client(proxies=proxy_rotator.get_proxy())
client = Client()
response = client.chat.completions.create(
model=GPT_MODEL_PRIMARY,
messages=[{"role": "user", "content": prompt}],
)
out = response.choices[0].message.content
return self._process_output(out, stop)
def _handle_call_exception(self, e: Exception, attempt: int):
print(f"Attempt {attempt + 1} failed with proxy: {str(e)}")
# proxy_rotator.remove_current_proxy()
# if not proxy_rotator.proxies:
# proxy_rotator.refresh_proxies()
def _fallback_call(self, prompt: str, stop: Optional[List[str]]) -> str:
print("Attempting to connect without a proxy...")
client = Client()
response = client.chat.completions.create(
model=GPT_MODEL_SECONDARY,
messages=[{"role": "user", "content": prompt}],
)
out = response.choices[0].message.content
return self._process_output(out, stop)
def _process_output(self, out: str, stop: Optional[List[str]]) -> str:
if stop:
stop_indexes = (out.find(s) for s in stop if s in out)
min_stop = min(stop_indexes, default=-1)
if min_stop > -1:
out = out[:min_stop]
return out
class JobAnalyzer:
def __init__(self, df: Optional[pd.DataFrame] = None, resume_text: Optional[str] = None):
self.llm = EducationalLLM()
self.df = df
self.resume_text = resume_text
def _get_prompt(self) -> PromptTemplate:
template = """
Analyze the following job description and resume, then provide the requested information:
Job Description:
{job_description}
Resume:
{resume}
Company Name: {company_name}
Job Position Title: {job_position_title}
location: {location}
Please provide the following information:
1. List the top 3 technical tools and the tech stack that are mentioned in the job description, which I'm familiar with as per my given resume. Include Python by default, listed in priority order.
2. Categorization of the job role: data analyst role, business analyst role, or SDE role
3. A personalized 'Why This Company' paragraph (see instructions below)
4. A personalized 'Why Me' paragraph (see instructions below)
5. A formatted job position title in English, remove any unwanted characters which can't be allowed in directory creation and ensuring it's professional which I can use it in my resume. Make it short if its too long and a typical one.
6. A formatted company name in English, removing any unwanted characters which can't be allowed in directory or file creation. If the company name is only in French, leave it as is.
7. Formatted location of compnay like this "City, Country"
Instructions for 'Why This Company':
Generate a paragraph that includes the following elements: Do web search and know about company.
• An understanding of the company's mission, vision, and values.
• Specific details about the company's products, services, and market position.
• A mention of the company's reputation and culture.
• How the company's direction and growth opportunities align with the candidate's career aspirations.
• Why the candidate is excited about the company.
example: 'Affirm's innovative approach to consumer finance is a major factor that draws me to this role. Affirm's
commitment to transparency and creating consumer-friendly financial products aligns perfectly with my
values and career goals. I am particularly impressed by Affirm's dedication to eliminating hidden fees and
providing clear, upfront information to consumers, which resonates with my passion for ethical financial
practices. The opportunity to work at a company that leverages cutting-edge technology to optimize
portfolio economics and consumer growth is incredibly exciting to me. I am eager to contribute to Affirm's
mission of delivering honest financial products that improve lives.'
length: follow the length of the example provided.
Instructions for 'Why Me':
Generate a paragraph that includes the following elements:
• Relevant experience and skills that match the job requirements.
• Specific achievements that demonstrate the candidate's capabilities.
• How the candidate's skills and experience align with the company's needs.
• The candidate's passion for the industry or role.
• A brief, professional mention of hoping to master pizza-making before the interview call.
example: 'With over three years of experience as a Data Analyst, I bring strong analytical skills and proficiency in
SQL, Python, and VBA, essential for the Quantitative Analyst role at Affirm. My achievements include
boosting sales projections by 15% with predictive models and enhancing system reliability through
automated monitoring. My collaborative and problem-solving abilities make me a great fit for this role. I
am confident my technical expertise and passion for fintech innovation will significantly contribute to
Affirm's success. I look forward to discussing how I can add value, hopefully before perfecting my
homemade pizza recipe!'
length: follow the length of the example provided.
Format your response as a JSON object with the following keys:
skills_in_priority_order, job_category, why_this_company, why_me, job_position_title, company_name, location.
"""
return PromptTemplate(
input_variables=["job_description", "resume", "company_name", "job_position_title", "location"],
template=template
)
def _extract_json(self, text: str) -> Dict[str, Any]:
match = re.search(r'\{[\s\S]*\}', text)
if match:
try:
return json.loads(match.group(0))
except json.JSONDecodeError:
print(f"Failed to parse JSON: {match.group(0)}")
return {}
else:
print(f"No JSON found in the text: {text}")
return {}
async def analyze_job(self, job_description, resume, company_name, job_position_title, job_id, location, attempts=0):
if attempts >= 3:
print(f"Failed to analyze job after 3 attempts for {job_position_title} at {company_name}")
return None
prompt = self._get_prompt()
chain = (
{"job_description": RunnablePassthrough(), "resume": RunnablePassthrough(), "company_name": RunnablePassthrough(), "job_position_title": RunnablePassthrough(), "location": RunnablePassthrough()}
| prompt
| self.llm
| self._extract_json
)
result = await chain.ainvoke({"job_description": job_description, "resume": resume, "company_name": company_name, "job_position_title": job_position_title, "location": location})
try:
analysis_output = JobAnalysisOutput(**result)
return job_id, analysis_output
except ValueError as e:
print(f"Validation error (attempt {attempts + 1}): {e}")
print(f"Raw result: {result}")
return await self.analyze_job(job_description, resume, company_name, job_position_title, job_id, attempts + 1)
async def process_jobs(self) -> Tuple[pd.DataFrame, pd.DataFrame]:
if self.df is None or self.resume_text is None:
raise ValueError("DataFrame and resume text must be provided.")
tasks = [self.analyze_job(row['job_description'], self.resume_text, row['company_name'], row["job_position_title"], row["job_id"], row["location"])
for _, row in self.df.iterrows()]
results = []
completed_tasks = 0
total_tasks = len(tasks)
print(f"Total jobs to process: {total_tasks}")
for i in range(0, total_tasks, 5):
batch = tasks[i:i+5]
batch_results = await asyncio.gather(*batch)
results.extend(batch_results)
completed_tasks += len(batch)
print(f"Processed {completed_tasks} out of {total_tasks} jobs")
print(f"All tasks completed. Total jobs processed: {completed_tasks}")
valid_results = [result for result in results if result is not None]
if not valid_results:
print("No valid results were obtained.")
return pd.DataFrame(), pd.DataFrame()
new_columns, update_columns = zip(*[self._preprocess_job_analysis(result) for result in valid_results])
df_new = pd.DataFrame(new_columns)
df_update = pd.DataFrame(update_columns)
df_new['job_id'] = [result[0] for result in valid_results]
df_update['job_id'] = [result[0] for result in valid_results]
return df_new, df_update
@staticmethod
def _preprocess_job_analysis(result: Tuple[str, Optional[JobAnalysisOutput]]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
job_id, result = result
new_columns = {
"job_id": job_id,
"top_skills": None,
"job_category": None,
"why_this_company": None,
"why_me": None,
}
update_columns = {
"job_id": job_id,
"job_position_title": None,
"company_name": None,
"location": None
}
if result is None:
return new_columns, update_columns
try:
skills = result.skills_in_priority_order[:3]
if "Python" not in skills and "Python" in result.skills_in_priority_order:
skills = skills[:2] + ["Python"]
skills_str = ", ".join(skills[:-1]) + ", and " + skills[-1] if len(skills) > 1 else skills[0]
new_columns.update({
"top_skills": skills_str,
"job_category": result.job_category.value,
"why_this_company": result.why_this_company,
"why_me": result.why_me,
})
update_columns.update({
"job_position_title": result.job_position_title,
"company_name": result.company_name,
"location": result.location
})
except AttributeError as e:
print(f"AttributeError in preprocess_job_analysis: {e}")
return new_columns, update_columns
if __name__ == "__main__":
pass
==================================================
File: src/utilities/__init__.py
==================================================
from .utilities import *
from .proxies import ProxyRotator
==================================================
File: src/utilities/proxies.py
==================================================
import requests
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
import random
class ProxyRotator:
def __init__(self):
self.proxies = None
self.current_proxy = None
def get_proxy(self):
if self.proxies:
self.current_proxy = random.choice(self.proxies)
return {'all': self.current_proxy, 'https': self.current_proxy, 'http': self.current_proxy}
else:
self.proxies = self.get_working_proxies()
self.current_proxy = random.choice(self.proxies)
return {'all': self.current_proxy, 'https': self.current_proxy}
def remove_current_proxy(self):
if self.current_proxy in self.proxies:
self.proxies.remove(self.current_proxy)
@staticmethod
def get_proxies():
url = 'https://free-proxy-list.net/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
proxies = []
table = soup.find('table', class_='table table-striped table-bordered')
if table:
tbody = table.find('tbody')
if tbody:
rows = tbody.find_all('tr')
for row in rows:
tds = row.find_all('td')
ip = tds[0].text.strip()
port = tds[1].text.strip()
proxies.append(f'http://{ip}:{port}')
else:
print("No table body found")
else:
print("No table found")
return proxies
@staticmethod
def check_proxy(proxy):
try:
response = requests.get('https://httpbin.org/ip', proxies={'http': proxy, 'https': proxy}, timeout=5)
if response.status_code == 200:
return proxy
except:
pass
return None
def get_working_proxies(self):
proxies = self.get_proxies()
working_proxies = []
with ThreadPoolExecutor(max_workers=20) as executor:
future_to_proxy = {executor.submit(self.check_proxy, proxy): proxy for proxy in proxies}
for future in as_completed(future_to_proxy):
result = future.result()
if result:
working_proxies.append(result)
print(f"proxy count: {len(working_proxies)}")
return working_proxies
def refresh_proxies(self):
self.proxies = self.get_working_proxies()
# if __name__ == "__main__":
# proxy_rotator = ProxyRotator()
# print("Initial working proxies:")
# for proxy in proxy_rotator.proxies:
# print(proxy)
# print("\nGetting a proxy:")
# proxy = proxy_rotator.get_proxy()
# print(proxy)
# print("\nRemoving current proxy:")
# proxy_rotator.remove_current_proxy()
# print(f"Proxies left: {len(proxy_rotator.proxies)}")
# print("\nRefreshing proxies:")
# proxy_rotator.refresh_proxies()
# print(f"New proxy count: {len(proxy_rotator.proxies)}")
==================================================
File: src/utilities/utilities.py
==================================================
import re
from datetime import datetime, timedelta
from urllib.parse import urlencode, quote_plus
import pytz
from src.config import (
DEFAULT_SORT_BY, DEFAULT_EXPERIENCE_LEVEL, DEFAULT_DISTANCE,
DEFAULT_TIME_FILTER, DEFAULT_GEO_ID, DEFAULT_JOB_FUNCTION, DEFAULT_INDUSTRY
)
def calculate_posted_time(time_ago_string):
"""Calculate the posted time based on a 'time ago' string."""
try:
current_time = datetime.now()
match = re.match(r'(\d+)\s+(\w+)\s+ago', time_ago_string)
if not match:
raise ValueError("Invalid input format")
number, unit = int(match.group(1)), match.group(2).lower().rstrip('s')
units = {
'second': timedelta(seconds=1),
'minute': timedelta(minutes=1),
'hour': timedelta(hours=1),
'day': timedelta(days=1),
'week': timedelta(weeks=1),
'month': timedelta(days=30), # Approximation
'year': timedelta(days=365) # Approximation
}
if unit not in units:
raise ValueError("Invalid time unit")
return current_time - (units[unit] * number)
except Exception as e:
print(f"An error occurred in calculate_posted_time: {str(e)}")
return datetime.now()
def convert_to_iso_time(date_string, local_timezone='America/New_York'):
"""Convert a local datetime string to ISO 8601 format in UTC."""
local_time = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S.%f")
local_tz = pytz.timezone(local_timezone)
local_time_with_tz = local_tz.localize(local_time)
utc_time = local_time_with_tz.astimezone(pytz.UTC)
return utc_time.isoformat()
def duration_to_seconds(duration_string):
"""Convert a duration string to seconds."""
time_units = {
'second': 1,
'minute': 60,
'hour': 3600,
'day': 86400,
'week': 604800
}
default_seconds = 86400 # 1 day in seconds
total_seconds = 0
parts = re.findall(r'(\d+)\s*(\w+)', duration_string)
for number, unit in parts:
number = int(number)
unit = unit.lower().rstrip('s')
if unit in time_units:
total_seconds += number * time_units[unit]
if total_seconds == 0:
total_seconds = default_seconds
return f"r{str(total_seconds)}"
def generate_linkedin_job_search_url(
keyword,
sort_by=DEFAULT_SORT_BY,
time_filter=DEFAULT_TIME_FILTER,
experience_level=DEFAULT_EXPERIENCE_LEVEL,
distance=DEFAULT_DISTANCE,
industry=DEFAULT_INDUSTRY,
geo_id=DEFAULT_GEO_ID,
job_function=DEFAULT_JOB_FUNCTION
):
"""Generate a LinkedIn job search URL with the given parameters."""
time_filter = duration_to_seconds(time_filter)
params = {
"keywords": keyword,
"sortBy": sort_by,
"f_TPR": time_filter,
"f_E": experience_level,
"distance": distance,
"geoId": geo_id,
"origin": "JOB_SEARCH_PAGE_JOB_FILTER",
"refresh": "false",
"spellCorrectionEnabled": "true"
}
if industry:
params["f_I"] = industry
# Remove any None values from the params
params = {k: v for k, v in params.items() if v is not None}
base_url = "https://www.linkedin.com/jobs/search/?"
encoded_params = urlencode(params, quote_via=quote_plus)
# Add the job_function parameter separately without encoding
if job_function:
encoded_params += f"&f_F={job_function}"
if industry:
encoded_params += f"&f_I={industry}"
return base_url + encoded_params
==================================================
File: src/notion_integration/notion_manager.py
==================================================
import os
from typing import Dict, Any, List
from notion_client import Client
import pandas as pd
from dotenv import load_dotenv
from src.config import NOTION_API_KEY, NOTION_SCHEMA, NOTION_DATABASE_ID
class NotionManager:
def __init__(self, df, database_id: str = NOTION_DATABASE_ID):
self.notion = self._initialize_notion_client()
self.df = df
self.database_id = database_id
self.sync_to_notion(self.df)
@staticmethod
def _initialize_notion_client() -> Client:
load_dotenv()
api_key = os.getenv("NOTION_API_KEY", NOTION_API_KEY)
if not api_key:
raise ValueError("Notion API key not found in environment variables or config")
return Client(auth=api_key)
def create_property(self, property_name: str, property_type: str) -> None:
try:
self.notion.databases.update(
database_id=self.database_id,
properties={
property_name: {
"type": property_type,
property_type: {}
}
}
)
print(f"Property '{property_name}' of type '{property_type}' created successfully.")
except Exception as e:
print(f"Error creating property: {e}")
def sync_to_notion(self, df: pd.DataFrame) -> None:
for _, row in df.iterrows():
properties = self._prepare_properties(row)
try:
page = self.notion.pages.create(
parent={"database_id": self.database_id},
properties=properties,
icon={"type": "external", "external": {"url": row['company_logo']}}
)
self.add_detailed_content(page["id"], row)
print(f"Row added successfully: {row['job_id']}")
except Exception as e:
print(f"Error adding row: {row['job_id']}. Error: {e}")
def _prepare_properties(self, row: pd.Series) -> Dict[str, Any]:
properties = {}
for col, prop_data in NOTION_SCHEMA.items():
notion_prop_name = prop_data["notion_prop_name"]