@jayyuen66/dsh-scrapling 0.1.16 → 0.1.17

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.
package/py/bridge.py CHANGED
@@ -7,6 +7,9 @@
7
7
  协议(Host -> Python,每行一个 JSON 对象)::
8
8
 
9
9
  {"id": "7", "method": "fetch", "params": {...}}
10
+ {"id": "cancel-7", "method": "cancel", "params": {"id": "7"}}
11
+
12
+ 取消只设置请求 token;适配器在抓取、读取与动作的安全边界检查,不强行中断阻塞调用。
10
13
 
11
14
  响应(Python -> Host,同样一行一个)::
12
15
 
@@ -35,6 +38,7 @@
35
38
 
36
39
  from __future__ import annotations
37
40
 
41
+ import contextlib
38
42
  import json
39
43
  import os
40
44
  import sys
@@ -42,7 +46,10 @@ import threading
42
46
  import time
43
47
  import traceback
44
48
  from io import BufferedReader
45
- from typing import Any, Callable, cast
49
+ from typing import TYPE_CHECKING, Any, Callable, cast
50
+
51
+ if TYPE_CHECKING:
52
+ from cancellation import CancellationToken
46
53
 
47
54
  # 协议帧与日志一律 UTF-8:宿主按 UTF-8 解码本进程的 stdout/stderr,而两者都是管道。
48
55
  # 管道在 Windows 上默认走本地 ANSI 代码页;`LC_ALL=C` 配上 `PYTHONUTF8=0` 这类环境
@@ -157,6 +164,8 @@ _QUEUE: list[dict[str, Any]] = []
157
164
  _QUEUE_LOCK = threading.Lock()
158
165
  _WORKERS_LOCK = threading.Lock()
159
166
  _WORKERS: list[threading.Thread] = []
167
+ _REQUEST_TOKENS_LOCK = threading.Lock()
168
+ _REQUEST_TOKENS: dict[str, CancellationToken] = {}
160
169
 
161
170
 
162
171
  def log(message: str) -> None:
@@ -200,6 +209,41 @@ def fail(request_id: Any, code: str, message: str, details: dict[str, Any] | Non
200
209
  return {"id": request_id, "ok": False, "error": error}
201
210
 
202
211
 
212
+ def _register_request(request_id: Any) -> CancellationToken | None:
213
+ """为已接收的请求登记 token;排队项也登记,出队后先检查再执行。"""
214
+ from cancellation import CancellationToken
215
+
216
+ if not isinstance(request_id, str):
217
+ return None
218
+ with _REQUEST_TOKENS_LOCK:
219
+ token = _REQUEST_TOKENS.get(request_id)
220
+ if token is None:
221
+ token = CancellationToken()
222
+ _REQUEST_TOKENS[request_id] = token
223
+ return token
224
+
225
+
226
+ def _release_request(request_id: Any, token: CancellationToken | None) -> None:
227
+ """只摘自己这一笔,避免延迟完成或重复 id 误删后来登记的 token。"""
228
+ if token is None or not isinstance(request_id, str):
229
+ return
230
+ with _REQUEST_TOKENS_LOCK:
231
+ if _REQUEST_TOKENS.get(request_id) is token:
232
+ _REQUEST_TOKENS.pop(request_id, None)
233
+
234
+
235
+ def _cancel_request(request_id: Any) -> bool:
236
+ """设置运行中或排队请求的取消事件;未知、已完成 id 都是 no-op。"""
237
+ if not isinstance(request_id, str):
238
+ return False
239
+ with _REQUEST_TOKENS_LOCK:
240
+ token = _REQUEST_TOKENS.get(request_id)
241
+ if token is None:
242
+ return False
243
+ token.cancel()
244
+ return True
245
+
246
+
203
247
  # scrapling 的可选 extra(fetchers / rag)会按需导入这些包;只有它们缺失才算
204
248
  # 「环境没装对」。其它 ModuleNotFoundError 是本插件自己的导入缺陷,不能包装成
205
249
  # 安装提示——用户照提示装完仍然会失败。
@@ -220,12 +264,26 @@ OPTIONAL_DEPENDENCIES = frozenset(
220
264
 
221
265
 
222
266
  def handle(frame: dict[str, Any]) -> dict[str, Any]:
223
- """分发一个请求帧。
267
+ """分发一个请求帧,并把取消 token 绑定到这一次 handler 调用。"""
268
+ from cancellation import RequestCancelled, bind, raise_if_cancelled
224
269
 
225
- :param frame - 已解析的请求帧
226
- :returns: 响应帧
227
- """
270
+ request_id = frame.get("id")
271
+ token = _register_request(request_id)
272
+ try:
273
+ with bind(token) if token is not None else contextlib.nullcontext():
274
+ try:
275
+ raise_if_cancelled()
276
+ return _handle_request(frame)
277
+ except RequestCancelled:
278
+ return fail(request_id, "SIDECAR_ABORTED", f"{frame.get('method')} was cancelled")
279
+ finally:
280
+ _release_request(request_id, token)
281
+
282
+
283
+ def _handle_request(frame: dict[str, Any]) -> dict[str, Any]:
284
+ """校验并执行一个已绑定取消上下文的请求。"""
228
285
  import adapters
286
+ from cancellation import RequestCancelled, raise_if_cancelled
229
287
 
230
288
  request_id = frame.get("id")
231
289
  method = frame.get("method")
@@ -243,7 +301,11 @@ def handle(frame: dict[str, Any]) -> dict[str, Any]:
243
301
 
244
302
  with _SLOTS:
245
303
  try:
304
+ # 等待并发名额期间也可能收到 cancel;拿到名额后再判一次。
305
+ raise_if_cancelled()
246
306
  return ok(request_id, handler(params))
307
+ except RequestCancelled:
308
+ raise
247
309
  except adapters.AdapterError as error:
248
310
  return fail(request_id, error.code, str(error), error.details)
249
311
  except ModuleNotFoundError as error:
@@ -482,6 +544,15 @@ def read_loop() -> int:
482
544
  if not isinstance(frame, dict):
483
545
  emit(fail(None, "BAD_FRAME", "frame must be an object"))
484
546
  return True
547
+ if frame.get("method") == "cancel":
548
+ params = frame.get("params")
549
+ target = params.get("id") if isinstance(params, dict) else None
550
+ if not isinstance(target, str) or not target:
551
+ emit(fail(frame.get("id"), "BAD_ARGS", "cancel requires a non-empty string id"))
552
+ return True
553
+ _cancel_request(target)
554
+ emit(ok(frame.get("id"), {"cancelled": True}))
555
+ return True
485
556
  if frame.get("method") == "shutdown":
486
557
  emit(ok(frame.get("id"), {"stopping": True}))
487
558
  _drain_before_exit()
@@ -502,6 +573,7 @@ def read_loop() -> int:
502
573
  f"{depth} requests already queued (limit {MAX_QUEUE_DEPTH})",
503
574
  )
504
575
  else:
576
+ _register_request(frame.get("id"))
505
577
  _QUEUE.append(frame)
506
578
  depth += 1
507
579
  if busy_reply is not None:
@@ -0,0 +1,56 @@
1
+ """逐请求取消 token;只在调用方明确设置的安全阶段边界生效。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from contextlib import contextmanager
6
+ from contextvars import ContextVar
7
+ from threading import Event
8
+ from typing import Iterator
9
+
10
+
11
+ class RequestCancelled(RuntimeError):
12
+ """当前请求已被取消;bridge 负责把它映射成协议错误码。"""
13
+
14
+
15
+ class CancellationToken:
16
+ """可跨线程设置的请求级取消事件。"""
17
+
18
+ def __init__(self) -> None:
19
+ self._event = Event()
20
+
21
+ @property
22
+ def cancelled(self) -> bool:
23
+ """是否已经收到取消。"""
24
+ return self._event.is_set()
25
+
26
+ def cancel(self) -> None:
27
+ """设置取消事件;重复调用没有副作用。"""
28
+ self._event.set()
29
+
30
+
31
+ _CURRENT_TOKEN: ContextVar[CancellationToken | None] = ContextVar(
32
+ "dsh_scrapling_cancellation",
33
+ default=None,
34
+ )
35
+
36
+
37
+ def current_token() -> CancellationToken | None:
38
+ """返回当前请求绑定的 token;没有请求上下文时为 None。"""
39
+ return _CURRENT_TOKEN.get()
40
+
41
+
42
+ @contextmanager
43
+ def bind(token: CancellationToken) -> Iterator[None]:
44
+ """把 token 绑定到当前线程与异步上下文,并在退出时恢复上一层。"""
45
+ previous = _CURRENT_TOKEN.set(token)
46
+ try:
47
+ yield
48
+ finally:
49
+ _CURRENT_TOKEN.reset(previous)
50
+
51
+
52
+ def raise_if_cancelled() -> None:
53
+ """在安全阶段边界检查取消;不试图中断阻塞中的第三方调用。"""
54
+ token = current_token()
55
+ if token is not None and token.cancelled:
56
+ raise RequestCancelled("request was cancelled")
package/py/document.py ADDED
@@ -0,0 +1,128 @@
1
+ """PDF 文本读取:流式下载到临时文件,再用可选 pypdf 逐页抽取。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from cancellation import raise_if_cancelled
10
+
11
+ DEFAULT_MAX_BYTES = 20 * 1024 * 1024
12
+ DEFAULT_MAX_PAGES = 200
13
+ DEFAULT_MAX_OUTPUT_CHARS = 200_000
14
+ PYPDF_VERSION = "7.1.1"
15
+
16
+
17
+ def available() -> bool:
18
+ """pypdf 是否可导入;缺包不影响 sidecar 启动。"""
19
+ try:
20
+ from pypdf import PdfReader
21
+ except ImportError:
22
+ return False
23
+ return callable(PdfReader)
24
+
25
+
26
+ def _error(code: str, message: str) -> Exception:
27
+ from adapters import AdapterError
28
+
29
+ return AdapterError(code, message)
30
+
31
+
32
+ def _positive(value: Any, field: str, default: int) -> int:
33
+ from adapters import _positive_int
34
+
35
+ return _positive_int(value, field, default)
36
+
37
+
38
+ def _limits(args: dict[str, Any]) -> tuple[int, int, int]:
39
+ """模型上限只能向下收,部署缺省值就是任务约定的三档。"""
40
+ deployment = args.get("deployment")
41
+ if deployment is None:
42
+ deployment = {}
43
+ if not isinstance(deployment, dict):
44
+ raise _error("BAD_ARGS", "deployment must be an object")
45
+ byte_ceiling = _positive(deployment.get("documentMaxBytes"), "deployment.documentMaxBytes", DEFAULT_MAX_BYTES)
46
+ page_ceiling = _positive(deployment.get("documentMaxPages"), "deployment.documentMaxPages", DEFAULT_MAX_PAGES)
47
+ output_ceiling = _positive(
48
+ deployment.get("documentMaxOutputChars"),
49
+ "deployment.documentMaxOutputChars",
50
+ DEFAULT_MAX_OUTPUT_CHARS,
51
+ )
52
+ requested_bytes = _positive(args.get("maxBytes"), "maxBytes", byte_ceiling)
53
+ requested_pages = _positive(args.get("maxPages"), "maxPages", page_ceiling)
54
+ requested_output = _positive(args.get("maxOutputChars"), "maxOutputChars", output_ceiling)
55
+ return min(requested_bytes, byte_ceiling), min(requested_pages, page_ceiling), min(requested_output, output_ceiling)
56
+
57
+
58
+ def read(args: dict[str, Any]) -> dict[str, Any]:
59
+ """读一个 HTTP(S) PDF,返回页数、文本与截断标记。"""
60
+ import guard
61
+ import media
62
+ from adapters import AdapterError, _positive_number, _string_map, _url, clip
63
+
64
+ if not available():
65
+ raise _error(
66
+ "DEPENDENCY_MISSING",
67
+ f"pypdf {PYPDF_VERSION} is not installed; run dsh-scrapling setup --feature documents --apply",
68
+ )
69
+ url = _url(args)
70
+ allowed, reason = guard.url_allowed(url)
71
+ if not allowed:
72
+ raise _error("URL_BLOCKED", f"{url}: {reason}")
73
+ max_bytes, max_pages, max_output_chars = _limits(args)
74
+ headers = _string_map(args.get("headers"), "headers")
75
+ cookies = _string_map(args.get("cookies"), "cookies")
76
+ timeout = _positive_number(args.get("timeoutSeconds"), "timeoutSeconds", 120.0)
77
+ impersonate = args.get("impersonate")
78
+ if not isinstance(impersonate, str) or not impersonate:
79
+ impersonate = "chrome"
80
+
81
+ # TemporaryDirectory 包住整个读取过程:头部预检、流式超限、解析失败与加密/扫描
82
+ # 分支都走同一个 finally,不把远端 PDF 留在用户目录或系统临时目录里。
83
+ with tempfile.TemporaryDirectory(prefix="dsh-scrapling-document-") as temporary:
84
+ downloaded = media._download_via_stream(
85
+ url,
86
+ name="document.pdf",
87
+ directory=Path(temporary),
88
+ limit=max_bytes,
89
+ timeout=timeout,
90
+ headers=headers,
91
+ cookies=cookies,
92
+ impersonate=impersonate,
93
+ too_large_code="PDF_TOO_LARGE",
94
+ )
95
+ try:
96
+ from pypdf import PdfReader
97
+ except ImportError as error:
98
+ raise _error("DEPENDENCY_MISSING", f"pypdf {PYPDF_VERSION} is not installed") from error
99
+ try:
100
+ reader = PdfReader(downloaded["path"])
101
+ if reader.is_encrypted:
102
+ raise _error("PDF_ENCRYPTED", "encrypted PDFs are not supported; provide an unencrypted copy")
103
+ page_count = len(reader.pages)
104
+ if page_count > max_pages:
105
+ raise _error(
106
+ "PDF_TOO_LARGE",
107
+ f"PDF has {page_count} pages, over the {max_pages}-page cap",
108
+ )
109
+ texts: list[str] = []
110
+ for index in range(page_count):
111
+ raise_if_cancelled()
112
+ texts.append(reader.pages[index].extract_text() or "")
113
+ if not any(text.strip() for text in texts):
114
+ raise _error("PDF_SCANNED", "PDF has no extractable text; scanned pages need OCR")
115
+ content = "\n\n".join(f"--- Page {index + 1} ---\n{text.strip()}" for index, text in enumerate(texts))
116
+ except AdapterError:
117
+ raise
118
+ except Exception as error:
119
+ raise _error("FETCH_FAILED", f"could not read PDF: {type(error).__name__}: {error}") from error
120
+ content, truncated = clip(content, max_output_chars)
121
+ return {
122
+ "url": url,
123
+ "bytes": downloaded["bytes"],
124
+ "pageCount": page_count,
125
+ "pagesRead": page_count,
126
+ "content": content,
127
+ "truncated": truncated,
128
+ }
@@ -0,0 +1 @@
1
+ pypdf==7.1.1 --hash=sha256:04c5680d4b4cfa04ab505b09393fc949860c34a4dad6565284d11a2f5c3ce8b1
package/py/media.py CHANGED
@@ -177,6 +177,7 @@ def _download_via_stream(
177
177
  headers: dict[str, str] | None,
178
178
  cookies: dict[str, str] | None,
179
179
  impersonate: str,
180
+ too_large_code: str = "DOWNLOAD_TOO_LARGE",
180
181
  ) -> dict[str, Any]:
181
182
  """流式下载:逐块落盘并计哈希,内存占用与块同阶,与响应体大小无关。
182
183
 
@@ -220,7 +221,7 @@ def _download_via_stream(
220
221
  # 头部预检在正文传输之前给出结论;谎报长度的服务端由流式循环里的复核兜住。
221
222
  if declared.isdigit() and int(declared) > limit:
222
223
  raise _error(
223
- "DOWNLOAD_TOO_LARGE",
224
+ too_large_code,
224
225
  f"download is {int(declared)} bytes by Content-Length, over the {limit}-byte cap",
225
226
  )
226
227
  digest = hashlib.sha256()
@@ -232,7 +233,7 @@ def _download_via_stream(
232
233
  # 先判后写:写盘再判会让写到磁盘字节超过上限最多一个块(64 KiB)。
233
234
  if total + len(chunk) > limit:
234
235
  raise _error(
235
- "DOWNLOAD_TOO_LARGE",
236
+ too_large_code,
236
237
  f"download is over the {limit}-byte cap"
237
238
  + (f" (Content-Length declared {int(declared)})" if declared.isdigit() else ""),
238
239
  )
@@ -1,3 +1,4 @@
1
+ # Optional PDF support is pinned separately in documents-requirements.txt.
1
2
  annotated-types==0.8.0 --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0
2
3
  anyio==4.15.1 --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101
3
4
  apify_fingerprint_datapoints==0.15.0 --hash=sha256:fc9299b3136880f47b468897cd00ac622ad2c2a93e9cc9f972d10dbf5ed2b3aa
package/py/search.py CHANGED
@@ -7,7 +7,14 @@ search provider 交给本 sidecar 的 fetch/render。每条后端都按各家**
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
- from typing import Any
10
+ import base64
11
+ import binascii
12
+ import re
13
+ from typing import Any, cast
14
+ from urllib.parse import parse_qs, urlparse
15
+
16
+ import guard
17
+ from curl_cffi.requests import ProxySpec
11
18
 
12
19
  DEFAULT_TAVILY_ENDPOINT = "https://api.tavily.com/search"
13
20
  DEFAULT_BING_ENDPOINT = "https://www.bing.com/search"
@@ -27,6 +34,11 @@ TAVILY_MAX_RESULTS = 20
27
34
  # `3 × timeout + 2s`,比协议层先到期的超时还长 —— 于是 SEARCH_TIMEOUT 永远走不到,
28
35
  # 模型看到的是一条含义更模糊的协议层超时。显式传 1 让两层的预算对齐。
29
36
  SEARCH_RETRIES = 1
37
+ _CJK_QUERY = re.compile(r"[\u3400-\u9fff]")
38
+
39
+
40
+ def _proxies(url: str) -> "ProxySpec | None":
41
+ return cast("ProxySpec | None", guard.proxies_for(url))
30
42
 
31
43
 
32
44
  class SearchError(ValueError):
@@ -45,6 +57,14 @@ def _positive_int(value: Any, field: str, default: int) -> int:
45
57
  return value
46
58
 
47
59
 
60
+ def _offset(value: Any) -> int:
61
+ if value is None:
62
+ return 0
63
+ if not isinstance(value, int) or isinstance(value, bool) or value < 0:
64
+ raise SearchError("BAD_ARGS", "offset must be a non-negative integer")
65
+ return value
66
+
67
+
48
68
  def _timeout(value: Any) -> float:
49
69
  if value is None:
50
70
  return DEFAULT_SEARCH_TIMEOUT_SECONDS
@@ -83,7 +103,7 @@ def _status_error(status: int, backend: str) -> SearchError | None:
83
103
  return None
84
104
 
85
105
 
86
- def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
106
+ def _tavily(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
87
107
  key = args.get("apiKey")
88
108
  if not isinstance(key, str) or not key:
89
109
  raise SearchError(
@@ -99,11 +119,12 @@ def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
99
119
  json={
100
120
  "api_key": key,
101
121
  "query": query,
102
- "max_results": min(limit, TAVILY_MAX_RESULTS),
122
+ "max_results": min(limit + offset, TAVILY_MAX_RESULTS),
103
123
  "search_depth": "basic",
104
124
  },
105
125
  timeout=timeout,
106
126
  retries=SEARCH_RETRIES,
127
+ proxies=_proxies(endpoint),
107
128
  )
108
129
  except Exception as error: # noqa: BLE001 —— 只翻译成带码的失败,不回显请求体
109
130
  raise _translate(error, "tavily") from None
@@ -115,20 +136,58 @@ def _tavily(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
115
136
  # 而非对象回包已经在 _json_body 那里判成 SEARCH_FAILED 了。
116
137
  hits = _collect(
117
138
  payload.get("results"),
118
- limit=limit,
139
+ limit=limit + offset,
119
140
  url_key="url",
120
141
  title_key="title",
121
142
  snippet_key="content",
143
+ summary_key="summary",
144
+ date_key="published_date",
122
145
  )
123
- return {"backend": "tavily", "hits": hits}
146
+ return {"backend": "tavily", "hits": hits[offset : offset + limit]}
124
147
 
125
148
 
126
- def _bing(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
149
+ def _bing_target(href: str) -> str:
150
+ """解包 Bing 的 ck/a 跳板;只接受 Bing 自家主机与 http(s) 目标。"""
151
+ parts = urlparse(href)
152
+ host = (parts.hostname or "").lower()
153
+ if not (host == "bing.com" or host.endswith(".bing.com")) or parts.path != "/ck/a":
154
+ return href
155
+ token = parse_qs(parts.query).get("u", [""])[0]
156
+ if not token.startswith("a1"):
157
+ return href
158
+ encoded = token[2:]
159
+ try:
160
+ target = base64.b64decode(
161
+ encoded + "=" * (-len(encoded) % 4),
162
+ altchars=b"-_",
163
+ validate=True,
164
+ ).decode("utf-8")
165
+ except ValueError, binascii.Error, UnicodeDecodeError:
166
+ return href
167
+ parsed = urlparse(target)
168
+ if parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.username or parsed.password:
169
+ return href
170
+ return target
171
+
172
+
173
+ def _bing(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
127
174
  endpoint = _endpoint(args.get("bingEndpoint"), DEFAULT_BING_ENDPOINT, "bingEndpoint")
128
175
  from scrapling.fetchers import Fetcher
129
176
 
177
+ params = {
178
+ "q": query,
179
+ "first": offset + 1,
180
+ "count": limit,
181
+ "setlang": "zh-hans" if _CJK_QUERY.search(query) else "en",
182
+ }
130
183
  try:
131
- response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout, retries=SEARCH_RETRIES)
184
+ response = Fetcher.get(
185
+ endpoint,
186
+ params=params,
187
+ timeout=timeout,
188
+ retries=SEARCH_RETRIES,
189
+ proxies=_proxies(endpoint),
190
+ )
132
191
  except Exception as error: # noqa: BLE001
133
192
  raise _translate(error, "bing") from None
134
193
  failed = _status_error(int(getattr(response, "status", 0)), "bing")
@@ -149,7 +208,7 @@ def _bing(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[
149
208
  snippet_node = node.css(".b_caption p").first or node.css("p").first
150
209
  hits.append(
151
210
  {
152
- "url": href,
211
+ "url": _bing_target(href),
153
212
  "title": link.get_all_text(strip=True),
154
213
  "snippet": snippet_node.get_all_text(strip=True) if snippet_node is not None else "",
155
214
  }
@@ -191,9 +250,11 @@ def _collect(
191
250
  url_key: str,
192
251
  title_key: str,
193
252
  snippet_key: str,
194
- ) -> list[dict[str, str]]:
195
- """把各家形状不同的结果表收成同一份 hits(url/title/snippet)。"""
196
- hits: list[dict[str, str]] = []
253
+ summary_key: str | None = None,
254
+ date_key: str | None = None,
255
+ ) -> list[dict[str, Any]]:
256
+ """把各家形状不同的结果表收成同一份 hits。"""
257
+ hits: list[dict[str, Any]] = []
197
258
  if not isinstance(items, list):
198
259
  return hits
199
260
  for item in items:
@@ -204,11 +265,15 @@ def _collect(
204
265
  continue
205
266
  title = item.get(title_key)
206
267
  snippet = item.get(snippet_key)
268
+ summary = item.get(summary_key) if summary_key is not None else None
269
+ published = item.get(date_key) if date_key is not None else None
207
270
  hits.append(
208
271
  {
209
272
  "url": url,
210
273
  "title": title if isinstance(title, str) else "",
211
274
  "snippet": snippet if isinstance(snippet, str) else "",
275
+ **({"summary": summary} if isinstance(summary, str) and summary else {}),
276
+ **({"publishedAt": published} if isinstance(published, str) and published else {}),
212
277
  }
213
278
  )
214
279
  if len(hits) >= limit:
@@ -226,7 +291,7 @@ def _nested(payload: dict[str, Any], *keys: str) -> Any:
226
291
  return current
227
292
 
228
293
 
229
- def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
294
+ def _brave(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
230
295
  key = _require_key(args, "brave")
231
296
  endpoint = _endpoint(args.get("braveEndpoint"), DEFAULT_BRAVE_ENDPOINT, "braveEndpoint")
232
297
  from scrapling.fetchers import Fetcher
@@ -236,10 +301,11 @@ def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict
236
301
  try:
237
302
  response = Fetcher.get(
238
303
  endpoint,
239
- params={"q": query, "count": min(limit, BRAVE_MAX_COUNT)},
304
+ params={"q": query, "count": min(limit, BRAVE_MAX_COUNT), "offset": offset},
240
305
  headers={"X-Subscription-Token": key, "Accept": "application/json"},
241
306
  timeout=timeout,
242
307
  retries=SEARCH_RETRIES,
308
+ proxies=_proxies(endpoint),
243
309
  )
244
310
  except Exception as error: # noqa: BLE001
245
311
  raise _translate(error, "brave") from None
@@ -257,18 +323,21 @@ def _brave(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict
257
323
  return {"backend": "brave", "hits": hits}
258
324
 
259
325
 
260
- def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
326
+ def _serper(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
261
327
  key = _require_key(args, "serper")
262
328
  endpoint = _endpoint(args.get("serperEndpoint"), DEFAULT_SERPER_ENDPOINT, "serperEndpoint")
263
329
  from scrapling.fetchers import Fetcher
264
330
 
331
+ page = offset // limit + 1
332
+ skip = offset % limit
265
333
  try:
266
334
  response = Fetcher.post(
267
335
  endpoint,
268
- json={"q": query, "num": limit},
336
+ json={"q": query, "num": limit + skip, "page": page},
269
337
  headers={"X-API-KEY": key, "Content-Type": "application/json"},
270
338
  timeout=timeout,
271
339
  retries=SEARCH_RETRIES,
340
+ proxies=_proxies(endpoint),
272
341
  )
273
342
  except Exception as error: # noqa: BLE001
274
343
  raise _translate(error, "serper") from None
@@ -278,12 +347,13 @@ def _serper(args: dict[str, Any], query: str, limit: int, timeout: float) -> dic
278
347
  payload = _json_body(response, "serper")
279
348
  hits = _collect(
280
349
  payload.get("organic"),
281
- limit=limit,
350
+ limit=limit + skip,
282
351
  url_key="link",
283
352
  title_key="title",
284
353
  snippet_key="snippet",
354
+ date_key="date",
285
355
  )
286
- return {"backend": "serper", "hits": hits}
356
+ return {"backend": "serper", "hits": hits[skip : skip + limit]}
287
357
 
288
358
 
289
359
  def _duckduckgo_target(href: str) -> str:
@@ -305,12 +375,18 @@ def _duckduckgo_target(href: str) -> str:
305
375
  return urlunparse(parts)
306
376
 
307
377
 
308
- def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
378
+ def _duckduckgo(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
309
379
  endpoint = _endpoint(args.get("duckduckgoEndpoint"), DEFAULT_DUCKDUCKGO_ENDPOINT, "duckduckgoEndpoint")
310
380
  from scrapling.fetchers import Fetcher
311
381
 
312
382
  try:
313
- response = Fetcher.get(endpoint, params={"q": query}, timeout=timeout, retries=SEARCH_RETRIES)
383
+ response = Fetcher.get(
384
+ endpoint,
385
+ params={"q": query, "s": offset},
386
+ timeout=timeout,
387
+ retries=SEARCH_RETRIES,
388
+ proxies=_proxies(endpoint),
389
+ )
314
390
  except Exception as error: # noqa: BLE001
315
391
  raise _translate(error, "duckduckgo") from None
316
392
  failed = _status_error(int(getattr(response, "status", 0)), "duckduckgo")
@@ -344,7 +420,7 @@ def _duckduckgo(args: dict[str, Any], query: str, limit: int, timeout: float) ->
344
420
  return result
345
421
 
346
422
 
347
- def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> dict[str, Any]:
423
+ def _searxng(args: dict[str, Any], query: str, limit: int, offset: int, timeout: float) -> dict[str, Any]:
348
424
  endpoint = args.get("searxngEndpoint")
349
425
  if not isinstance(endpoint, str) or not endpoint:
350
426
  raise SearchError(
@@ -356,7 +432,13 @@ def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> di
356
432
  from scrapling.fetchers import Fetcher
357
433
 
358
434
  try:
359
- response = Fetcher.get(url, params={"q": query, "format": "json"}, timeout=timeout, retries=SEARCH_RETRIES)
435
+ response = Fetcher.get(
436
+ url,
437
+ params={"q": query, "format": "json", "pageno": offset // limit + 1},
438
+ timeout=timeout,
439
+ retries=SEARCH_RETRIES,
440
+ proxies=_proxies(url),
441
+ )
360
442
  except Exception as error: # noqa: BLE001
361
443
  raise _translate(error, "searxng") from None
362
444
  failed = _status_error(int(getattr(response, "status", 0)), "searxng")
@@ -369,6 +451,7 @@ def _searxng(args: dict[str, Any], query: str, limit: int, timeout: float) -> di
369
451
  url_key="url",
370
452
  title_key="title",
371
453
  snippet_key="content",
454
+ date_key="publishedDate",
372
455
  )
373
456
  return {"backend": "searxng", "hits": hits}
374
457
 
@@ -390,6 +473,7 @@ def discover(args: dict[str, Any]) -> dict[str, Any]:
390
473
  if not isinstance(query, str) or not query.strip():
391
474
  raise SearchError("BAD_ARGS", "query must be a non-empty string")
392
475
  limit = _positive_int(args.get("maxResults"), "maxResults", DEFAULT_SEARCH_RESULTS)
476
+ offset = _offset(args.get("offset"))
393
477
  timeout = _timeout(args.get("timeoutSeconds"))
394
478
  key = args.get("apiKey")
395
479
  resolved = backend
@@ -420,4 +504,4 @@ def discover(args: dict[str, Any]) -> dict[str, Any]:
420
504
  "duckduckgo": _duckduckgo,
421
505
  "searxng": _searxng,
422
506
  }
423
- return handlers[resolved](args, query.strip(), limit, timeout)
507
+ return handlers[resolved](args, query.strip(), limit, offset, timeout)