jobstreaming 0.0.1__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.
@@ -0,0 +1,291 @@
1
+ from __future__ import annotations
2
+
3
+ import random
4
+ import threading
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from urllib.parse import parse_qs, urljoin, urlsplit
7
+
8
+ from bs4 import BeautifulSoup
9
+ from bs4.element import Tag
10
+
11
+ from jobstreaming.bdjobs.constant import headers, search_params
12
+ from jobstreaming.bdjobs.util import (
13
+ find_job_listings,
14
+ is_job_remote,
15
+ parse_date,
16
+ parse_location,
17
+ )
18
+ from jobstreaming.exception import BDJobsException
19
+ from jobstreaming.model import (
20
+ AdapterCapabilities,
21
+ DescriptionFormat,
22
+ JobPost,
23
+ JobResponse,
24
+ JobType,
25
+ Scraper,
26
+ ScraperInput,
27
+ Site,
28
+ )
29
+ from jobstreaming.runtime import ScrapeContext
30
+ from jobstreaming.util import (
31
+ create_logger,
32
+ create_session,
33
+ extract_emails_from_text,
34
+ markdown_converter,
35
+ plain_converter,
36
+ stable_job_id,
37
+ )
38
+
39
+ log = create_logger("BDJobs")
40
+
41
+
42
+ class BDJobs(Scraper):
43
+ base_url = "https://jobs.bdjobs.com"
44
+ search_url = "https://jobs.bdjobs.com/jobsearch.asp"
45
+ delay = 2
46
+ band_delay = 3
47
+ capabilities = AdapterCapabilities(
48
+ filters=frozenset({"offset", "description_format"}),
49
+ supports_resume=True,
50
+ resume_granularity="page",
51
+ )
52
+
53
+ def __init__(
54
+ self,
55
+ proxies: list[str] | str | None = None,
56
+ ca_cert: str | None = None,
57
+ user_agent: str | None = None,
58
+ ) -> None:
59
+ super().__init__(
60
+ Site.BDJOBS,
61
+ proxies=proxies,
62
+ ca_cert=ca_cert,
63
+ user_agent=user_agent,
64
+ )
65
+ self.session = self._new_session()
66
+ self.scraper_input: ScraperInput | None = None
67
+ self._thread_local = threading.local()
68
+
69
+ def _new_session(self):
70
+ session = create_session(
71
+ proxies=self.proxies,
72
+ ca_cert=self.ca_cert,
73
+ is_tls=False,
74
+ has_retry=True,
75
+ delay=5,
76
+ clear_cookies=True,
77
+ )
78
+ request_headers = headers.copy()
79
+ if self.user_agent:
80
+ request_headers["User-Agent"] = self.user_agent
81
+ session.headers.update(request_headers)
82
+ return session
83
+
84
+ def scrape(
85
+ self, scraper_input: ScraperInput, context: ScrapeContext | None = None
86
+ ) -> JobResponse:
87
+ self.scraper_input = scraper_input
88
+ context = ScrapeContext.local(self.site, scraper_input, context)
89
+ emitted: list[JobPost] = []
90
+ state = context.resume_state
91
+ page = int(state.get("page", 1))
92
+ raw_seen = int(state.get("raw_seen", 0))
93
+
94
+ while context.should_continue and page <= scraper_input.max_pages:
95
+ params = search_params.copy()
96
+ params["txtsearch"] = scraper_input.search_term or ""
97
+ if page > 1:
98
+ params["pg"] = page
99
+ response = self.session.get(
100
+ self.search_url,
101
+ params=params,
102
+ timeout=scraper_input.request_timeout,
103
+ )
104
+ if response.status_code != 200:
105
+ raise BDJobsException(f"BDJobs returned HTTP {response.status_code}")
106
+ cards = find_job_listings(BeautifulSoup(response.text, "html.parser"))
107
+ if not cards:
108
+ break
109
+
110
+ page_state = {"page": page, "raw_seen": raw_seen}
111
+ candidates = [
112
+ card
113
+ for index, card in enumerate(cards)
114
+ if raw_seen + index >= scraper_input.offset
115
+ ]
116
+ with ThreadPoolExecutor(
117
+ max_workers=min(8, max(1, len(candidates)))
118
+ ) as pool:
119
+ futures = {
120
+ pool.submit(self._process_job, card): card for card in candidates
121
+ }
122
+ for future in as_completed(futures):
123
+ if not context.should_continue:
124
+ break
125
+ try:
126
+ job = future.result()
127
+ if job and context.emit_job(job, page_state):
128
+ emitted.append(job)
129
+ except Exception as exc:
130
+ context.emit_warning(
131
+ f"Skipped BDJobs listing: {type(exc).__name__}: {exc}"
132
+ )
133
+
134
+ raw_seen += len(cards)
135
+ context.emit_progress(
136
+ {"page": page + 1, "raw_seen": raw_seen},
137
+ f"completed BDJobs page {page}",
138
+ )
139
+ if not context.should_continue:
140
+ break
141
+ page += 1
142
+ if not context.wait(
143
+ random.uniform(self.delay, self.delay + self.band_delay)
144
+ ):
145
+ break
146
+
147
+ return JobResponse(jobs=emitted)
148
+
149
+ def _process_job(self, job_card: Tag) -> JobPost | None:
150
+ assert self.scraper_input is not None
151
+ job_link = job_card.find(
152
+ "a", href=lambda value: value and "jobdetail" in value.lower()
153
+ )
154
+ if not isinstance(job_link, Tag):
155
+ return None
156
+ href = job_link.get("href")
157
+ if not isinstance(href, str):
158
+ return None
159
+ job_url = urljoin(self.base_url, href)
160
+ title = job_link.get_text(strip=True)
161
+ if not title:
162
+ return None
163
+
164
+ company_element = job_card.find(
165
+ ["span", "div"],
166
+ class_=lambda value: value
167
+ and any(
168
+ marker
169
+ in " ".join(value if isinstance(value, list) else [value]).lower()
170
+ for marker in ("comp-name-text", "company", "org", "comp-name")
171
+ ),
172
+ )
173
+ company_name = company_element.get_text(strip=True) if company_element else None
174
+
175
+ location_element = job_card.find(
176
+ ["span", "div"],
177
+ class_=lambda value: value
178
+ and any(
179
+ marker
180
+ in " ".join(value if isinstance(value, list) else [value]).lower()
181
+ for marker in ("locon-text-d", "location", "area", "locon")
182
+ ),
183
+ )
184
+ location = parse_location(
185
+ location_element.get_text(strip=True) if location_element else None
186
+ )
187
+
188
+ published_element = job_card.find(
189
+ ["span", "div"],
190
+ class_=lambda value: value
191
+ and "published"
192
+ in " ".join(value if isinstance(value, list) else [value]).lower(),
193
+ )
194
+ date_posted = (
195
+ parse_date(published_element.get_text(strip=True))
196
+ if published_element
197
+ else None
198
+ )
199
+ details = self._get_job_details(job_url)
200
+ description = details.get("description")
201
+ is_remote = is_job_remote(title, description=description, location=location)
202
+
203
+ query = {
204
+ key.lower(): value
205
+ for key, value in parse_qs(urlsplit(job_url).query).items()
206
+ }
207
+ source_id = query.get("jobid", [None])[0]
208
+ job_id = f"bd-{source_id}" if source_id else stable_job_id("bdjobs", job_url)
209
+ return JobPost(
210
+ id=job_id,
211
+ title=title,
212
+ company_name=company_name or None,
213
+ location=location,
214
+ date_posted=date_posted,
215
+ job_url=job_url,
216
+ is_remote=is_remote,
217
+ description=description,
218
+ emails=extract_emails_from_text(description or ""),
219
+ job_type=details.get("job_type"),
220
+ company_industry=details.get("company_industry"),
221
+ )
222
+
223
+ def _get_job_details(self, job_url: str) -> dict[str, object]:
224
+ assert self.scraper_input is not None
225
+ session = self._detail_session()
226
+ response = session.get(job_url, timeout=self.scraper_input.request_timeout)
227
+ if response.status_code != 200:
228
+ raise BDJobsException(
229
+ f"BDJobs detail page returned HTTP {response.status_code}"
230
+ )
231
+ soup = BeautifulSoup(response.text, "html.parser")
232
+
233
+ content = soup.find("div", class_="jobcontent") or soup.find(
234
+ ["div", "section"],
235
+ class_=lambda value: value
236
+ and any(
237
+ marker
238
+ in " ".join(value if isinstance(value, list) else [value]).lower()
239
+ for marker in ("job-description", "details", "requirements")
240
+ ),
241
+ )
242
+ description = None
243
+ if isinstance(content, Tag):
244
+ for element in content.find_all(["script", "style"]):
245
+ element.decompose()
246
+ html = str(content)
247
+ if self.scraper_input.description_format == DescriptionFormat.MARKDOWN:
248
+ description = markdown_converter(html)
249
+ elif self.scraper_input.description_format == DescriptionFormat.PLAIN:
250
+ description = plain_converter(html)
251
+ else:
252
+ description = html
253
+
254
+ job_type = None
255
+ label = soup.find(
256
+ ["span", "div"],
257
+ string=lambda value: value
258
+ and any(
259
+ marker in value.lower() for marker in ("job type", "employment type")
260
+ ),
261
+ )
262
+ if label:
263
+ value_element = label.find_next(["span", "div"])
264
+ value = value_element.get_text(strip=True) if value_element else ""
265
+ try:
266
+ job_type = (JobType.from_string(value),) if value else None
267
+ except ValueError:
268
+ job_type = None
269
+
270
+ industry = None
271
+ industry_label = soup.find(
272
+ ["span", "div"],
273
+ string=lambda value: value and "industry" in value.lower(),
274
+ )
275
+ if industry_label:
276
+ industry_element = industry_label.find_next(["span", "div"])
277
+ industry = (
278
+ industry_element.get_text(strip=True) if industry_element else None
279
+ )
280
+ return {
281
+ "description": description,
282
+ "job_type": job_type,
283
+ "company_industry": industry,
284
+ }
285
+
286
+ def _detail_session(self):
287
+ session = getattr(self._thread_local, "session", None)
288
+ if session is None:
289
+ session = self._new_session()
290
+ self._thread_local.session = session
291
+ return session
@@ -0,0 +1,32 @@
1
+ # constant.py
2
+ # Headers for BDJobs requests
3
+ headers = {
4
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
5
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
6
+ "Accept-Language": "en-US,en;q=0.5",
7
+ "Connection": "keep-alive",
8
+ "Referer": "https://jobs.bdjobs.com/",
9
+ "Cache-Control": "max-age=0",
10
+ }
11
+
12
+ # Search parameters that work best for BDJobs
13
+ search_params = {
14
+ "hidJobSearch": "jobsearch",
15
+ }
16
+
17
+ # Selectors for job listings
18
+ job_selectors = [
19
+ "div.job-item", # Catches both normal and premium job cards, as well as other types
20
+ "div.sout-jobs-wrapper", # Catches job listings in the main search results page
21
+ "div.norm-jobs-wrapper", # Catches normal job listings
22
+ "div.featured-wrap", # Catches featured job listings
23
+ ]
24
+
25
+ # Date formats used by BDJobs
26
+ date_formats = [
27
+ "%d %b %Y",
28
+ "%d-%b-%Y",
29
+ "%d %B %Y",
30
+ "%B %d, %Y",
31
+ "%d/%m/%Y",
32
+ ]
@@ -0,0 +1,110 @@
1
+ # util.py
2
+ from datetime import date, datetime
3
+ from typing import Any
4
+
5
+ from bs4 import BeautifulSoup
6
+
7
+ from jobstreaming.model import Country, Location
8
+
9
+
10
+ def parse_location(
11
+ location_text: str | None, country: str = "bangladesh"
12
+ ) -> Location | None:
13
+ """
14
+ Parses location text into a Location object
15
+ :param location_text: Location text from job listing
16
+ :param country: Default country
17
+ :return: Location object
18
+ """
19
+ if not location_text or not location_text.strip():
20
+ return None
21
+ parts = [part.strip() for part in location_text.split(",") if part.strip()]
22
+ country_enum = Country.from_string(country)
23
+ has_country_suffix = bool(
24
+ parts and parts[-1].lower() in country_enum.value[0].split(",")
25
+ )
26
+ if len(parts) >= 2:
27
+ state_parts = parts[1:-1] if has_country_suffix else parts[1:]
28
+ return Location(
29
+ city=parts[0],
30
+ state=", ".join(state_parts) or None,
31
+ country=country_enum,
32
+ )
33
+ return Location(city=parts[0], country=country_enum)
34
+
35
+
36
+ def parse_date(date_text: str) -> date | None:
37
+ """
38
+ Parses date text into a datetime object
39
+ :param date_text: Date text from job listing
40
+ :return: datetime object or None if parsing fails
41
+ """
42
+ from .constant import date_formats
43
+
44
+ try:
45
+ # Clean up date text
46
+ lowered = date_text.lower()
47
+ if "deadline" in lowered:
48
+ return None
49
+ date_text = date_text.replace("Published:", "").strip()
50
+
51
+ # Try different date formats
52
+ for fmt in date_formats:
53
+ try:
54
+ return datetime.strptime(date_text, fmt).date()
55
+ except ValueError:
56
+ continue
57
+
58
+ return None
59
+ except Exception:
60
+ return None
61
+
62
+
63
+ def find_job_listings(soup: BeautifulSoup) -> list[Any]:
64
+ """
65
+ Finds job listing elements in the HTML
66
+ :param soup: BeautifulSoup object
67
+ :return: List of job card elements
68
+ """
69
+ from .constant import job_selectors
70
+
71
+ # Try different selectors
72
+ for selector in job_selectors:
73
+ if "." in selector:
74
+ tag_name, class_name = selector.split(".", 1)
75
+ elements = soup.find_all(tag_name, class_=class_name)
76
+ if elements and len(elements) > 0:
77
+ return elements
78
+
79
+ # If no selectors match, look for job detail links
80
+ job_links = soup.find_all("a", href=lambda h: h and "jobdetail" in h.lower())
81
+ if job_links:
82
+ # Return parent elements of job links
83
+ return [link.parent for link in job_links]
84
+
85
+ return []
86
+
87
+
88
+ def is_job_remote(
89
+ title: str,
90
+ description: str | None = None,
91
+ location: Location | None = None,
92
+ ) -> bool:
93
+ """
94
+ Determines if a job is remote based on title, description, and location
95
+ :param title: Job title
96
+ :param description: Job description
97
+ :param location: Job location
98
+ :return: True if job is remote, False otherwise
99
+ """
100
+ remote_keywords = ["remote", "work from home", "wfh", "home based"]
101
+
102
+ # Combine all text fields
103
+ full_text = title.lower()
104
+ if description:
105
+ full_text += " " + description.lower()
106
+ if location:
107
+ full_text += " " + location.display_location().lower()
108
+
109
+ # Check for remote keywords
110
+ return any(keyword in full_text for keyword in remote_keywords)
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import tempfile
5
+ from pathlib import Path
6
+ from threading import Lock
7
+ from typing import Protocol
8
+
9
+ from jobstreaming.events import SearchCheckpoint
10
+
11
+
12
+ class CheckpointError(RuntimeError):
13
+ pass
14
+
15
+
16
+ class CheckpointMismatchError(CheckpointError):
17
+ pass
18
+
19
+
20
+ class CheckpointStore(Protocol):
21
+ def load(self) -> SearchCheckpoint | None: ...
22
+
23
+ def save(self, checkpoint: SearchCheckpoint) -> None: ...
24
+
25
+ def clear(self) -> None: ...
26
+
27
+
28
+ class MemoryCheckpointStore:
29
+ def __init__(self) -> None:
30
+ self._checkpoint: SearchCheckpoint | None = None
31
+ self._lock = Lock()
32
+
33
+ def load(self) -> SearchCheckpoint | None:
34
+ with self._lock:
35
+ if self._checkpoint is None:
36
+ return None
37
+ return self._checkpoint.model_copy(deep=True)
38
+
39
+ def save(self, checkpoint: SearchCheckpoint) -> None:
40
+ with self._lock:
41
+ self._checkpoint = checkpoint.model_copy(deep=True)
42
+
43
+ def clear(self) -> None:
44
+ with self._lock:
45
+ self._checkpoint = None
46
+
47
+
48
+ class JsonFileCheckpointStore:
49
+ """Atomic JSON checkpoint storage for a single search stream."""
50
+
51
+ def __init__(self, path: str | Path) -> None:
52
+ self.path = Path(path).expanduser().resolve()
53
+ self._lock = Lock()
54
+
55
+ def load(self) -> SearchCheckpoint | None:
56
+ with self._lock:
57
+ if not self.path.exists():
58
+ return None
59
+ try:
60
+ return SearchCheckpoint.model_validate_json(
61
+ self.path.read_text(encoding="utf-8")
62
+ )
63
+ except Exception as exc:
64
+ raise CheckpointError(
65
+ f"Unable to read checkpoint {self.path}: {exc}"
66
+ ) from exc
67
+
68
+ def save(self, checkpoint: SearchCheckpoint) -> None:
69
+ payload = checkpoint.model_dump_json(indent=2)
70
+ with self._lock:
71
+ self.path.parent.mkdir(parents=True, exist_ok=True)
72
+ temporary_name: str | None = None
73
+ try:
74
+ with tempfile.NamedTemporaryFile(
75
+ mode="w",
76
+ encoding="utf-8",
77
+ dir=self.path.parent,
78
+ prefix=f".{self.path.name}.",
79
+ suffix=".tmp",
80
+ delete=False,
81
+ ) as handle:
82
+ temporary_name = handle.name
83
+ handle.write(payload)
84
+ handle.flush()
85
+ os.fsync(handle.fileno())
86
+ os.replace(temporary_name, self.path)
87
+ finally:
88
+ if temporary_name and os.path.exists(temporary_name):
89
+ os.unlink(temporary_name)
90
+
91
+ def clear(self) -> None:
92
+ with self._lock:
93
+ self.path.unlink(missing_ok=True)
jobstreaming/events.py ADDED
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass
5
+ from datetime import datetime, timezone
6
+ from enum import Enum
7
+ from types import MappingProxyType
8
+ from typing import Any, TypeAlias
9
+
10
+ from pydantic import Field
11
+
12
+ from jobstreaming.model import FrozenModel, JobPost, SearchRequest, Site
13
+
14
+
15
+ def freeze_state(state: Mapping[str, Any]) -> Mapping[str, Any]:
16
+ """Return a deeply read-only snapshot of adapter resume state."""
17
+
18
+ def freeze(value: Any) -> Any:
19
+ if isinstance(value, Mapping):
20
+ return MappingProxyType(
21
+ {str(key): freeze(item) for key, item in value.items()}
22
+ )
23
+ if isinstance(value, (list, tuple)):
24
+ return tuple(freeze(item) for item in value)
25
+ if isinstance(value, (set, frozenset)):
26
+ return frozenset(freeze(item) for item in value)
27
+ return value
28
+
29
+ return freeze(state)
30
+
31
+
32
+ def thaw_state(state: Mapping[str, Any]) -> dict[str, Any]:
33
+ """Return a detached, checkpoint-serializable copy of resume state."""
34
+
35
+ def thaw(value: Any) -> Any:
36
+ if isinstance(value, Mapping):
37
+ return {str(key): thaw(item) for key, item in value.items()}
38
+ if isinstance(value, tuple):
39
+ return [thaw(item) for item in value]
40
+ if isinstance(value, frozenset):
41
+ return [thaw(item) for item in sorted(value, key=repr)]
42
+ return value
43
+
44
+ return thaw(state)
45
+
46
+
47
+ class EventType(str, Enum):
48
+ JOB = "job"
49
+ PROGRESS = "progress"
50
+ WARNING = "warning"
51
+ ERROR = "error"
52
+ SITE_COMPLETE = "site_complete"
53
+ SEARCH_COMPLETE = "search_complete"
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class JobEvent:
58
+ sequence: int
59
+ emitted_at: datetime
60
+ site: Site
61
+ job: JobPost
62
+ job_key: str
63
+ resume_state: Mapping[str, Any]
64
+ type: EventType = EventType.JOB
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class ProgressEvent:
69
+ sequence: int
70
+ emitted_at: datetime
71
+ site: Site
72
+ resume_state: Mapping[str, Any]
73
+ message: str | None = None
74
+ type: EventType = EventType.PROGRESS
75
+
76
+
77
+ @dataclass(frozen=True, slots=True)
78
+ class WarningEvent:
79
+ sequence: int
80
+ emitted_at: datetime
81
+ site: Site
82
+ message: str
83
+ resume_state: Mapping[str, Any]
84
+ type: EventType = EventType.WARNING
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class ErrorEvent:
89
+ sequence: int
90
+ emitted_at: datetime
91
+ site: Site
92
+ message: str
93
+ error_type: str
94
+ recoverable: bool
95
+ resume_state: Mapping[str, Any]
96
+ type: EventType = EventType.ERROR
97
+
98
+
99
+ @dataclass(frozen=True, slots=True)
100
+ class SiteCompleteEvent:
101
+ sequence: int
102
+ emitted_at: datetime
103
+ site: Site
104
+ emitted_count: int
105
+ resume_state: Mapping[str, Any]
106
+ type: EventType = EventType.SITE_COMPLETE
107
+
108
+
109
+ @dataclass(frozen=True, slots=True)
110
+ class SearchCompleteEvent:
111
+ sequence: int
112
+ emitted_at: datetime
113
+ total_jobs: int
114
+ total_errors: int
115
+ completed: bool
116
+ type: EventType = EventType.SEARCH_COMPLETE
117
+
118
+
119
+ SearchEvent: TypeAlias = (
120
+ JobEvent
121
+ | ProgressEvent
122
+ | WarningEvent
123
+ | ErrorEvent
124
+ | SiteCompleteEvent
125
+ | SearchCompleteEvent
126
+ )
127
+
128
+
129
+ class AdapterCheckpoint(FrozenModel):
130
+ site: Site
131
+ state: dict[str, Any] = Field(default_factory=dict)
132
+ seen_job_keys: tuple[str, ...] = ()
133
+ emitted_count: int = 0
134
+ completed: bool = False
135
+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
136
+
137
+
138
+ class SearchCheckpoint(FrozenModel):
139
+ version: int = 1
140
+ request_fingerprint: str
141
+ adapters: dict[str, AdapterCheckpoint] = Field(default_factory=dict)
142
+ completed: bool = False
143
+ updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
144
+
145
+ @classmethod
146
+ def for_request(cls, request: SearchRequest) -> SearchCheckpoint:
147
+ return cls(
148
+ request_fingerprint=request.fingerprint(),
149
+ adapters={
150
+ site.value: AdapterCheckpoint(site=site) for site in request.sites
151
+ },
152
+ )