datamarket 0.6.0__py3-none-any.whl → 0.10.3__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.

Potentially problematic release.


This version of datamarket might be problematic. Click here for more details.

Files changed (38) hide show
  1. datamarket/__init__.py +0 -1
  2. datamarket/exceptions/__init__.py +1 -0
  3. datamarket/exceptions/main.py +118 -0
  4. datamarket/interfaces/alchemy.py +1934 -25
  5. datamarket/interfaces/aws.py +81 -14
  6. datamarket/interfaces/azure.py +127 -0
  7. datamarket/interfaces/drive.py +60 -10
  8. datamarket/interfaces/ftp.py +37 -14
  9. datamarket/interfaces/llm.py +1220 -0
  10. datamarket/interfaces/nominatim.py +314 -42
  11. datamarket/interfaces/peerdb.py +272 -104
  12. datamarket/interfaces/proxy.py +354 -50
  13. datamarket/interfaces/tinybird.py +7 -15
  14. datamarket/params/nominatim.py +439 -0
  15. datamarket/utils/__init__.py +1 -1
  16. datamarket/utils/airflow.py +10 -7
  17. datamarket/utils/alchemy.py +2 -1
  18. datamarket/utils/logs.py +88 -0
  19. datamarket/utils/main.py +138 -10
  20. datamarket/utils/nominatim.py +201 -0
  21. datamarket/utils/playwright/__init__.py +0 -0
  22. datamarket/utils/playwright/async_api.py +274 -0
  23. datamarket/utils/playwright/sync_api.py +281 -0
  24. datamarket/utils/requests.py +655 -0
  25. datamarket/utils/selenium.py +6 -12
  26. datamarket/utils/strings/__init__.py +1 -0
  27. datamarket/utils/strings/normalization.py +217 -0
  28. datamarket/utils/strings/obfuscation.py +153 -0
  29. datamarket/utils/strings/standardization.py +40 -0
  30. datamarket/utils/typer.py +2 -1
  31. datamarket/utils/types.py +1 -0
  32. datamarket-0.10.3.dist-info/METADATA +172 -0
  33. datamarket-0.10.3.dist-info/RECORD +38 -0
  34. {datamarket-0.6.0.dist-info → datamarket-0.10.3.dist-info}/WHEEL +1 -2
  35. datamarket-0.6.0.dist-info/METADATA +0 -49
  36. datamarket-0.6.0.dist-info/RECORD +0 -24
  37. datamarket-0.6.0.dist-info/top_level.txt +0 -1
  38. {datamarket-0.6.0.dist-info → datamarket-0.10.3.dist-info/licenses}/LICENSE +0 -0
@@ -0,0 +1,281 @@
1
+ ########################################################################################################################
2
+ # IMPORTS
3
+
4
+ import json
5
+ import logging
6
+ import time
7
+ from datetime import timedelta
8
+ from random import randint
9
+ from types import TracebackType
10
+ from typing import Optional, Self, Sequence
11
+
12
+ from bs4 import BeautifulSoup
13
+ from camoufox import Camoufox
14
+ from playwright.sync_api import Browser, BrowserContext, Page, Response
15
+ from playwright.sync_api import (
16
+ Error as PlaywrightError,
17
+ )
18
+ from playwright.sync_api import (
19
+ TimeoutError as PlaywrightTimeoutError,
20
+ )
21
+ from requests.exceptions import HTTPError, ProxyError
22
+ from tenacity import (
23
+ before_sleep_log,
24
+ retry,
25
+ retry_if_exception_type,
26
+ retry_if_not_exception_type,
27
+ stop_after_attempt,
28
+ stop_after_delay,
29
+ wait_exponential,
30
+ )
31
+
32
+ from datamarket.exceptions import BadRequestError, EmptyResponseError, NotFoundError, RedirectionDetectedError
33
+ from datamarket.exceptions.main import IgnoredHTTPError
34
+ from datamarket.interfaces.proxy import ProxyInterface
35
+ from datamarket.utils.main import ban_sleep
36
+
37
+ ########################################################################################################################
38
+ # SETUP LOGGER
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+
43
+ ########################################################################################################################
44
+ # HELPER FUNCTIONS
45
+
46
+
47
+ def human_type(page: Page, text: str, delay: int = 100):
48
+ for char in text:
49
+ page.keyboard.type(char, delay=randint(int(delay * 0.5), int(delay * 1.5))) # noqa: S311
50
+
51
+
52
+ def human_press_key(page: Page, key: str, count: int = 1, delay: int = 100, add_sleep: bool = True) -> None:
53
+ """Presses a key with a random delay, optionally sleeping between presses."""
54
+ for _ in range(count):
55
+ page.keyboard.press(key, delay=randint(int(delay * 0.5), int(delay * 1.5))) # noqa: S311
56
+ if add_sleep:
57
+ time.sleep(randint(int(delay * 1.5), int(delay * 2.5)) / 1000) # noqa: S311
58
+
59
+
60
+ ########################################################################################################################
61
+ # CLASSES
62
+
63
+
64
+ class PlaywrightCrawler:
65
+ """A robust, proxy-enabled Playwright crawler with captcha bypass and retry logic."""
66
+
67
+ _REDIRECT_STATUS_CODES = set(range(300, 309))
68
+
69
+ def __init__(self, proxy_interface: Optional[ProxyInterface] = None):
70
+ """
71
+ Initializes the crawler.
72
+
73
+ Args:
74
+ proxy_interface (Optional[ProxyInterface], optional): Provider used to fetch
75
+ proxy credentials. Defaults to None. When None, no proxy is configured and
76
+ the browser will run without a proxy.
77
+ """
78
+ self.proxy_interface = proxy_interface
79
+ self.pw: Optional[Camoufox] = None
80
+ self.browser: Optional[Browser] = None
81
+ self.context: Optional[BrowserContext] = None
82
+ self.page: Optional[Page] = None
83
+
84
+ def __enter__(self) -> Self:
85
+ """Initializes the browser context when entering the `with` statement."""
86
+ self.init_context()
87
+ return self
88
+
89
+ def __exit__(
90
+ self,
91
+ exc_type: Optional[type[BaseException]],
92
+ exc_val: Optional[BaseException],
93
+ exc_tb: Optional[TracebackType],
94
+ ) -> None:
95
+ """Safely closes the browser context upon exit."""
96
+ if self.pw:
97
+ try:
98
+ self.pw.__exit__(exc_type, exc_val, exc_tb)
99
+ except Exception as e:
100
+ logger.warning(f"Error closing browser: {e}")
101
+ finally:
102
+ self.pw = None
103
+ self.browser = None
104
+ self.context = None
105
+ self.page = None
106
+
107
+ def _build_proxy_config(self) -> Optional[dict]:
108
+ """Builds the proxy configuration dictionary.
109
+
110
+ Returns:
111
+ Optional[dict]: Proxy configuration if a proxy_interface is provided; otherwise None.
112
+ """
113
+ if not self.proxy_interface:
114
+ logger.info("Starting browser without proxy.")
115
+ return None
116
+
117
+ host, port, user, pwd = self.proxy_interface.get_proxies(raw=True, use_auth=True)
118
+ proxy_url = f"http://{host}:{port}"
119
+ proxy_cfg: dict = {"server": proxy_url}
120
+ if user and pwd:
121
+ proxy_cfg.update({"username": user, "password": pwd})
122
+
123
+ logger.info(f"Starting browser with proxy: {proxy_url}")
124
+ return proxy_cfg
125
+
126
+ @retry(
127
+ wait=wait_exponential(exp_base=2, multiplier=3, max=90),
128
+ stop=stop_after_delay(timedelta(minutes=10)),
129
+ before_sleep=before_sleep_log(logger, logging.INFO),
130
+ reraise=True,
131
+ )
132
+ def init_context(self) -> Self:
133
+ """
134
+ Initializes a new browser instance and context.
135
+
136
+ Behavior:
137
+ - If a proxy_interface is provided, fetches fresh proxy credentials and starts
138
+ the browser using that proxy.
139
+ - If proxy_interface is None, starts the browser without any proxy.
140
+
141
+ Returns:
142
+ Self: The crawler instance with active browser, context, and page.
143
+ """
144
+ try:
145
+ proxy_cfg: Optional[dict] = self._build_proxy_config()
146
+
147
+ self.pw = Camoufox(headless=True, geoip=True, humanize=True, proxy=proxy_cfg)
148
+ self.browser = self.pw.__enter__()
149
+ self.context = self.browser.new_context()
150
+ self.page = self.context.new_page()
151
+ except Exception as e:
152
+ logger.error(f"Failed to initialize browser context: {e}")
153
+ if self.pw:
154
+ self.pw.__exit__(type(e), e, e.__traceback__)
155
+ raise
156
+ return self
157
+
158
+ def restart_context(self) -> None:
159
+ """Closes the current browser instance and initializes a new one."""
160
+ logger.info("Restarting browser context...")
161
+ if self.pw:
162
+ self.pw.__exit__(None, None, None)
163
+ self.init_context()
164
+
165
+ @retry(
166
+ retry=retry_if_exception_type((PlaywrightTimeoutError, PlaywrightError)),
167
+ wait=wait_exponential(exp_base=2, multiplier=3, max=90),
168
+ stop=stop_after_delay(timedelta(minutes=10)),
169
+ before_sleep=before_sleep_log(logger, logging.INFO),
170
+ before=lambda rs: rs.args[0].restart_context() if rs.attempt_number > 1 else None,
171
+ reraise=True,
172
+ )
173
+ def _goto_with_retry(self, url: str, timeout: int = 30_000) -> Response:
174
+ """
175
+ Navigates to a URL with retries for common Playwright errors.
176
+ Restarts the browser context on repeated failures.
177
+ """
178
+ if not (self.page and not self.page.is_closed()):
179
+ logger.warning("Page is not available or closed. Restarting context.")
180
+ self.restart_context()
181
+
182
+ response = self.page.goto(url, timeout=timeout, wait_until="domcontentloaded")
183
+ return response
184
+
185
+ def goto(self, url: str, max_proxy_delay: timedelta = timedelta(minutes=10), timeout: int = 30_000) -> Response:
186
+ """
187
+ Ensures the browser is initialized and navigates to the given URL.
188
+ Public wrapper for the internal retry-enabled navigation method.
189
+ """
190
+ if not self.page:
191
+ logger.info("Browser context not found, initializing now...")
192
+ self.init_context()
193
+ return self._goto_with_retry.retry_with(stop=stop_after_delay(max_proxy_delay))(self, url, timeout)
194
+
195
+ def _handle_http_error(self, status_code: int, url: str, response, allow_redirects: bool = True) -> None:
196
+ """
197
+ Handle HTTP errors with special handling for redirects.
198
+
199
+ Args:
200
+ status_code: HTTP status code
201
+ url: Request URL
202
+ response: Response object
203
+
204
+ Raises:
205
+ RedirectionDetectedError: If a redirect status is received
206
+ NotFoundError: For 404/410 errors
207
+ BadRequestError: For 400 errors
208
+ HTTPError: For other non-2xx status codes
209
+ """
210
+
211
+ if not allow_redirects and response.request.redirected_from: # noqa: F841
212
+ raise RedirectionDetectedError(
213
+ message=f"HTTP redirect detected from {response.request.redirected_from.url} to {response.request.redirected_from.redirected_to.url}",
214
+ response=response,
215
+ )
216
+
217
+ # Standard error handlers
218
+ error_handlers = {
219
+ 404: lambda: NotFoundError(message=f"404 Not Found error for {url}", response=response),
220
+ 410: lambda: NotFoundError(message=f"410 Gone error for {url}", response=response),
221
+ 400: lambda: BadRequestError(message=f"400 Bad Request error for {url}", response=response),
222
+ }
223
+
224
+ if status_code in error_handlers:
225
+ raise error_handlers[status_code]()
226
+
227
+ # Raise for any other non-2xx status
228
+ if status_code >= 400:
229
+ raise HTTPError(f"Navigation failed: {status_code} - {url}", response=response)
230
+
231
+ @retry(
232
+ retry=retry_if_not_exception_type(
233
+ (IgnoredHTTPError, NotFoundError, BadRequestError, RedirectionDetectedError, ProxyError)
234
+ ),
235
+ wait=wait_exponential(exp_base=3, multiplier=3, max=60),
236
+ stop=stop_after_attempt(5),
237
+ before_sleep=before_sleep_log(logger, logging.WARNING),
238
+ reraise=False,
239
+ retry_error_callback=lambda rs: None,
240
+ )
241
+ def get_data(
242
+ self,
243
+ url: str,
244
+ output: str = "json",
245
+ sleep: tuple = (6, 3),
246
+ max_proxy_delay: timedelta = timedelta(minutes=10),
247
+ ignored_status_codes: Sequence[int] = (),
248
+ timeout: int = 30_000,
249
+ **kwargs,
250
+ ):
251
+ """Crawls a given URL using Playwright and attempts to parse its body content"""
252
+
253
+ params = kwargs.copy()
254
+
255
+ allow_redirects = params.get("allow_redirects", True)
256
+
257
+ logger.info(f"Fetching data from {url} ...")
258
+ r = self.goto(url, max_proxy_delay, timeout)
259
+ ban_sleep(*sleep)
260
+ body_content = self.page.eval_on_selector("body", "body => body.innerText")
261
+
262
+ if r.status in ignored_status_codes:
263
+ raise IgnoredHTTPError(message=f"Status {r.status} in ignored_status_codes for URL {url}", response=r)
264
+
265
+ # Handle HTTP errors with redirect detection
266
+ self._handle_http_error(r.status, url, r, allow_redirects)
267
+
268
+ if not body_content:
269
+ raise EmptyResponseError(message=f"Empty body received from {url} (status {r.status})", response=r)
270
+
271
+ output_format = {
272
+ "json": lambda: json.loads(body_content),
273
+ "text": lambda: body_content,
274
+ "soup": lambda: BeautifulSoup(body_content, "html.parser"),
275
+ "response": lambda: r,
276
+ }
277
+
278
+ if output in output_format:
279
+ return output_format[output]()
280
+
281
+ raise ValueError(f"Unsupported output format: {output}")