unitbytes 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
unitbytes/jobs.py ADDED
@@ -0,0 +1,869 @@
1
+ """Google Jobs domain namespace (`ub.jobs`) with ATS classification, JobSpy migration, atomic `0600` watchlists, and B2B hiring company aggregation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ from decimal import Decimal
7
+ import hashlib
8
+ import ipaddress
9
+ import os
10
+ import re
11
+ from typing import TYPE_CHECKING, Any, Literal, Mapping, Sequence
12
+ from urllib.parse import parse_qs, urlparse
13
+
14
+ from ._serialization import filter_unseen_by_key, require_pandas
15
+ from ._transports import unwrap_items_payload
16
+
17
+ if TYPE_CHECKING:
18
+ from .client import UnitBytes
19
+
20
+ ACTOR_GOOGLE_JOBS = "unitbytes/google-jobs-scraper"
21
+ DEFAULT_WATCHLIST_STATE_FILE = ".google_jobs_watchlist_state.json"
22
+
23
+ DatePostedOption = Literal["any", "today", "3days", "week", "month"]
24
+ EmploymentTypeOption = Literal["FULLTIME", "PARTTIME", "CONTRACTOR", "INTERN"]
25
+ AtsProvider = Literal[
26
+ "greenhouse",
27
+ "lever",
28
+ "workday",
29
+ "ashby",
30
+ "smartrecruiters",
31
+ "icims",
32
+ "bamboohr",
33
+ "workable",
34
+ "rippling",
35
+ "job_board",
36
+ "company_direct",
37
+ ]
38
+
39
+ DIRECT_ATS_PROVIDERS: frozenset[str] = frozenset(
40
+ {
41
+ "greenhouse",
42
+ "lever",
43
+ "workday",
44
+ "ashby",
45
+ "smartrecruiters",
46
+ "icims",
47
+ "bamboohr",
48
+ "workable",
49
+ "rippling",
50
+ }
51
+ )
52
+
53
+ _VALID_DATE_POSTED = {"any", "today", "3days", "week", "month"}
54
+
55
+ _EMPLOYMENT_TYPE_ALIASES: dict[str, EmploymentTypeOption] = {
56
+ "FULLTIME": "FULLTIME",
57
+ "FULL-TIME": "FULLTIME",
58
+ "FULL TIME": "FULLTIME",
59
+ "FT": "FULLTIME",
60
+ "PARTTIME": "PARTTIME",
61
+ "PART-TIME": "PARTTIME",
62
+ "PART TIME": "PARTTIME",
63
+ "PT": "PARTTIME",
64
+ "CONTRACTOR": "CONTRACTOR",
65
+ "CONTRACT": "CONTRACTOR",
66
+ "TEMPORARY": "CONTRACTOR",
67
+ "TEMP": "CONTRACTOR",
68
+ "INTERN": "INTERN",
69
+ "INTERNSHIP": "INTERN",
70
+ }
71
+
72
+ _COUNTRY_ALIASES: dict[str, str] = {
73
+ "usa": "us",
74
+ "united states": "us",
75
+ "united states of america": "us",
76
+ "uk": "gb",
77
+ "united kingdom": "gb",
78
+ "great britain": "gb",
79
+ "england": "gb",
80
+ "canada": "ca",
81
+ "germany": "de",
82
+ "deutschland": "de",
83
+ "france": "fr",
84
+ "netherlands": "nl",
85
+ "spain": "es",
86
+ "italy": "it",
87
+ "australia": "au",
88
+ "india": "in",
89
+ "singapore": "sg",
90
+ "brazil": "br",
91
+ "mexico": "mx",
92
+ "japan": "jp",
93
+ "uae": "ae",
94
+ "united arab emirates": "ae",
95
+ "south africa": "za",
96
+ "ireland": "ie",
97
+ "switzerland": "ch",
98
+ "sweden": "se",
99
+ "poland": "pl",
100
+ }
101
+
102
+ _JOB_BOARD_HOST_FRAGMENTS: tuple[str, ...] = (
103
+ "linkedin.",
104
+ "indeed.",
105
+ "glassdoor.",
106
+ "ziprecruiter.",
107
+ "monster.",
108
+ "simplyhired.",
109
+ "dice.com",
110
+ "talent.com",
111
+ "jooble.",
112
+ "adzuna.",
113
+ "reed.co.uk",
114
+ "totaljobs.",
115
+ "stepstone.",
116
+ "xing.com",
117
+ "careerbuilder.",
118
+ "builtin",
119
+ "lensa.",
120
+ "tealhq.",
121
+ "snagajob.",
122
+ "bebee.",
123
+ "learn4good.",
124
+ "4dayweek.io",
125
+ "wellfound.com",
126
+ "angel.co",
127
+ "remotive.com",
128
+ "weworkremotely.com",
129
+ "flexjobs.com",
130
+ "upwork.com",
131
+ )
132
+
133
+ _GOOGLE_SEARCH_HOST_RE = re.compile(
134
+ r"^(?:[a-z0-9-]+\.)?google\.(?:com|[a-z]{2}|co\.[a-z]{2}|com\.[a-z]{2})$",
135
+ re.IGNORECASE,
136
+ )
137
+
138
+ _CORP_SUFFIX_RE = re.compile(
139
+ r"\b(?:inc|incorporated|llc|ltd|limited|plc|corp|corporation|company|co|gmbh|ag|sa|sas|bv|nv|group|holdings|technologies|technology|labs)\b\.?",
140
+ re.IGNORECASE,
141
+ )
142
+
143
+ _DEPARTMENT_PATTERNS: tuple[tuple[str, re.Pattern[str]], ...] = (
144
+ (
145
+ "ai_data",
146
+ re.compile(
147
+ r"\b(?:machine learning|ml\b|ai\b|data scien|data engineer|analytics|llm|nlp|computer vision|bi\b)\b",
148
+ re.IGNORECASE,
149
+ ),
150
+ ),
151
+ (
152
+ "security_it",
153
+ re.compile(
154
+ r"\b(?:security|infosec|appsec|cyber|soc\b|iam\b|pentest|it support|sysadmin)\b",
155
+ re.IGNORECASE,
156
+ ),
157
+ ),
158
+ (
159
+ "engineering",
160
+ re.compile(
161
+ r"\b(?:software|engineer|developer|frontend|front-end|backend|back-end|fullstack|full-stack|devops|sre|platform|infrastructure|ios|android|firmware|qa\b)\b",
162
+ re.IGNORECASE,
163
+ ),
164
+ ),
165
+ (
166
+ "product_design",
167
+ re.compile(r"\b(?:product manager|product owner|ux\b|ui\b|designer|product design)\b", re.IGNORECASE),
168
+ ),
169
+ (
170
+ "sales_gtm",
171
+ re.compile(
172
+ r"\b(?:account executive|sdr\b|bdr\b|sales|solutions architect|sales engineer|customer success|revenue|partnerships|account manager)\b",
173
+ re.IGNORECASE,
174
+ ),
175
+ ),
176
+ (
177
+ "marketing",
178
+ re.compile(r"\b(?:marketing|growth|seo\b|demand gen|content|brand|communications|pr\b)\b", re.IGNORECASE),
179
+ ),
180
+ (
181
+ "finance_ops",
182
+ re.compile(
183
+ r"\b(?:finance|accounting|controller|fp&a|operations|revops|bizops|legal|counsel|compliance)\b",
184
+ re.IGNORECASE,
185
+ ),
186
+ ),
187
+ (
188
+ "hr_recruiting",
189
+ re.compile(r"\b(?:recruiter|recruiting|talent acquisition|people ops|human resources|hr\b)\b", re.IGNORECASE),
190
+ ),
191
+ )
192
+
193
+
194
+ def classify_ats_provider(url: str | None) -> AtsProvider:
195
+ """Classify an application URL into its canonical ATS or job-board category."""
196
+ raw = str(url or "").strip()
197
+ if not raw or not raw.lower().startswith(("http://", "https://")):
198
+ return "job_board"
199
+
200
+ try:
201
+ parsed = urlparse(raw)
202
+ except ValueError:
203
+ return "job_board"
204
+
205
+ host = (parsed.hostname or "").lower().strip(".")
206
+ if not host or "." not in host:
207
+ return "job_board"
208
+
209
+ try:
210
+ ip_obj = ipaddress.ip_address(host.split("%", 1)[0])
211
+ if not ip_obj.is_global or ip_obj.is_private or ip_obj.is_loopback or ip_obj.is_link_local:
212
+ return "job_board"
213
+ except ValueError:
214
+ pass
215
+
216
+ qs = parse_qs(parsed.query)
217
+ qs_keys_low = {k.lower() for k in qs}
218
+
219
+ if (
220
+ host == "greenhouse.io"
221
+ or host.endswith(".greenhouse.io")
222
+ or host == "grnh.se"
223
+ or "gh_jid" in qs_keys_low
224
+ ):
225
+ return "greenhouse"
226
+ if (
227
+ host == "lever.co"
228
+ or host.endswith(".lever.co")
229
+ or "lever-origin" in qs_keys_low
230
+ or "lever-source" in qs_keys_low
231
+ ):
232
+ return "lever"
233
+ if (
234
+ host == "workday.com"
235
+ or host.endswith(".workday.com")
236
+ or host == "myworkdayjobs.com"
237
+ or host.endswith(".myworkdayjobs.com")
238
+ or host == "myworkdaysite.com"
239
+ or host.endswith(".myworkdaysite.com")
240
+ ):
241
+ return "workday"
242
+ if host == "ashbyhq.com" or host.endswith(".ashbyhq.com") or "ashby_jid" in qs_keys_low:
243
+ return "ashby"
244
+ if host == "smartrecruiters.com" or host.endswith(".smartrecruiters.com"):
245
+ return "smartrecruiters"
246
+ if host == "icims.com" or host.endswith(".icims.com"):
247
+ return "icims"
248
+ if host == "bamboohr.com" or host.endswith(".bamboohr.com"):
249
+ return "bamboohr"
250
+ if host == "workable.com" or host.endswith(".workable.com"):
251
+ return "workable"
252
+ if (
253
+ host == "rippling.com"
254
+ or host.endswith(".rippling.com")
255
+ or host == "rippling-ats.com"
256
+ or host.endswith(".rippling-ats.com")
257
+ ):
258
+ return "rippling"
259
+
260
+ if _GOOGLE_SEARCH_HOST_RE.match(host) and not host.startswith(("careers.google.", "jobs.google.")):
261
+ return "job_board"
262
+
263
+ if any(board in host for board in _JOB_BOARD_HOST_FRAGMENTS):
264
+ return "job_board"
265
+
266
+ return "company_direct"
267
+
268
+
269
+ def resolve_best_apply_target(job: Mapping[str, Any]) -> tuple[str | None, AtsProvider, bool]:
270
+ """Select the highest-priority apply URL from `directApplyUrl`, `applyUrl`, and `applyOptions`."""
271
+ candidates: list[str] = []
272
+ for key in ("directApplyUrl", "applyUrl"):
273
+ val = str(job.get(key) or "").strip()
274
+ if val and val not in candidates:
275
+ candidates.append(val)
276
+
277
+ raw_opts = job.get("applyOptions")
278
+ if isinstance(raw_opts, Sequence) and not isinstance(raw_opts, (str, bytes)):
279
+ for opt in raw_opts:
280
+ if isinstance(opt, Mapping):
281
+ lnk = str(opt.get("link") or opt.get("url") or "").strip()
282
+ if lnk and lnk not in candidates:
283
+ candidates.append(lnk)
284
+
285
+ if not candidates:
286
+ return None, "job_board", False
287
+
288
+ def _priority(url: str) -> int:
289
+ prov = classify_ats_provider(url)
290
+ if prov in DIRECT_ATS_PROVIDERS:
291
+ return 3
292
+ if prov == "company_direct":
293
+ return 2
294
+ return 1
295
+
296
+ best_url = max(enumerate(candidates), key=lambda pair: (_priority(pair[1]), -pair[0]))[1]
297
+ provider = classify_ats_provider(best_url)
298
+ return best_url, provider, provider != "job_board"
299
+
300
+
301
+ def enrich_job_ats_metadata(job: Mapping[str, Any]) -> dict[str, Any]:
302
+ """Return a copy of `job` enriched with `bestApplyUrl`, `atsProvider`, and `isDirectEmployerLink`."""
303
+ best_url, provider, is_direct = resolve_best_apply_target(job)
304
+ out = dict(job)
305
+ out["bestApplyUrl"] = best_url
306
+ out["atsProvider"] = provider
307
+ out["isDirectEmployerLink"] = is_direct
308
+ return out
309
+
310
+
311
+ def extract_job_id(job: Mapping[str, Any] | str) -> str:
312
+ """Extract or synthesize a deterministic canonical job ID."""
313
+ if isinstance(job, str):
314
+ cleaned = job.strip()
315
+ if not cleaned:
316
+ raise ValueError("job identifier cannot be empty.")
317
+ return cleaned
318
+
319
+ for key in ("jobId", "job_id", "id"):
320
+ raw = job.get(key)
321
+ if raw is not None and str(raw).strip():
322
+ return str(raw).strip()
323
+
324
+ best_url, _, _ = resolve_best_apply_target(job)
325
+ basis = "|".join(
326
+ [
327
+ str(job.get("company") or "").strip().lower(),
328
+ str(job.get("title") or "").strip().lower(),
329
+ str(job.get("location") or "").strip().lower(),
330
+ str(best_url or ""),
331
+ ]
332
+ )
333
+ digest = hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]
334
+ return f"gjob_{digest}"
335
+
336
+
337
+ def _normalize_company_key(company: str) -> str:
338
+ raw = str(company or "").strip()
339
+ if not raw:
340
+ return ""
341
+ base = raw.split(",")[0].split("(")[0]
342
+ stripped = _CORP_SUFFIX_RE.sub("", base)
343
+ key = re.sub(r"[^a-z0-9]+", " ", stripped.lower()).strip()
344
+ return key or re.sub(r"[^a-z0-9]+", " ", raw.lower()).strip()
345
+
346
+
347
+ def _infer_department(title: str) -> str:
348
+ for dept, pat in _DEPARTMENT_PATTERNS:
349
+ if pat.search(title or ""):
350
+ return dept
351
+ return "other"
352
+
353
+
354
+ def _extract_career_domain(url: str | None, provider: AtsProvider) -> str | None:
355
+ if not url:
356
+ return None
357
+ try:
358
+ host = (urlparse(url).hostname or "").lower().strip(".")
359
+ except ValueError:
360
+ return None
361
+ if not host:
362
+ return None
363
+ if host.startswith("www."):
364
+ host = host[4:]
365
+ if provider == "company_direct":
366
+ for pfx in ("careers.", "jobs.", "apply.", "join."):
367
+ if host.startswith(pfx) and host.count(".") >= 2:
368
+ return host[len(pfx) :]
369
+ return host
370
+
371
+
372
+ def aggregate_hiring_companies(jobs: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
373
+ """Aggregate job postings into company-level B2B hiring signal records."""
374
+ buckets: dict[str, dict[str, Any]] = {}
375
+ seen_job_ids_per_co: dict[str, set[str]] = {}
376
+
377
+ for raw_job in jobs:
378
+ if not isinstance(raw_job, Mapping):
379
+ continue
380
+ company_display = str(raw_job.get("company") or raw_job.get("company_name") or "").strip()
381
+ if not company_display:
382
+ continue
383
+ co_key = _normalize_company_key(company_display)
384
+ if not co_key:
385
+ continue
386
+
387
+ jid = extract_job_id(raw_job)
388
+ seen_for_co = seen_job_ids_per_co.setdefault(co_key, set())
389
+ if jid in seen_for_co:
390
+ continue
391
+ seen_for_co.add(jid)
392
+
393
+ best_url, provider, is_direct = resolve_best_apply_target(raw_job)
394
+ title = str(raw_job.get("title") or "").strip()
395
+ loc = str(raw_job.get("location") or "").strip()
396
+ is_remote = bool(raw_job.get("isRemote")) or str(raw_job.get("workplaceType") or "").lower() == "remote"
397
+ posted_date = str(raw_job.get("postedDate") or "").strip() or None
398
+ logo = str(raw_job.get("companyLogo") or "").strip() or None
399
+ sal_min = raw_job.get("salaryMin")
400
+ sal_max = raw_job.get("salaryMax")
401
+ sal_curr = str(raw_job.get("salaryCurrency") or "").strip() or None
402
+
403
+ b = buckets.get(co_key)
404
+ if b is None:
405
+ b = {
406
+ "company": company_display,
407
+ "company_logo": logo,
408
+ "open_roles_count": 0,
409
+ "remote_roles_count": 0,
410
+ "direct_links_count": 0,
411
+ "provider_counts": Counter(),
412
+ "career_domains": [],
413
+ "departments": Counter(),
414
+ "locations": [],
415
+ "salary_mins": [],
416
+ "salary_maxs": [],
417
+ "salary_currencies": Counter(),
418
+ "posted_dates": [],
419
+ "sample_titles": [],
420
+ "sample_direct_apply_urls": [],
421
+ }
422
+ buckets[co_key] = b
423
+
424
+ b["open_roles_count"] += 1
425
+ if logo and not b["company_logo"]:
426
+ b["company_logo"] = logo
427
+ if is_remote:
428
+ b["remote_roles_count"] += 1
429
+ if is_direct:
430
+ b["direct_links_count"] += 1
431
+ b["provider_counts"][provider] += 1
432
+
433
+ c_dom = _extract_career_domain(best_url, provider)
434
+ if c_dom and provider != "job_board" and c_dom not in b["career_domains"]:
435
+ b["career_domains"].append(c_dom)
436
+
437
+ if title:
438
+ dept = _infer_department(title)
439
+ b["departments"][dept] += 1
440
+ if title not in b["sample_titles"] and len(b["sample_titles"]) < 5:
441
+ b["sample_titles"].append(title)
442
+
443
+ if loc and loc not in b["locations"] and len(b["locations"]) < 8:
444
+ b["locations"].append(loc)
445
+
446
+ if isinstance(sal_min, (int, float)) and sal_min > 0:
447
+ b["salary_mins"].append(float(sal_min))
448
+ if isinstance(sal_max, (int, float)) and sal_max > 0:
449
+ b["salary_maxs"].append(float(sal_max))
450
+ if sal_curr:
451
+ b["salary_currencies"][sal_curr] += 1
452
+
453
+ if posted_date:
454
+ b["posted_dates"].append(posted_date)
455
+
456
+ if best_url and is_direct and best_url not in b["sample_direct_apply_urls"] and len(b["sample_direct_apply_urls"]) < 3:
457
+ b["sample_direct_apply_urls"].append(best_url)
458
+
459
+ aggregated: list[dict[str, Any]] = []
460
+ for b in buckets.values():
461
+ prov_counts: Counter[str] = b["provider_counts"]
462
+ non_board = [(p, cnt) for p, cnt in prov_counts.items() if p != "job_board"]
463
+ primary_ats = sorted(non_board, key=lambda kv: (-kv[1], kv[0]))[0][0] if non_board else "job_board"
464
+
465
+ ats_list = [p for p, _ in prov_counts.most_common()]
466
+ depts = [d for d, _ in b["departments"].most_common()]
467
+ latest_date = max(b["posted_dates"]) if b["posted_dates"] else None
468
+ sal_min_floor = round(min(b["salary_mins"]), 2) if b["salary_mins"] else None
469
+ sal_max_ceil = round(max(b["salary_maxs"]), 2) if b["salary_maxs"] else None
470
+ sal_curr = b["salary_currencies"].most_common(1)[0][0] if b["salary_currencies"] else None
471
+
472
+ velocity = min(45, b["open_roles_count"] * 12)
473
+ if primary_ats in DIRECT_ATS_PROVIDERS:
474
+ velocity += 22
475
+ elif primary_ats == "company_direct":
476
+ velocity += 16
477
+ if len(depts) >= 2:
478
+ velocity += 12
479
+ if sal_max_ceil is not None:
480
+ velocity += 10
481
+ if latest_date is not None:
482
+ velocity += 11
483
+ velocity = min(100, velocity)
484
+
485
+ aggregated.append(
486
+ {
487
+ "company": b["company"],
488
+ "company_logo": b["company_logo"],
489
+ "open_roles_count": b["open_roles_count"],
490
+ "remote_roles_count": b["remote_roles_count"],
491
+ "direct_ats_provider": primary_ats,
492
+ "ats_providers": ats_list,
493
+ "career_domain": b["career_domains"][0] if b["career_domains"] else None,
494
+ "departments_hiring": depts,
495
+ "locations": b["locations"],
496
+ "salary_min_floor": sal_min_floor,
497
+ "salary_max_ceiling": sal_max_ceil,
498
+ "salary_currency": sal_curr,
499
+ "latest_posted_date": latest_date,
500
+ "sample_titles": b["sample_titles"],
501
+ "sample_direct_apply_urls": b["sample_direct_apply_urls"],
502
+ "hiring_velocity_score": velocity,
503
+ }
504
+ )
505
+
506
+ aggregated.sort(
507
+ key=lambda r: (-r["open_roles_count"], -r["hiring_velocity_score"], str(r["company"]).lower())
508
+ )
509
+ return aggregated
510
+
511
+
512
+ def _map_jobspy_job_type(raw_emp: str | None) -> str | None:
513
+ if not raw_emp:
514
+ return None
515
+ low = raw_emp.strip().lower().replace("-", "").replace(" ", "")
516
+ if "fulltime" in low:
517
+ return "fulltime"
518
+ if "parttime" in low:
519
+ return "parttime"
520
+ if "contract" in low or "temp" in low:
521
+ return "contract"
522
+ if "intern" in low:
523
+ return "internship"
524
+ return raw_emp.strip().lower()
525
+
526
+
527
+ def _map_jobspy_interval(raw_interval: str | None) -> str | None:
528
+ if not raw_interval:
529
+ return None
530
+ low = raw_interval.strip().lower()
531
+ return {
532
+ "year": "yearly",
533
+ "month": "monthly",
534
+ "week": "weekly",
535
+ "day": "daily",
536
+ "hour": "hourly",
537
+ }.get(low, low)
538
+
539
+
540
+ def to_jobspy_row(job: Mapping[str, Any]) -> dict[str, Any]:
541
+ """Convert a UnitBytes `JobPost` dict into `python-jobspy` column schema."""
542
+ best_url, provider, is_direct = resolve_best_apply_target(job)
543
+ sal_min = job.get("salaryMin")
544
+ sal_max = job.get("salaryMax")
545
+ has_salary = sal_min is not None or sal_max is not None
546
+
547
+ return {
548
+ "id": extract_job_id(job),
549
+ "site": "google",
550
+ "job_url": job.get("googleJobsUrl") or job.get("applyUrl") or best_url,
551
+ "job_url_direct": best_url if is_direct else (job.get("directApplyUrl") or best_url),
552
+ "title": job.get("title") or "",
553
+ "company": job.get("company") or "",
554
+ "location": job.get("location") or "",
555
+ "date_posted": job.get("postedDate"),
556
+ "job_type": _map_jobspy_job_type(str(job.get("employmentType") or "") or None),
557
+ "salary_source": "direct_data" if has_salary else None,
558
+ "interval": _map_jobspy_interval(str(job.get("salaryInterval") or "") or None),
559
+ "min_amount": sal_min,
560
+ "max_amount": sal_max,
561
+ "currency": job.get("salaryCurrency"),
562
+ "is_remote": bool(job.get("isRemote")),
563
+ "job_level": job.get("degreeRequirement"),
564
+ "company_logo": job.get("companyLogo"),
565
+ "description": job.get("description") or "",
566
+ "ats_provider": provider,
567
+ "workplace_type": job.get("workplaceType") or ("Remote" if job.get("isRemote") else "On-site"),
568
+ }
569
+
570
+
571
+ def _normalize_queries(queries: Sequence[str] | str) -> list[str]:
572
+ items: list[str] = []
573
+ if isinstance(queries, str):
574
+ for part in re.split(r"[\r\n,;]+", queries):
575
+ if part.strip():
576
+ items.append(part.strip())
577
+ elif isinstance(queries, Sequence):
578
+ for el in queries:
579
+ if isinstance(el, bool) or not isinstance(el, str):
580
+ raise ValueError("Each query in 'queries' must be a string.")
581
+ if el.strip():
582
+ items.append(el.strip())
583
+ else:
584
+ raise ValueError("queries must be a string or sequence of job search strings.")
585
+
586
+ deduped: list[str] = []
587
+ seen: set[str] = set()
588
+ for q in items:
589
+ low = q.lower()
590
+ if low not in seen:
591
+ seen.add(low)
592
+ deduped.append(q)
593
+ if not deduped:
594
+ raise ValueError("Provide at least one non-empty job search query.")
595
+ return deduped
596
+
597
+
598
+ def _normalize_locations(locations: Sequence[str] | str | None) -> list[str]:
599
+ if locations is None:
600
+ return []
601
+ if isinstance(locations, str):
602
+ cleaned = locations.strip()
603
+ if not cleaned:
604
+ return []
605
+ if ";" in cleaned or "\n" in cleaned:
606
+ return [p.strip() for p in re.split(r"[\r\n;]+", cleaned) if p.strip()]
607
+ return [cleaned]
608
+ if isinstance(locations, Sequence):
609
+ return [str(loc).strip() for loc in locations if loc is not None and str(loc).strip()]
610
+ raise ValueError("locations must be a string or sequence of location strings.")
611
+
612
+
613
+ def _normalize_country(country: str | None) -> str:
614
+ if not country or not str(country).strip():
615
+ return "us"
616
+ low = str(country).strip().lower()
617
+ mapped = _COUNTRY_ALIASES.get(low, low)
618
+ if len(mapped) != 2 or not mapped.isalpha():
619
+ raise ValueError(
620
+ f"Invalid country {country!r}. Provide a 2-letter ISO code ('us', 'gb', 'de') or country name ('usa', 'uk')."
621
+ )
622
+ return mapped
623
+
624
+
625
+ def _normalize_employment_types(employment_types: Sequence[str] | str | None) -> list[EmploymentTypeOption]:
626
+ if employment_types is None:
627
+ return []
628
+ raw_list: Sequence[str] = (
629
+ [p.strip() for p in re.split(r"[\r\n,;|]+", employment_types) if p.strip()]
630
+ if isinstance(employment_types, str)
631
+ else [str(x).strip() for x in employment_types if x is not None and str(x).strip()]
632
+ )
633
+ out: list[EmploymentTypeOption] = []
634
+ for item in raw_list:
635
+ mapped = _EMPLOYMENT_TYPE_ALIASES.get(item.upper())
636
+ if not mapped:
637
+ raise ValueError(
638
+ f"Invalid employment type {item!r}. Expected FULLTIME, PARTTIME, CONTRACTOR, or INTERN."
639
+ )
640
+ if mapped not in out:
641
+ out.append(mapped)
642
+ return out
643
+
644
+
645
+ def _hours_old_to_date_posted(hours_old: int | float | None) -> DatePostedOption:
646
+ if hours_old is None:
647
+ return "any"
648
+ hrs = float(hours_old)
649
+ if hrs <= 0:
650
+ return "any"
651
+ if hrs <= 24:
652
+ return "today"
653
+ if hrs <= 72:
654
+ return "3days"
655
+ if hrs <= 168:
656
+ return "week"
657
+ if hrs <= 744:
658
+ return "month"
659
+ return "any"
660
+
661
+
662
+ class JobsNamespace:
663
+ """Google Jobs search, ATS enrichment, JobSpy migration, and hiring velocity signals (`ub.jobs`)."""
664
+
665
+ def __init__(self, client: UnitBytes) -> None:
666
+ self._client = client
667
+
668
+ def search(
669
+ self,
670
+ queries: Sequence[str] | str,
671
+ *,
672
+ locations: Sequence[str] | str | None = None,
673
+ country: str = "us",
674
+ language: str = "",
675
+ date_posted: DatePostedOption = "any",
676
+ employment_types: Sequence[str] | str | None = None,
677
+ remote_only: bool = False,
678
+ max_jobs: int = 50,
679
+ resolve_apply_links: bool = True,
680
+ direct_ats_only: bool = False,
681
+ allowed_ats_providers: Sequence[AtsProvider | str] | None = None,
682
+ only_new: bool = False,
683
+ state_file: str | os.PathLike[str] | None = None,
684
+ proxy_configuration: Mapping[str, Any] | None = None,
685
+ max_total_charge_usd: float | Decimal | None = None,
686
+ ) -> list[dict[str, Any]]:
687
+ """Search Google Jobs across 80+ countries and enrich every posting with direct ATS metadata."""
688
+ norm_queries = _normalize_queries(queries)
689
+ norm_locations = _normalize_locations(locations)
690
+ norm_country = _normalize_country(country)
691
+ norm_emp = _normalize_employment_types(employment_types)
692
+
693
+ if isinstance(max_jobs, bool) or int(max_jobs) < 1:
694
+ raise ValueError(f"max_jobs must be >= 1, got {max_jobs!r}.")
695
+ capped_max = min(5000, int(max_jobs))
696
+
697
+ dp_clean = str(date_posted or "any").strip().lower()
698
+ if dp_clean not in _VALID_DATE_POSTED:
699
+ raise ValueError(
700
+ f"Invalid date_posted {date_posted!r}. Expected one of: any, today, 3days, week, month."
701
+ )
702
+
703
+ run_input: dict[str, Any] = {
704
+ "queries": norm_queries,
705
+ "country": norm_country,
706
+ "language": str(language or "").strip().lower(),
707
+ "datePosted": dp_clean,
708
+ "remoteOnly": bool(remote_only),
709
+ "maxJobs": capped_max,
710
+ "resolveApplyLinks": bool(resolve_apply_links),
711
+ }
712
+ if norm_locations:
713
+ run_input["locations"] = norm_locations
714
+ if norm_emp:
715
+ run_input["employmentTypes"] = norm_emp
716
+ if proxy_configuration is not None:
717
+ run_input["proxyConfiguration"] = dict(proxy_configuration)
718
+
719
+ raw = self._client._transport.execute_operation(
720
+ service="jobs",
721
+ operation="search",
722
+ actor_slug=ACTOR_GOOGLE_JOBS,
723
+ actor_input=run_input,
724
+ http_method="POST",
725
+ json_body=run_input,
726
+ max_total_charge_usd=max_total_charge_usd,
727
+ )
728
+ raw_rows = unwrap_items_payload(raw)
729
+
730
+ seen_ids: set[str] = set()
731
+ enriched: list[dict[str, Any]] = []
732
+ allowed_set = (
733
+ {str(p).strip().lower() for p in allowed_ats_providers if str(p).strip()}
734
+ if allowed_ats_providers
735
+ else None
736
+ )
737
+
738
+ for row in raw_rows:
739
+ if row.get("error"):
740
+ continue
741
+ item = enrich_job_ats_metadata(row)
742
+ jid = extract_job_id(item)
743
+ if jid in seen_ids:
744
+ continue
745
+ seen_ids.add(jid)
746
+
747
+ if direct_ats_only and not item["isDirectEmployerLink"]:
748
+ continue
749
+ if allowed_set is not None and item["atsProvider"] not in allowed_set:
750
+ continue
751
+ enriched.append(item)
752
+
753
+ if only_new:
754
+ enriched = filter_unseen_by_key(
755
+ enriched,
756
+ key_fn=extract_job_id,
757
+ state_file=state_file or DEFAULT_WATCHLIST_STATE_FILE,
758
+ id_field="seen_job_ids",
759
+ max_return=capped_max,
760
+ )
761
+
762
+ return enriched[:capped_max]
763
+
764
+ def scrape_jobspy_compat(
765
+ self,
766
+ *,
767
+ search_term: str | Sequence[str] | None = None,
768
+ google_search_term: str | None = None,
769
+ location: str | None = None,
770
+ locations: Sequence[str] | None = None,
771
+ results_wanted: int = 20,
772
+ hours_old: int | float | None = None,
773
+ job_type: str | None = None,
774
+ is_remote: bool = False,
775
+ country_indeed: str = "usa",
776
+ language: str = "",
777
+ resolve_apply_links: bool = True,
778
+ direct_ats_only: bool = False,
779
+ only_new: bool = False,
780
+ state_file: str | os.PathLike[str] | None = None,
781
+ as_dataframe: bool = False,
782
+ max_total_charge_usd: float | Decimal | None = None,
783
+ ) -> Any:
784
+ """Drop-in Google Jobs migration helper matching `python-jobspy`'s `scrape_jobs` schema."""
785
+ effective_query = google_search_term or search_term
786
+ if not effective_query:
787
+ raise ValueError("Provide 'search_term' or 'google_search_term'.")
788
+
789
+ pd = require_pandas() if as_dataframe else None
790
+ effective_locs: Sequence[str] | str | None = locations if locations is not None else location
791
+ date_posted = _hours_old_to_date_posted(hours_old)
792
+
793
+ jobs = self.search(
794
+ effective_query,
795
+ locations=effective_locs,
796
+ country=country_indeed,
797
+ language=language,
798
+ date_posted=date_posted,
799
+ employment_types=job_type,
800
+ remote_only=is_remote,
801
+ max_jobs=results_wanted,
802
+ resolve_apply_links=resolve_apply_links,
803
+ direct_ats_only=direct_ats_only,
804
+ only_new=only_new,
805
+ state_file=state_file,
806
+ max_total_charge_usd=max_total_charge_usd,
807
+ )
808
+ rows = [to_jobspy_row(j) for j in jobs]
809
+ if as_dataframe and pd is not None:
810
+ return pd.DataFrame(rows)
811
+ return rows
812
+
813
+ @staticmethod
814
+ def classify_ats_provider(url: str | None) -> AtsProvider:
815
+ """Classify an application URL into its canonical ATS (`greenhouse`, `lever`, `workday`, `ashby`, ...) or `job_board`."""
816
+ return classify_ats_provider(url)
817
+
818
+ def aggregate_hiring_companies(
819
+ self,
820
+ jobs_or_queries: Sequence[Mapping[str, Any]] | Sequence[str] | str,
821
+ *,
822
+ locations: Sequence[str] | str | None = None,
823
+ country: str = "us",
824
+ date_posted: DatePostedOption = "week",
825
+ remote_only: bool = False,
826
+ max_jobs: int = 50,
827
+ max_total_charge_usd: float | Decimal | None = None,
828
+ ) -> list[dict[str, Any]]:
829
+ """Aggregate already-fetched job records (offline) OR live search queries into company hiring velocity signals."""
830
+ if isinstance(jobs_or_queries, str):
831
+ fetched = self.search(
832
+ jobs_or_queries,
833
+ locations=locations,
834
+ country=country,
835
+ date_posted=date_posted,
836
+ remote_only=remote_only,
837
+ max_jobs=max_jobs,
838
+ max_total_charge_usd=max_total_charge_usd,
839
+ )
840
+ return aggregate_hiring_companies(fetched)
841
+
842
+ seq = list(jobs_or_queries)
843
+ if not seq:
844
+ return []
845
+ if all(isinstance(x, str) for x in seq):
846
+ fetched = self.search(
847
+ [str(x) for x in seq],
848
+ locations=locations,
849
+ country=country,
850
+ date_posted=date_posted,
851
+ remote_only=remote_only,
852
+ max_jobs=max_jobs,
853
+ max_total_charge_usd=max_total_charge_usd,
854
+ )
855
+ return aggregate_hiring_companies(fetched)
856
+
857
+ return aggregate_hiring_companies([x for x in seq if isinstance(x, Mapping)])
858
+
859
+
860
+ __all__ = [
861
+ "JobsNamespace",
862
+ "AtsProvider",
863
+ "DIRECT_ATS_PROVIDERS",
864
+ "classify_ats_provider",
865
+ "enrich_job_ats_metadata",
866
+ "extract_job_id",
867
+ "aggregate_hiring_companies",
868
+ "to_jobspy_row",
869
+ ]