-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2044 lines (1841 loc) · 75.9 KB
/
Copy pathserver.py
File metadata and controls
2044 lines (1841 loc) · 75.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
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
"""Job Apply Assistant - a local, privacy-first job search web app.
Run it:
python server.py
Then open http://127.0.0.1:8000 in your browser.
The app uses the standard library plus optional pypdf resume text extraction.
What it does
------------
* Search real jobs via JSearch with exact country and student-focused filters.
Free no-key sources are used as a fallback.
* Store your resume + basic profile locally under ./data (never uploaded anywhere
except when *you* open an employer's application page yourself).
* Track which jobs you've applied to.
Honest note about "auto apply to everything"
--------------------------------------------
Final submission happens on each employer's own site/ATS. "Prepare & Open"
queues jobs and opens their real application pages for review. Browsers do not
allow a local web app to set a file-upload control, so resume upload and final
submission remain deliberate user actions.
"""
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from contextlib import contextmanager
from datetime import datetime, timezone
import base64
import csv
import ctypes
from ctypes import wintypes
import hashlib
import io
import json
import os
import re
import sqlite3
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import zipfile
from xml.etree import ElementTree
HOST = "127.0.0.1"
PORT = 8000
HERE = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(HERE, "static")
DATA_DIR = os.path.join(HERE, "data")
RESUME_DIR = os.path.join(DATA_DIR, "resume")
APPLICATIONS_FILE = os.path.join(DATA_DIR, "applications.json")
PROFILE_FILE = os.path.join(DATA_DIR, "profile.json")
CONFIG_FILE = os.path.join(DATA_DIR, "config.json")
DATABASE_FILE = os.path.join(DATA_DIR, "job_assistant.db")
RESUME_TEXT_FILE = os.path.join(DATA_DIR, "resume_text.txt")
ANSWERS_FILE = os.path.join(DATA_DIR, "answers.json")
REMOTIVE_JOBS = "https://remotive.com/api/remote-jobs"
REMOTIVE_CATEGORIES = "https://remotive.com/api/remote-jobs/categories"
JSEARCH_URL = "https://jsearch.p.rapidapi.com/search-v2"
JSEARCH_HOST = "jsearch.p.rapidapi.com"
HTTP_TIMEOUT = 20
USER_AGENT = "JobApplyAssistant/1.0 (personal use)"
MAX_UPLOAD = 8 * 1024 * 1024 # 8 MB resume cap
DISPLAY_LIMIT = 200 # max jobs sent to the browser per search
PREVIEW_LIMIT = 60 # jobs fetched just to suggest company names
JSEARCH_PAGES = 3 # pages returned by one JSearch HTTP call
JSEARCH_SG_PAGES = 1 # extra Singapore-targeted page, merged on top
JOBS_CACHE_TTL = 6 * 3600 # reuse identical searches for 6h = 0 API requests
HOME_COUNTRY = "singapore" # jobs here are sorted to the top
JOBICY_URL = "https://jobicy.com/api/v2/remote-jobs"
ARBEITNOW_URL = "https://www.arbeitnow.com/api/job-board-api"
# Singapore's official government job portal: no key, no quota, ~0.2s responses.
MCF_SEARCH_URL = "https://api.mycareersfuture.gov.sg/v2/search"
MCF_PAGE_SIZE = 100 # results per MyCareersFuture request
MCF_PAGES = 3 # up to 300 Singapore jobs per search
MCF_PREVIEW_SIZE = 40 # smaller page for company-name suggestions
CACHE_VERSION = "2026-08-04-v3"
MAX_DESCRIPTION = 6000
MAX_QUESTION_LEN = 400
MAX_ANSWER_LEN = 4000
MAX_ANSWERS = 500
ANSWER_MATCH_THRESHOLD = 0.6 # token overlap needed to reuse a saved answer
# Posting-quality heuristics. These raise flags for review - never a verdict.
AGENCY_NAME_HINTS = (
"recruit", "hr advisory", "manpower", "staffing", "employment agency",
"search & selection", "hr solutions", "personnel", "outsourcing",
"hr consult", "talent acquisition", "headhunt",
)
BATCH_CODE_RE = re.compile(r"^\s*\d{3,6}\s*[-\u2013\u2014:]\s*")
SALARY_NOTE_RE = re.compile(r"\s*[\(\[][^)\]]*(?:up to|from|\$|salary)[^)\]]*[\)\]]", re.I)
AGENCY_FLOOD_THRESHOLD = 4 # postings from one employer within a single result set
MIN_PLAUSIBLE_MONTHLY_SGD = 900
WIDE_SALARY_RATIO = 3.0
REPOST_MIN_TIMES = 3
REPOST_MIN_DAYS = 21
APPLICATION_STATUSES = {
"saved", "queued", "opened", "submitted", "interview", "offer", "rejected"
}
COUNTRY_CODES = {
"singapore": "sg", "sg": "sg",
"malaysia": "my", "my": "my",
"indonesia": "id", "id": "id",
"philippines": "ph", "ph": "ph",
"thailand": "th", "th": "th",
"vietnam": "vn", "vn": "vn",
"brunei": "bn", "bn": "bn",
"cambodia": "kh", "kh": "kh",
"india": "in", "in": "in",
"china": "cn", "cn": "cn",
"hong kong": "hk", "hk": "hk",
"taiwan": "tw", "tw": "tw",
"japan": "jp", "jp": "jp",
"south korea": "kr", "korea": "kr", "kr": "kr",
"australia": "au", "au": "au",
"new zealand": "nz", "nz": "nz",
"united kingdom": "gb", "uk": "gb", "gb": "gb",
"united states": "us", "usa": "us", "us": "us",
"canada": "ca", "ca": "ca",
"germany": "de", "de": "de",
"france": "fr", "fr": "fr",
"netherlands": "nl", "nl": "nl",
"switzerland": "ch", "ch": "ch",
"sweden": "se", "se": "se",
"norway": "no", "no": "no",
"denmark": "dk", "dk": "dk",
"finland": "fi", "fi": "fi",
"ireland": "ie", "ie": "ie",
"united arab emirates": "ae", "uae": "ae", "ae": "ae",
"saudi arabia": "sa", "sa": "sa",
}
RELATED_ROLE_FAMILIES = {
"mechatronics": [
"Mechatronics Engineer", "Robotics Engineer", "Automation Engineer",
"Controls Engineer", "PLC Engineer", "Embedded Systems Engineer",
"Mechanical Design Engineer", "Test Validation Engineer",
"Manufacturing Engineer", "Field Service Engineer",
],
"robotics": [
"Robotics Engineer", "Mechatronics Engineer", "Automation Engineer",
"Controls Engineer", "ROS Engineer", "Embedded Systems Engineer",
],
"automation": [
"Automation Engineer", "Controls Engineer", "PLC Engineer",
"Mechatronics Engineer", "Manufacturing Engineer", "Process Engineer",
],
"data scientist": [
"Data Scientist", "Data Analyst", "Machine Learning Engineer",
"AI Engineer", "Business Intelligence Analyst",
],
}
SKILL_ALIASES = {
"PLC": ["plc", "programmable logic controller"],
"MATLAB": ["matlab"],
"Simulink": ["simulink"],
"SolidWorks": ["solidworks"],
"AutoCAD": ["autocad"],
"Python": ["python"],
"C++": ["c++", "cpp"],
"C": [" c ", "c programming", "c/c++", "c and c++"],
"C#": ["c#", "c sharp"],
"ROS": ["robot operating system", " ros "],
"Arduino": ["arduino"],
"Raspberry Pi": ["raspberry pi"],
"Embedded Systems": ["embedded system", "embedded software"],
"Control Systems": ["control system", "controls engineering"],
"Robotics": ["robotics", "robotic"],
"Automation": ["automation", "automated systems"],
"CAD": [" cad ", "computer-aided design", "computer aided design"],
"CAM": [" cam ", "computer-aided manufacturing"],
"LabVIEW": ["labview"],
"Altium": ["altium"],
"PCB Design": ["pcb", "printed circuit board"],
"IoT": ["iot", "internet of things"],
"Git": [" git ", "github", "gitlab"],
"SQL": ["sql"],
"TensorFlow": ["tensorflow"],
"PyTorch": ["pytorch"],
}
CONTENT_TYPES = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
".ico": "image/x-icon",
".png": "image/png",
}
# Used only if the live job API can't be reached, so the app still demos.
SAMPLE_JOBS = [
{"id": "s1", "title": "Frontend Engineer", "company": "Acme Corp",
"category": "Software Development", "location": "Worldwide",
"job_type": "full_time", "salary": "$90k - $120k",
"url": "https://example.com/jobs/frontend-engineer", "date": "2026-07-01",
"logo": ""},
{"id": "s2", "title": "Data Analyst", "company": "Globex",
"category": "Data Analysis", "location": "Europe",
"job_type": "full_time", "salary": "",
"url": "https://example.com/jobs/data-analyst", "date": "2026-06-28",
"logo": ""},
{"id": "s3", "title": "Product Marketing Manager", "company": "Initech",
"category": "Marketing", "location": "USA / Canada",
"job_type": "full_time", "salary": "$110k - $140k",
"url": "https://example.com/jobs/pmm", "date": "2026-06-30",
"logo": ""},
{"id": "s4", "title": "Customer Support Specialist", "company": "Umbrella",
"category": "Customer Service", "location": "Anywhere",
"job_type": "part_time", "salary": "",
"url": "https://example.com/jobs/support", "date": "2026-06-25",
"logo": ""},
{"id": "s5", "title": "DevOps Engineer", "company": "Hooli",
"category": "DevOps / Sysadmin", "location": "Asia",
"job_type": "contract", "salary": "$80k - $110k",
"url": "https://example.com/jobs/devops", "date": "2026-07-02",
"logo": ""},
{"id": "s6", "title": "Mechatronics Engineer", "company": "RoboWorks",
"category": "Engineering", "location": "Singapore",
"job_type": "full_time", "salary": "",
"url": "https://example.com/jobs/mechatronics-engineer", "date": "2026-07-03",
"logo": ""},
{"id": "s7", "title": "Robotics / Automation Engineer", "company": "AutoMate",
"category": "Engineering", "location": "Germany",
"job_type": "full_time", "salary": "",
"url": "https://example.com/jobs/robotics-engineer", "date": "2026-07-04",
"logo": ""},
]
# ---------------------------------------------------------------------------
# Storage helpers
# ---------------------------------------------------------------------------
def ensure_dirs():
os.makedirs(RESUME_DIR, exist_ok=True)
init_database()
def load_json(path, default):
try:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return default
def save_json(path, obj):
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=2)
os.replace(tmp, path)
_DB_LOCK = threading.Lock()
def _db():
conn = sqlite3.connect(DATABASE_FILE, timeout=15)
conn.row_factory = sqlite3.Row
return conn
@contextmanager
def db_session():
"""Serialize writes and always close SQLite handles (important on Windows)."""
with _DB_LOCK:
conn = _db()
try:
with conn:
yield conn
finally:
conn.close()
def init_database():
os.makedirs(DATA_DIR, exist_ok=True)
with db_session() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS job_cache (
cache_key TEXT PRIMARY KEY,
created_at REAL NOT NULL,
result_json TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS api_usage (
id INTEGER PRIMARY KEY AUTOINCREMENT,
called_at REAL NOT NULL,
endpoint TEXT NOT NULL,
status INTEGER,
remaining INTEGER,
limit_count INTEGER,
reset_value TEXT
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS api_usage_called_at ON api_usage(called_at)")
conn.execute("""
CREATE TABLE IF NOT EXISTS posting_history (
fingerprint TEXT PRIMARY KEY,
first_seen REAL NOT NULL,
last_seen REAL NOT NULL,
times INTEGER NOT NULL DEFAULT 1,
last_post_id TEXT
)
""")
def _cache_key(payload):
raw = CACHE_VERSION + "|" + json.dumps(payload, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def cache_get(key):
now = time.time()
with db_session() as conn:
row = conn.execute(
"SELECT created_at, result_json FROM job_cache WHERE cache_key = ?", (key,)
).fetchone()
if not row:
return None
age = now - row["created_at"]
if age >= JOBS_CACHE_TTL:
conn.execute("DELETE FROM job_cache WHERE cache_key = ?", (key,))
return None
try:
result = json.loads(row["result_json"])
except json.JSONDecodeError:
conn.execute("DELETE FROM job_cache WHERE cache_key = ?", (key,))
return None
result["cached"] = True
result["cache_age_seconds"] = int(age)
return result
def cache_set(key, result):
stored = dict(result)
stored.pop("cached", None)
stored.pop("cache_age_seconds", None)
with db_session() as conn:
conn.execute(
"""INSERT INTO job_cache(cache_key, created_at, result_json)
VALUES (?, ?, ?)
ON CONFLICT(cache_key) DO UPDATE SET
created_at = excluded.created_at,
result_json = excluded.result_json""",
(key, time.time(), json.dumps(stored, separators=(",", ":"))),
)
def cache_clear():
with db_session() as conn:
count = conn.execute("SELECT COUNT(*) FROM job_cache").fetchone()[0]
conn.execute("DELETE FROM job_cache")
return count
def _header_int(headers, *names):
for name in names:
value = headers.get(name) if headers else None
if value is not None:
try:
return int(value)
except (TypeError, ValueError):
pass
return None
def record_api_usage(headers, status, endpoint="jsearch/search-v2"):
remaining = _header_int(
headers, "x-ratelimit-requests-remaining", "X-RateLimit-Requests-Remaining"
)
limit_count = _header_int(
headers, "x-ratelimit-requests-limit", "X-RateLimit-Requests-Limit"
)
reset_value = ""
if headers:
reset_value = headers.get("x-ratelimit-requests-reset", "")
with db_session() as conn:
conn.execute(
"""INSERT INTO api_usage
(called_at, endpoint, status, remaining, limit_count, reset_value)
VALUES (?, ?, ?, ?, ?, ?)""",
(time.time(), endpoint, status, remaining, limit_count, str(reset_value)),
)
conn.execute("DELETE FROM api_usage WHERE called_at < ?", (time.time() - 90 * 86400,))
def usage_summary():
now = datetime.now(timezone.utc)
month_start = datetime(now.year, now.month, 1, tzinfo=timezone.utc).timestamp()
with db_session() as conn:
latest = conn.execute(
"""SELECT remaining, limit_count, reset_value, called_at
FROM api_usage ORDER BY id DESC LIMIT 1"""
).fetchone()
calls = conn.execute(
"SELECT COUNT(*) FROM api_usage WHERE called_at >= ?", (month_start,)
).fetchone()[0]
cache_entries = conn.execute(
"SELECT COUNT(*) FROM job_cache WHERE created_at >= ?",
(time.time() - JOBS_CACHE_TTL,),
).fetchone()[0]
return {
"observed_calls_this_month": calls,
"remaining": latest["remaining"] if latest else None,
"limit": latest["limit_count"] if latest else None,
"reset": latest["reset_value"] if latest else "",
"last_call_at": (
datetime.fromtimestamp(latest["called_at"], timezone.utc).isoformat()
if latest else None
),
"cache_entries": cache_entries,
"cache_ttl_hours": JOBS_CACHE_TTL // 3600,
}
class _DataBlob(ctypes.Structure):
_fields_ = [("cbData", wintypes.DWORD),
("pbData", ctypes.POINTER(ctypes.c_byte))]
def _protect_secret(value):
"""Encrypt a secret for the current Windows user via DPAPI."""
if os.name != "nt" or not value:
return None
raw = value.encode("utf-8")
buffer = (ctypes.c_byte * len(raw)).from_buffer_copy(raw)
source = _DataBlob(len(raw), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte)))
target = _DataBlob()
ok = ctypes.windll.crypt32.CryptProtectData(
ctypes.byref(source), "Job Apply Assistant", None, None, None, 0,
ctypes.byref(target),
)
if not ok:
raise ctypes.WinError()
try:
encrypted = ctypes.string_at(target.pbData, target.cbData)
return base64.b64encode(encrypted).decode("ascii")
finally:
ctypes.windll.kernel32.LocalFree(target.pbData)
def _unprotect_secret(value):
if os.name != "nt" or not value:
return None
encrypted = base64.b64decode(value)
buffer = (ctypes.c_byte * len(encrypted)).from_buffer_copy(encrypted)
source = _DataBlob(
len(encrypted), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_byte))
)
target = _DataBlob()
ok = ctypes.windll.crypt32.CryptUnprotectData(
ctypes.byref(source), None, None, None, None, 0, ctypes.byref(target)
)
if not ok:
raise ctypes.WinError()
try:
return ctypes.string_at(target.pbData, target.cbData).decode("utf-8")
finally:
ctypes.windll.kernel32.LocalFree(target.pbData)
def save_rapidapi_key(key):
cfg = load_json(CONFIG_FILE, {})
key = (key or "").strip()
cfg.pop("rapidapi_key", None)
cfg.pop("rapidapi_key_protected", None)
if key:
protected = _protect_secret(key)
if protected:
cfg["rapidapi_key_protected"] = protected
else:
# Non-Windows fallback; prefer RAPIDAPI_KEY environment variable there.
cfg["rapidapi_key"] = key
save_json(CONFIG_FILE, cfg)
cache_clear()
# ---------------------------------------------------------------------------
# Job source (Remotive)
# ---------------------------------------------------------------------------
def fetch_url(url, timeout=HTTP_TIMEOUT):
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
def normalize_job(j):
return {
"id": j.get("id"),
"title": j.get("title", ""),
"company": j.get("company_name", ""),
"category": j.get("category", ""),
"location": j.get("candidate_required_location", "") or "Anywhere",
"job_type": j.get("job_type", ""),
"salary": j.get("salary", ""),
"url": j.get("url", ""),
"date": (j.get("publication_date", "") or "")[:10],
"logo": j.get("company_logo", ""),
}
def get_categories():
try:
data = fetch_url(REMOTIVE_CATEGORIES)
cats = [
{"name": c.get("name", ""), "slug": c.get("slug", "")}
for c in data.get("jobs-categories", [])
if c.get("slug")
]
if cats:
return cats
except (urllib.error.URLError, json.JSONDecodeError, TimeoutError, OSError):
pass
# Fallback list of Remotive categories.
return [
{"name": "Software Development", "slug": "software-dev"},
{"name": "Customer Service", "slug": "customer-support"},
{"name": "Design", "slug": "design"},
{"name": "Marketing", "slug": "marketing"},
{"name": "Sales / Business", "slug": "sales"},
{"name": "Product", "slug": "product"},
{"name": "Business", "slug": "business"},
{"name": "Data Analysis", "slug": "data"},
{"name": "DevOps / Sysadmin", "slug": "devops"},
{"name": "Finance / Legal", "slug": "finance-legal"},
{"name": "Human Resources", "slug": "hr"},
{"name": "Quality Assurance", "slug": "qa"},
{"name": "Writing", "slug": "writing"},
{"name": "Project Management", "slug": "project-management"},
{"name": "All others", "slug": "all-others"},
]
# Map our industry dropdown values to search keywords for JSearch.
INDUSTRY_KEYWORDS = {
"engineering": "engineer",
"software-dev": "software developer",
"data": "data analyst",
"design": "designer",
"marketing": "marketing",
"sales": "sales",
"product": "product manager",
"devops": "devops engineer",
"finance-legal": "finance",
"hr": "human resources",
"qa": "qa engineer",
"customer-support": "customer support",
"writing": "writer",
"project-management": "project manager",
"business": "business",
"all-others": "",
}
def industry_keyword(industry):
if not industry:
return ""
if industry in INDUSTRY_KEYWORDS:
return INDUSTRY_KEYWORDS[industry]
return industry.replace("-", " ")
def get_rapidapi_key():
env = os.environ.get("RAPIDAPI_KEY", "").strip()
if env:
return env
cfg = load_json(CONFIG_FILE, {})
protected = str(cfg.get("rapidapi_key_protected", "")).strip()
if protected:
try:
return (_unprotect_secret(protected) or "").strip()
except (ValueError, OSError):
return ""
plain = str(cfg.get("rapidapi_key", "")).strip()
if plain and os.name == "nt":
# One-time migration from the old plaintext config format.
try:
save_rapidapi_key(plain)
except OSError:
pass
return plain
def normalize_jsearch(j):
city = j.get("job_city") or ""
country = j.get("job_country") or ""
loc = j.get("job_location") or ", ".join(p for p in (city, country) if p)
if not loc:
loc = "Remote" if j.get("job_is_remote") else "N/A"
lo, hi = j.get("job_min_salary"), j.get("job_max_salary")
if lo and hi:
salary = f"${int(lo):,} - ${int(hi):,}"
elif lo or hi:
salary = f"${int(lo or hi):,}"
else:
salary = ""
etype = (j.get("job_employment_type") or "").replace("_", " ").title()
# Prefer the LinkedIn apply link when JSearch lists one for this job.
url = j.get("job_apply_link", "") or ""
publisher = j.get("job_publisher", "") or ""
for opt in (j.get("apply_options") or []):
if "linkedin" in (opt.get("publisher", "") or "").lower():
url = opt.get("apply_link") or url
publisher = opt.get("publisher") or publisher
break
return {
"id": j.get("job_id"),
"title": j.get("job_title", "") or "",
"company": j.get("employer_name", "") or "",
"category": etype,
"location": loc,
"job_type": etype,
"salary": salary,
"url": url,
"publisher": publisher,
"date": (j.get("job_posted_at_datetime_utc", "") or "")[:10],
"logo": j.get("employer_logo", "") or "",
"country_code": country.upper(),
"city": city,
"seniority": j.get("seniority_level") or "",
"experience_years": j.get("required_experience_years"),
"work_arrangement": (
j.get("work_arrangement")
or ("remote" if j.get("job_is_remote") else "")
),
"visa_sponsorship": j.get("visa_sponsorship"),
"education": j.get("education_required") or {},
"required_skills": j.get("required_technologies") or [],
"preferred_skills": j.get("preferred_technologies") or [],
"description": (j.get("job_description") or "")[:MAX_DESCRIPTION],
}
def country_code_for(location):
value = (location or "").strip().lower()
return COUNTRY_CODES.get(value, "")
def expanded_role_query(role, industry, include_related):
base = role.strip() if role else industry_keyword(industry)
if not include_related:
return base
lowered = base.lower()
family = None
for trigger, roles in RELATED_ROLE_FAMILIES.items():
if trigger in lowered:
family = roles
break
if family is None and industry == "engineering" and lowered in {"", "engineer"}:
family = RELATED_ROLE_FAMILIES["mechatronics"]
if not family:
return base
return "(" + " OR ".join(f'\"{item}\"' for item in family) + ")"
def fetch_jsearch(role, industry, company, location, key, pages=1, options=None):
options = options or {}
base = expanded_role_query(role, industry, options.get("related_roles", False))
terms = [t for t in (base, company.strip() if company else "") if t]
query = " ".join(terms).strip() or "jobs"
if location:
query = f"{query} in {location.strip()}"
params = {
"query": query,
"num_pages": str(pages),
"language": "en",
}
country_code = country_code_for(location)
if country_code:
params["country"] = country_code
date_posted = options.get("date_posted", "all")
if date_posted in {"today", "3days", "week", "month"}:
params["date_posted"] = date_posted
url = JSEARCH_URL + "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, headers={
"X-RapidAPI-Key": key,
"X-RapidAPI-Host": JSEARCH_HOST,
"User-Agent": USER_AGENT,
})
try:
with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
raw = resp.read()
record_api_usage(resp.headers, resp.status)
except urllib.error.HTTPError as exc:
record_api_usage(exc.headers, exc.code)
raise
data = json.loads(raw.decode("utf-8"))
# /search-v2 nests jobs under data.jobs; guard for the older list shape too.
payload = data.get("data", {})
items = payload.get("jobs", []) if isinstance(payload, dict) else payload
return [normalize_jsearch(j) for j in items if isinstance(j, dict)]
def _dedupe(jobs):
seen, out = set(), []
for j in jobs:
key = (j.get("url") or "").strip().lower()
if not key:
key = (j.get("title", "") + "|" + j.get("company", "")).lower()
if key in seen:
continue
seen.add(key)
out.append(j)
return out
def _sg_first(jobs):
# Stable sort: Singapore-located jobs first, everything else after.
return sorted(
jobs,
key=lambda j: 0 if HOME_COUNTRY in (j.get("location", "") or "").lower() else 1,
)
def _strip_html(text):
return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", text or "")).strip()
# MyCareersFuture position levels that rule a job out for a student/new grad.
_MCF_SENIOR_LEVELS = ("senior", "management", "manager", "director", "head")
def normalize_mcf(j):
meta = j.get("metadata") or {}
company = j.get("postedCompany") or {}
salary = j.get("salary") or {}
low, high = salary.get("minimum"), salary.get("maximum")
period = ((salary.get("type") or {}).get("salaryType") or "").lower()
suffix = ""
for prefix, unit in (("month", "/mo"), ("ann", "/yr"), ("year", "/yr"),
("hour", "/hr"), ("week", "/wk"), ("dai", "/day"),
("day", "/day")):
if period.startswith(prefix):
suffix = unit
break
if low and high:
pay = f"S${int(low):,} - S${int(high):,}{suffix}"
elif low or high:
pay = f"S${int(low or high):,}{suffix}"
else:
pay = ""
levels = ", ".join(
lvl.get("position") or "" for lvl in (j.get("positionLevels") or [])
).strip(", ")
seniority = "senior" if any(k in levels.lower() for k in _MCF_SENIOR_LEVELS) else "entry"
districts = [
d.get("region") or d.get("location") or ""
for d in ((j.get("address") or {}).get("districts") or [])
]
area = ", ".join(dict.fromkeys(p for p in districts if p)) or "Singapore"
location = area if "singapore" in area.lower() else f"{area}, Singapore"
etype = ", ".join(
t.get("employmentType") or "" for t in (j.get("employmentTypes") or [])
).strip(", ")
arrangement = ", ".join(
w.get("flexibleWorkArrangement") or ""
for w in (j.get("flexibleWorkArrangements") or [])
).strip(", ").lower()
return {
"id": meta.get("jobPostId") or "",
"title": j.get("title", "") or "",
"company": company.get("name", "") or "",
"category": etype,
"location": location,
"job_type": etype,
"salary": pay,
"salary_min": low or None,
"salary_max": high or None,
"salary_period": period,
"url": meta.get("jobDetailsUrl", "") or "",
"publisher": "MyCareersFuture",
"date": (meta.get("newPostingDate") or meta.get("updatedAt") or "")[:10],
"logo": company.get("logoUploadPath", "") or "",
"country_code": "SG",
"city": area,
# MCF states outright when an agency posts for an undisclosed employer.
"posted_on_behalf": bool(meta.get("isPostedOnBehalf")),
"employer_hidden": bool(meta.get("isHideHiringEmployerName")),
"seniority": seniority,
"experience_years": j.get("minimumYearsExperience"),
"work_arrangement": arrangement,
"visa_sponsorship": None,
"education": {},
# MCF tags every posting with structured skills - feeds resume matching.
"required_skills": [
s.get("skill") for s in (j.get("skills") or []) if s.get("skill")
],
"preferred_skills": [],
"description": _strip_html(j.get("description", ""))[:MAX_DESCRIPTION],
}
def targets_singapore(location):
value = (location or "").strip().lower()
return not value or HOME_COUNTRY in value
def fetch_mycareersfuture(role, industry, company, options=None, pages=1,
page_size=MCF_PAGE_SIZE):
options = options or {}
terms = [role.strip() if role else industry_keyword(industry)]
if company:
terms.append(company.strip())
search = " ".join(t for t in terms if t).strip() or "engineer"
jobs = []
for page in range(max(1, pages)):
url = f"{MCF_SEARCH_URL}?limit={page_size}&page={page}"
body = json.dumps({
"search": search,
"sessionId": "",
"sortBy": ["new_posting_date"],
}).encode("utf-8")
req = urllib.request.Request(url, data=body, method="POST", headers={
"Content-Type": "application/json",
"Accept": "application/json",
"User-Agent": USER_AGENT,
})
with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
data = json.loads(resp.read().decode("utf-8", "replace"))
results = [r for r in (data.get("results") or []) if isinstance(r, dict)]
jobs.extend(normalize_mcf(r) for r in results)
if len(results) < page_size:
break
return jobs
def fetch_remotive(industry, role):
params = {"limit": 200}
if industry and industry != "engineering":
params["category"] = industry
search = role or ("engineer" if industry == "engineering" else "")
if search:
params["search"] = search
url = REMOTIVE_JOBS + "?" + urllib.parse.urlencode(params)
data = fetch_url(url)
return [normalize_job(j) for j in data.get("jobs", [])]
def fetch_jobicy(role):
params = {"count": 50}
if role:
params["tag"] = role
url = JOBICY_URL + "?" + urllib.parse.urlencode(params)
data = fetch_url(url, timeout=12)
out = []
for j in data.get("jobs", []):
types = j.get("jobType") or []
industries = j.get("jobIndustry") or []
out.append({
"id": j.get("id"),
"title": j.get("jobTitle", "") or "",
"company": j.get("companyName", "") or "",
"category": industries[0] if industries else "",
"location": j.get("jobGeo", "") or "Remote",
"job_type": types[0] if types else "",
"salary": "",
"url": j.get("url", "") or "",
"date": (j.get("pubDate", "") or "")[:10],
"logo": j.get("companyLogo", "") or "",
})
return out
def fetch_arbeitnow(role):
data = fetch_url(ARBEITNOW_URL, timeout=12)
out = []
for j in data.get("data", []):
types = j.get("job_types") or []
tags = j.get("tags") or []
date = ""
ts = j.get("created_at")
if ts:
try:
date = datetime.fromtimestamp(int(ts), tz=timezone.utc).date().isoformat()
except (ValueError, OSError, OverflowError):
date = ""
out.append({
"id": j.get("slug"),
"title": j.get("title", "") or "",
"company": j.get("company_name", "") or "",
"category": tags[0] if tags else "",
"location": j.get("location", "") or ("Remote" if j.get("remote") else ""),
"job_type": types[0] if types else "",
"salary": "",
"url": j.get("url", "") or "",
"date": date,
"logo": "",
})
if role:
r = role.lower()
out = [j for j in out if r in j["title"].lower()]
return out
NET_ERRORS = (urllib.error.URLError, json.JSONDecodeError, TimeoutError, OSError)
SENIOR_TITLE_RE = re.compile(
r"\b(?:senior|sr\.?|lead|principal|staff|manager|director|head|chief|vp)\b",
re.IGNORECASE,
)
ENTRY_TITLE_RE = re.compile(
r"\b(?:intern|internship|graduate|junior|jr\.?|trainee|assistant|associate|entry)\b",
re.IGNORECASE,
)
def extract_resume_text(path):
ext = os.path.splitext(path)[1].lower()
try:
if ext == ".txt":
with open(path, "r", encoding="utf-8", errors="ignore") as f:
return f.read()
if ext == ".docx":
with zipfile.ZipFile(path) as archive:
xml = archive.read("word/document.xml")
root = ElementTree.fromstring(xml)
return " ".join(
node.text for node in root.iter()
if node.tag.endswith("}t") and node.text
)
if ext == ".pdf":
try:
from pypdf import PdfReader
except ImportError:
return ""
reader = PdfReader(path)
return "\n".join((page.extract_text() or "") for page in reader.pages)
except (OSError, ValueError, KeyError, zipfile.BadZipFile):
return ""
return ""
def candidate_text():
profile = load_json(PROFILE_FILE, {})
parts = [str(profile.get("skills", ""))]
try:
with open(RESUME_TEXT_FILE, "r", encoding="utf-8") as f:
parts.append(f.read())
except FileNotFoundError:
pass
return "\n".join(parts).strip()
def known_skills(text):
haystack = " " + re.sub(r"\s+", " ", (text or "").lower()) + " "
found = set()
for canonical, aliases in SKILL_ALIASES.items():
if any(alias.lower() in haystack for alias in aliases):
found.add(canonical)
return found
# Words that carry no meaning when telling two application questions apart.
_QUESTION_STOPWORDS = frozenset({
"a", "an", "the", "is", "are", "was", "do", "does", "did", "you", "your",
"yours", "please", "kindly", "enter", "provide", "tell", "us", "we", "i",
"my", "me", "this", "that", "it", "to", "of", "for", "in", "on", "at",
"and", "or", "if", "be", "been", "have", "has", "had", "will", "would",
"can", "could", "may", "might", "should", "what", "which", "any", "about",
})
def question_key(text):
"""Canonical form of a question, used to match a page field to a saved answer."""
lowered = (text or "").lower()
lowered = re.sub(r"\(.*?\)", " ", lowered)
lowered = re.sub(r"[^a-z0-9 ]+", " ", lowered)
tokens = [t for t in lowered.split() if t and t not in _QUESTION_STOPWORDS]
return " ".join(tokens)[:200]
def load_answers():
stored = load_json(ANSWERS_FILE, {})
answers = stored.get("answers") if isinstance(stored, dict) else None
return [a for a in (answers or []) if isinstance(a, dict) and a.get("key")]
def save_answer_records(items):
if not isinstance(items, list):
raise ValueError("answers must be a list")
answers = load_answers()
index = {a["key"]: a for a in answers}
order = [a["key"] for a in answers]
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
saved = 0
for item in items:
if not isinstance(item, dict):
continue