webscout 6.8__py3-none-any.whl → 7.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.

Potentially problematic release.


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

Files changed (45) hide show
  1. webscout/AIbase.py +12 -2
  2. webscout/DWEBS.py +38 -22
  3. webscout/Extra/YTToolkit/YTdownloader.py +7 -2
  4. webscout/Extra/YTToolkit/ytapi/channel.py +1 -1
  5. webscout/Extra/YTToolkit/ytapi/query.py +3 -0
  6. webscout/Extra/YTToolkit/ytapi/stream.py +3 -0
  7. webscout/Extra/YTToolkit/ytapi/video.py +3 -1
  8. webscout/Extra/autocoder/autocoder_utiles.py +68 -7
  9. webscout/Extra/autollama.py +0 -16
  10. webscout/Extra/gguf.py +0 -13
  11. webscout/Provider/AISEARCH/DeepFind.py +251 -0
  12. webscout/Provider/AISEARCH/__init__.py +2 -2
  13. webscout/Provider/AISEARCH/felo_search.py +167 -118
  14. webscout/Provider/Blackboxai.py +1 -1
  15. webscout/Provider/Glider.py +207 -0
  16. webscout/Provider/HF_space/__init__.py +0 -0
  17. webscout/Provider/HF_space/qwen_qwen2.py +206 -0
  18. webscout/Provider/TextPollinationsAI.py +201 -0
  19. webscout/Provider/Youchat.py +28 -22
  20. webscout/Provider/__init__.py +11 -3
  21. webscout/Provider/askmyai.py +2 -2
  22. webscout/Provider/cerebras.py +3 -3
  23. webscout/Provider/chatglm.py +205 -0
  24. webscout/Provider/dgaf.py +186 -0
  25. webscout/Provider/hermes.py +219 -0
  26. webscout/Provider/llmchat.py +1 -0
  27. webscout/__init__.py +0 -1
  28. webscout/litagent/__init__.py +3 -146
  29. webscout/litagent/agent.py +120 -0
  30. webscout/litagent/constants.py +31 -0
  31. webscout/swiftcli/__init__.py +1 -0
  32. webscout/tempid.py +0 -4
  33. webscout/version.py +1 -1
  34. webscout/webscout_search.py +1140 -1104
  35. webscout/webscout_search_async.py +635 -361
  36. {webscout-6.8.dist-info → webscout-7.0.dist-info}/METADATA +23 -39
  37. {webscout-6.8.dist-info → webscout-7.0.dist-info}/RECORD +41 -35
  38. {webscout-6.8.dist-info → webscout-7.0.dist-info}/WHEEL +1 -1
  39. webscout/Extra/markdownlite/__init__.py +0 -862
  40. webscout/Provider/AISEARCH/ooai.py +0 -155
  41. webscout/Provider/Deepseek.py +0 -227
  42. webscout/zerodir/__init__.py +0 -225
  43. {webscout-6.8.dist-info → webscout-7.0.dist-info}/LICENSE.md +0 -0
  44. {webscout-6.8.dist-info → webscout-7.0.dist-info}/entry_points.txt +0 -0
  45. {webscout-6.8.dist-info → webscout-7.0.dist-info}/top_level.txt +0 -0
@@ -1,1105 +1,1141 @@
1
- from __future__ import annotations
2
-
3
- # import logging
4
- import warnings
5
- from concurrent.futures import ThreadPoolExecutor
6
- from datetime import datetime, timezone
7
- from decimal import Decimal
8
- from functools import cached_property
9
- from itertools import cycle, islice
10
- from random import choice
11
- from threading import Event
12
- from types import TracebackType
13
- from typing import cast
14
-
15
- import primp # type: ignore
16
-
17
- try:
18
- from lxml.etree import _Element
19
- from lxml.html import HTMLParser as LHTMLParser
20
- from lxml.html import document_fromstring
21
-
22
- LXML_AVAILABLE = True
23
- except ImportError:
24
- LXML_AVAILABLE = False
25
-
26
- from .exceptions import ConversationLimitException, WebscoutE, RatelimitE, TimeoutE
27
- from .utils import (
28
- _calculate_distance,
29
- _expand_proxy_tb_alias,
30
- _extract_vqd,
31
- _normalize,
32
- _normalize_url,
33
- _text_extract_json,
34
- json_loads,
35
- )
36
-
37
- # logger = logging.getLogger("webscout.WEBS")
38
-
39
-
40
- class WEBS:
41
- """webscout class to get search results from duckduckgo.com."""
42
-
43
- _executor: ThreadPoolExecutor = ThreadPoolExecutor()
44
- _impersonates = (
45
- "chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107", "chrome_108",
46
- "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118", "chrome_119", "chrome_120",
47
- #"chrome_123", "chrome_124", "chrome_126",
48
- "chrome_127", "chrome_128", "chrome_129",
49
- "safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_15.3", "safari_15.5", "safari_15.6.1",
50
- "safari_16", "safari_16.5", "safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5", "safari_18",
51
- "safari_ipad_18",
52
- "edge_101", "edge_122", "edge_127",
53
- ) # fmt: skip
54
-
55
- def __init__(
56
- self,
57
- headers: dict[str, str] | None = None,
58
- proxy: str | None = None,
59
- proxies: dict[str, str] | str | None = None, # deprecated
60
- timeout: int | None = 10,
61
- ) -> None:
62
- """Initialize the WEBS object.
63
-
64
- Args:
65
- headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
66
- proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
67
- example: "http://user:pass@example.com:3128". Defaults to None.
68
- timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
69
- """
70
- self.proxy: str | None = _expand_proxy_tb_alias(proxy) # replaces "tb" with "socks5://127.0.0.1:9150"
71
- assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
72
- if not proxy and proxies:
73
- warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
74
- self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
75
- self.headers = headers if headers else {}
76
- self.headers["Referer"] = "https://duckduckgo.com/"
77
- self.client = primp.Client(
78
- headers=self.headers,
79
- proxy=self.proxy,
80
- timeout=timeout,
81
- cookie_store=True,
82
- referer=True,
83
- impersonate=choice(self._impersonates),
84
- follow_redirects=False,
85
- verify=False,
86
- )
87
- self._exception_event = Event()
88
- self._chat_messages: list[dict[str, str]] = []
89
- self._chat_tokens_count = 0
90
- self._chat_vqd: str = ""
91
-
92
- def __enter__(self) -> WEBS:
93
- return self
94
-
95
- def __exit__(
96
- self,
97
- exc_type: type[BaseException] | None = None,
98
- exc_val: BaseException | None = None,
99
- exc_tb: TracebackType | None = None,
100
- ) -> None:
101
- pass
102
-
103
- @cached_property
104
- def parser(self) -> LHTMLParser:
105
- """Get HTML parser."""
106
- return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
107
-
108
- def _get_url(
109
- self,
110
- method: str,
111
- url: str,
112
- params: dict[str, str] | None = None,
113
- content: bytes | None = None,
114
- data: dict[str, str] | bytes | None = None,
115
- ) -> bytes:
116
- if self._exception_event.is_set():
117
- raise WebscoutE("Exception occurred in previous call.")
118
- try:
119
- resp = self.client.request(method, url, params=params, content=content, data=data)
120
- except Exception as ex:
121
- self._exception_event.set()
122
- if "time" in str(ex).lower():
123
- raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
124
- raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
125
- # logger.debug(f"_get_url() {resp.url} {resp.status_code} {len(resp.content)}")
126
- if resp.status_code == 200:
127
- return cast(bytes, resp.content)
128
- self._exception_event.set()
129
- if resp.status_code in (202, 301, 403):
130
- raise RatelimitE(f"{resp.url} {resp.status_code} Ratelimit")
131
- raise WebscoutE(f"{resp.url} return None. {params=} {content=} {data=}")
132
-
133
- def _get_vqd(self, keywords: str) -> str:
134
- """Get vqd value for a search query."""
135
- resp_content = self._get_url("GET", "https://duckduckgo.com", params={"q": keywords})
136
- return _extract_vqd(resp_content, keywords)
137
-
138
- def chat(self, keywords: str, model: str = "gpt-4o-mini", timeout: int = 30) -> str:
139
- """Initiates a chat session with webscout AI.
140
-
141
- Args:
142
- keywords (str): The initial message or question to send to the AI.
143
- model (str): The model to use: "gpt-4o-mini", "claude-3-haiku", "llama-3.1-70b", "mixtral-8x7b".
144
- Defaults to "gpt-4o-mini".
145
- timeout (int): Timeout value for the HTTP client. Defaults to 20.
146
-
147
- Returns:
148
- str: The response from the AI.
149
- """
150
- models_deprecated = {
151
- "gpt-3.5": "gpt-4o-mini",
152
- "llama-3-70b": "llama-3.1-70b",
153
- }
154
- if model in models_deprecated:
155
- # logger.info(f"{model=} is deprecated, using {models_deprecated[model]}")
156
- model = models_deprecated[model]
157
- models = {
158
- "claude-3-haiku": "claude-3-haiku-20240307",
159
- "gpt-4o-mini": "gpt-4o-mini",
160
- "llama-3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
161
- "mixtral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
162
- }
163
- # vqd
164
- if not self._chat_vqd:
165
- resp = self.client.get("https://duckduckgo.com/duckchat/v1/status", headers={"x-vqd-accept": "1"})
166
- self._chat_vqd = resp.headers.get("x-vqd-4", "")
167
-
168
- self._chat_messages.append({"role": "user", "content": keywords})
169
- self._chat_tokens_count += len(keywords) // 4 if len(keywords) >= 4 else 1 # approximate number of tokens
170
-
171
- json_data = {
172
- "model": models[model],
173
- "messages": self._chat_messages,
174
- }
175
- resp = self.client.post(
176
- "https://duckduckgo.com/duckchat/v1/chat",
177
- headers={"x-vqd-4": self._chat_vqd},
178
- json=json_data,
179
- timeout=timeout,
180
- )
181
- self._chat_vqd = resp.headers.get("x-vqd-4", "")
182
-
183
- data = ",".join(line.strip() for line in resp.text.rstrip("[DONE]LIMT_CVRSA\n").split("data:") if line.strip())
184
- data = json_loads("[" + data + "]")
185
-
186
- results = []
187
- for x in data:
188
- if x.get("action") == "error":
189
- err_message = x.get("type", "")
190
- if x.get("status") == 429:
191
- raise (
192
- ConversationLimitException(err_message)
193
- if err_message == "ERR_CONVERSATION_LIMIT"
194
- else RatelimitE(err_message)
195
- )
196
- raise WebscoutE(err_message)
197
- elif message := x.get("message"):
198
- results.append(message)
199
- result = "".join(results)
200
-
201
- self._chat_messages.append({"role": "assistant", "content": result})
202
- self._chat_tokens_count += len(results)
203
- return result
204
-
205
- def text(
206
- self,
207
- keywords: str,
208
- region: str = "wt-wt",
209
- safesearch: str = "moderate",
210
- timelimit: str | None = None,
211
- backend: str = "api",
212
- max_results: int | None = None,
213
- ) -> list[dict[str, str]]:
214
- """webscout text search. Query params: https://duckduckgo.com/params.
215
-
216
- Args:
217
- keywords: keywords for query.
218
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
219
- safesearch: on, moderate, off. Defaults to "moderate".
220
- timelimit: d, w, m, y. Defaults to None.
221
- backend: api, html, lite. Defaults to api.
222
- api - collect data from https://duckduckgo.com,
223
- html - collect data from https://html.duckduckgo.com,
224
- lite - collect data from https://lite.duckduckgo.com.
225
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
226
-
227
- Returns:
228
- List of dictionaries with search results, or None if there was an error.
229
-
230
- Raises:
231
- WebscoutE: Base exception for webscout errors.
232
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
233
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
234
- """
235
- if LXML_AVAILABLE is False and backend != "api":
236
- backend = "api"
237
- warnings.warn("lxml is not installed. Using backend='api'.", stacklevel=2)
238
-
239
- if backend == "api":
240
- results = self._text_api(keywords, region, safesearch, timelimit, max_results)
241
- elif backend == "html":
242
- results = self._text_html(keywords, region, timelimit, max_results)
243
- elif backend == "lite":
244
- results = self._text_lite(keywords, region, timelimit, max_results)
245
- return results
246
-
247
- def _text_api(
248
- self,
249
- keywords: str,
250
- region: str = "wt-wt",
251
- safesearch: str = "moderate",
252
- timelimit: str | None = None,
253
- max_results: int | None = None,
254
- ) -> list[dict[str, str]]:
255
- """webscout text search. Query params: https://duckduckgo.com/params.
256
-
257
- Args:
258
- keywords: keywords for query.
259
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
260
- safesearch: on, moderate, off. Defaults to "moderate".
261
- timelimit: d, w, m, y. Defaults to None.
262
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
263
-
264
- Returns:
265
- List of dictionaries with search results.
266
-
267
- Raises:
268
- WebscoutE: Base exception for webscout errors.
269
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
270
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
271
- """
272
- assert keywords, "keywords is mandatory"
273
-
274
- vqd = self._get_vqd(keywords)
275
-
276
- payload = {
277
- "q": keywords,
278
- "kl": region,
279
- "l": region,
280
- "p": "",
281
- "s": "0",
282
- "df": "",
283
- "vqd": vqd,
284
- "bing_market": f"{region[3:]}-{region[:2].upper()}",
285
- "ex": "",
286
- }
287
- safesearch = safesearch.lower()
288
- if safesearch == "moderate":
289
- payload["ex"] = "-1"
290
- elif safesearch == "off":
291
- payload["ex"] = "-2"
292
- elif safesearch == "on": # strict
293
- payload["p"] = "1"
294
- if timelimit:
295
- payload["df"] = timelimit
296
-
297
- cache = set()
298
- results: list[dict[str, str]] = []
299
-
300
- def _text_api_page(s: int) -> list[dict[str, str]]:
301
- payload["s"] = f"{s}"
302
- resp_content = self._get_url("GET", "https://links.duckduckgo.com/d.js", params=payload)
303
- page_data = _text_extract_json(resp_content, keywords)
304
- page_results = []
305
- for row in page_data:
306
- href = row.get("u", None)
307
- if href and href not in cache and href != f"http://www.google.com/search?q={keywords}":
308
- cache.add(href)
309
- body = _normalize(row["a"])
310
- if body:
311
- result = {
312
- "title": _normalize(row["t"]),
313
- "href": _normalize_url(href),
314
- "body": body,
315
- }
316
- page_results.append(result)
317
- return page_results
318
-
319
- slist = [0]
320
- if max_results:
321
- max_results = min(max_results, 2023)
322
- slist.extend(range(23, max_results, 50))
323
- try:
324
- for r in self._executor.map(_text_api_page, slist):
325
- results.extend(r)
326
- except Exception as e:
327
- raise e
328
-
329
- return list(islice(results, max_results))
330
-
331
- def _text_html(
332
- self,
333
- keywords: str,
334
- region: str = "wt-wt",
335
- timelimit: str | None = None,
336
- max_results: int | None = None,
337
- ) -> list[dict[str, str]]:
338
- """webscout text search. Query params: https://duckduckgo.com/params.
339
-
340
- Args:
341
- keywords: keywords for query.
342
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
343
- timelimit: d, w, m, y. Defaults to None.
344
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
345
-
346
- Returns:
347
- List of dictionaries with search results.
348
-
349
- Raises:
350
- WebscoutE: Base exception for webscout errors.
351
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
352
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
353
- """
354
- assert keywords, "keywords is mandatory"
355
-
356
- payload = {
357
- "q": keywords,
358
- "s": "0",
359
- "o": "json",
360
- "api": "d.js",
361
- "vqd": "",
362
- "kl": region,
363
- "bing_market": region,
364
- }
365
- if timelimit:
366
- payload["df"] = timelimit
367
- if max_results and max_results > 20:
368
- vqd = self._get_vqd(keywords)
369
- payload["vqd"] = vqd
370
-
371
- cache = set()
372
- results: list[dict[str, str]] = []
373
-
374
- def _text_html_page(s: int) -> list[dict[str, str]]:
375
- payload["s"] = f"{s}"
376
- resp_content = self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
377
- if b"No results." in resp_content:
378
- return []
379
-
380
- page_results = []
381
- tree = document_fromstring(resp_content, self.parser)
382
- elements = tree.xpath("//div[h2]")
383
- if not isinstance(elements, list):
384
- return []
385
- for e in elements:
386
- if isinstance(e, _Element):
387
- hrefxpath = e.xpath("./a/@href")
388
- href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
389
- if (
390
- href
391
- and href not in cache
392
- and not href.startswith(
393
- ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
394
- )
395
- ):
396
- cache.add(href)
397
- titlexpath = e.xpath("./h2/a/text()")
398
- title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
399
- bodyxpath = e.xpath("./a//text()")
400
- body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
401
- result = {
402
- "title": _normalize(title),
403
- "href": _normalize_url(href),
404
- "body": _normalize(body),
405
- }
406
- page_results.append(result)
407
- return page_results
408
-
409
- slist = [0]
410
- if max_results:
411
- max_results = min(max_results, 2023)
412
- slist.extend(range(23, max_results, 50))
413
- try:
414
- for r in self._executor.map(_text_html_page, slist):
415
- results.extend(r)
416
- except Exception as e:
417
- raise e
418
-
419
- return list(islice(results, max_results))
420
-
421
- def _text_lite(
422
- self,
423
- keywords: str,
424
- region: str = "wt-wt",
425
- timelimit: str | None = None,
426
- max_results: int | None = None,
427
- ) -> list[dict[str, str]]:
428
- """webscout text search. Query params: https://duckduckgo.com/params.
429
-
430
- Args:
431
- keywords: keywords for query.
432
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
433
- timelimit: d, w, m, y. Defaults to None.
434
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
435
-
436
- Returns:
437
- List of dictionaries with search results.
438
-
439
- Raises:
440
- WebscoutE: Base exception for webscout errors.
441
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
442
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
443
- """
444
- assert keywords, "keywords is mandatory"
445
-
446
- payload = {
447
- "q": keywords,
448
- "s": "0",
449
- "o": "json",
450
- "api": "d.js",
451
- "vqd": "",
452
- "kl": region,
453
- "bing_market": region,
454
- }
455
- if timelimit:
456
- payload["df"] = timelimit
457
-
458
- cache = set()
459
- results: list[dict[str, str]] = []
460
-
461
- def _text_lite_page(s: int) -> list[dict[str, str]]:
462
- payload["s"] = f"{s}"
463
- resp_content = self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
464
- if b"No more results." in resp_content:
465
- return []
466
-
467
- page_results = []
468
- tree = document_fromstring(resp_content, self.parser)
469
- elements = tree.xpath("//table[last()]//tr")
470
- if not isinstance(elements, list):
471
- return []
472
-
473
- data = zip(cycle(range(1, 5)), elements)
474
- for i, e in data:
475
- if isinstance(e, _Element):
476
- if i == 1:
477
- hrefxpath = e.xpath(".//a//@href")
478
- href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
479
- if (
480
- href is None
481
- or href in cache
482
- or href.startswith(
483
- ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
484
- )
485
- ):
486
- [next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
487
- else:
488
- cache.add(href)
489
- titlexpath = e.xpath(".//a//text()")
490
- title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
491
- elif i == 2:
492
- bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
493
- body = (
494
- "".join(str(x) for x in bodyxpath).strip()
495
- if bodyxpath and isinstance(bodyxpath, list)
496
- else ""
497
- )
498
- if href:
499
- result = {
500
- "title": _normalize(title),
501
- "href": _normalize_url(href),
502
- "body": _normalize(body),
503
- }
504
- page_results.append(result)
505
- return page_results
506
-
507
- slist = [0]
508
- if max_results:
509
- max_results = min(max_results, 2023)
510
- slist.extend(range(23, max_results, 50))
511
- try:
512
- for r in self._executor.map(_text_lite_page, slist):
513
- results.extend(r)
514
- except Exception as e:
515
- raise e
516
-
517
- return list(islice(results, max_results))
518
-
519
- def images(
520
- self,
521
- keywords: str,
522
- region: str = "wt-wt",
523
- safesearch: str = "moderate",
524
- timelimit: str | None = None,
525
- size: str | None = None,
526
- color: str | None = None,
527
- type_image: str | None = None,
528
- layout: str | None = None,
529
- license_image: str | None = None,
530
- max_results: int | None = None,
531
- ) -> list[dict[str, str]]:
532
- """webscout images search. Query params: https://duckduckgo.com/params.
533
-
534
- Args:
535
- keywords: keywords for query.
536
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
537
- safesearch: on, moderate, off. Defaults to "moderate".
538
- timelimit: Day, Week, Month, Year. Defaults to None.
539
- size: Small, Medium, Large, Wallpaper. Defaults to None.
540
- color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
541
- Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
542
- type_image: photo, clipart, gif, transparent, line.
543
- Defaults to None.
544
- layout: Square, Tall, Wide. Defaults to None.
545
- license_image: any (All Creative Commons), Public (PublicDomain),
546
- Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
547
- Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
548
- Use Commercially). Defaults to None.
549
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
550
-
551
- Returns:
552
- List of dictionaries with images search results.
553
-
554
- Raises:
555
- WebscoutE: Base exception for webscout errors.
556
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
557
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
558
- """
559
- assert keywords, "keywords is mandatory"
560
-
561
- vqd = self._get_vqd(keywords)
562
-
563
- safesearch_base = {"on": "1", "moderate": "1", "off": "-1"}
564
- timelimit = f"time:{timelimit}" if timelimit else ""
565
- size = f"size:{size}" if size else ""
566
- color = f"color:{color}" if color else ""
567
- type_image = f"type:{type_image}" if type_image else ""
568
- layout = f"layout:{layout}" if layout else ""
569
- license_image = f"license:{license_image}" if license_image else ""
570
- payload = {
571
- "l": region,
572
- "o": "json",
573
- "q": keywords,
574
- "vqd": vqd,
575
- "f": f"{timelimit},{size},{color},{type_image},{layout},{license_image}",
576
- "p": safesearch_base[safesearch.lower()],
577
- }
578
-
579
- cache = set()
580
- results: list[dict[str, str]] = []
581
-
582
- def _images_page(s: int) -> list[dict[str, str]]:
583
- payload["s"] = f"{s}"
584
- resp_content = self._get_url("GET", "https://duckduckgo.com/i.js", params=payload)
585
- resp_json = json_loads(resp_content)
586
-
587
- page_data = resp_json.get("results", [])
588
- page_results = []
589
- for row in page_data:
590
- image_url = row.get("image")
591
- if image_url and image_url not in cache:
592
- cache.add(image_url)
593
- result = {
594
- "title": row["title"],
595
- "image": _normalize_url(image_url),
596
- "thumbnail": _normalize_url(row["thumbnail"]),
597
- "url": _normalize_url(row["url"]),
598
- "height": row["height"],
599
- "width": row["width"],
600
- "source": row["source"],
601
- }
602
- page_results.append(result)
603
- return page_results
604
-
605
- slist = [0]
606
- if max_results:
607
- max_results = min(max_results, 500)
608
- slist.extend(range(100, max_results, 100))
609
- try:
610
- for r in self._executor.map(_images_page, slist):
611
- results.extend(r)
612
- except Exception as e:
613
- raise e
614
-
615
- return list(islice(results, max_results))
616
-
617
- def videos(
618
- self,
619
- keywords: str,
620
- region: str = "wt-wt",
621
- safesearch: str = "moderate",
622
- timelimit: str | None = None,
623
- resolution: str | None = None,
624
- duration: str | None = None,
625
- license_videos: str | None = None,
626
- max_results: int | None = None,
627
- ) -> list[dict[str, str]]:
628
- """webscout videos search. Query params: https://duckduckgo.com/params.
629
-
630
- Args:
631
- keywords: keywords for query.
632
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
633
- safesearch: on, moderate, off. Defaults to "moderate".
634
- timelimit: d, w, m. Defaults to None.
635
- resolution: high, standart. Defaults to None.
636
- duration: short, medium, long. Defaults to None.
637
- license_videos: creativeCommon, youtube. Defaults to None.
638
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
639
-
640
- Returns:
641
- List of dictionaries with videos search results.
642
-
643
- Raises:
644
- WebscoutE: Base exception for webscout errors.
645
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
646
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
647
- """
648
- assert keywords, "keywords is mandatory"
649
-
650
- vqd = self._get_vqd(keywords)
651
-
652
- safesearch_base = {"on": "1", "moderate": "-1", "off": "-2"}
653
- timelimit = f"publishedAfter:{timelimit}" if timelimit else ""
654
- resolution = f"videoDefinition:{resolution}" if resolution else ""
655
- duration = f"videoDuration:{duration}" if duration else ""
656
- license_videos = f"videoLicense:{license_videos}" if license_videos else ""
657
- payload = {
658
- "l": region,
659
- "o": "json",
660
- "q": keywords,
661
- "vqd": vqd,
662
- "f": f"{timelimit},{resolution},{duration},{license_videos}",
663
- "p": safesearch_base[safesearch.lower()],
664
- }
665
-
666
- cache = set()
667
- results: list[dict[str, str]] = []
668
-
669
- def _videos_page(s: int) -> list[dict[str, str]]:
670
- payload["s"] = f"{s}"
671
- resp_content = self._get_url("GET", "https://duckduckgo.com/v.js", params=payload)
672
- resp_json = json_loads(resp_content)
673
-
674
- page_data = resp_json.get("results", [])
675
- page_results = []
676
- for row in page_data:
677
- if row["content"] not in cache:
678
- cache.add(row["content"])
679
- page_results.append(row)
680
- return page_results
681
-
682
- slist = [0]
683
- if max_results:
684
- max_results = min(max_results, 400)
685
- slist.extend(range(60, max_results, 60))
686
- try:
687
- for r in self._executor.map(_videos_page, slist):
688
- results.extend(r)
689
- except Exception as e:
690
- raise e
691
-
692
- return list(islice(results, max_results))
693
-
694
- def news(
695
- self,
696
- keywords: str,
697
- region: str = "wt-wt",
698
- safesearch: str = "moderate",
699
- timelimit: str | None = None,
700
- max_results: int | None = None,
701
- ) -> list[dict[str, str]]:
702
- """webscout news search. Query params: https://duckduckgo.com/params.
703
-
704
- Args:
705
- keywords: keywords for query.
706
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
707
- safesearch: on, moderate, off. Defaults to "moderate".
708
- timelimit: d, w, m. Defaults to None.
709
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
710
-
711
- Returns:
712
- List of dictionaries with news search results.
713
-
714
- Raises:
715
- WebscoutE: Base exception for webscout errors.
716
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
717
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
718
- """
719
- assert keywords, "keywords is mandatory"
720
-
721
- vqd = self._get_vqd(keywords)
722
-
723
- safesearch_base = {"on": "1", "moderate": "-1", "off": "-2"}
724
- payload = {
725
- "l": region,
726
- "o": "json",
727
- "noamp": "1",
728
- "q": keywords,
729
- "vqd": vqd,
730
- "p": safesearch_base[safesearch.lower()],
731
- }
732
- if timelimit:
733
- payload["df"] = timelimit
734
-
735
- cache = set()
736
- results: list[dict[str, str]] = []
737
-
738
- def _news_page(s: int) -> list[dict[str, str]]:
739
- payload["s"] = f"{s}"
740
- resp_content = self._get_url("GET", "https://duckduckgo.com/news.js", params=payload)
741
- resp_json = json_loads(resp_content)
742
- page_data = resp_json.get("results", [])
743
- page_results = []
744
- for row in page_data:
745
- if row["url"] not in cache:
746
- cache.add(row["url"])
747
- image_url = row.get("image", None)
748
- result = {
749
- "date": datetime.fromtimestamp(row["date"], timezone.utc).isoformat(),
750
- "title": row["title"],
751
- "body": _normalize(row["excerpt"]),
752
- "url": _normalize_url(row["url"]),
753
- "image": _normalize_url(image_url),
754
- "source": row["source"],
755
- }
756
- page_results.append(result)
757
- return page_results
758
-
759
- slist = [0]
760
- if max_results:
761
- max_results = min(max_results, 120)
762
- slist.extend(range(30, max_results, 30))
763
- try:
764
- for r in self._executor.map(_news_page, slist):
765
- results.extend(r)
766
- except Exception as e:
767
- raise e
768
-
769
- return list(islice(results, max_results))
770
-
771
- def answers(self, keywords: str) -> list[dict[str, str]]:
772
- """webscout instant answers. Query params: https://duckduckgo.com/params.
773
-
774
- Args:
775
- keywords: keywords for query,
776
-
777
- Returns:
778
- List of dictionaries with instant answers results.
779
-
780
- Raises:
781
- WebscoutE: Base exception for webscout errors.
782
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
783
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
784
- """
785
- assert keywords, "keywords is mandatory"
786
-
787
- payload = {
788
- "q": f"what is {keywords}",
789
- "format": "json",
790
- }
791
- resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload)
792
- page_data = json_loads(resp_content)
793
-
794
- results = []
795
- answer = page_data.get("AbstractText")
796
- url = page_data.get("AbstractURL")
797
- if answer:
798
- results.append(
799
- {
800
- "icon": None,
801
- "text": answer,
802
- "topic": None,
803
- "url": url,
804
- }
805
- )
806
-
807
- # related
808
- payload = {
809
- "q": f"{keywords}",
810
- "format": "json",
811
- }
812
- resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload)
813
- resp_json = json_loads(resp_content)
814
- page_data = resp_json.get("RelatedTopics", [])
815
-
816
- for row in page_data:
817
- topic = row.get("Name")
818
- if not topic:
819
- icon = row["Icon"].get("URL")
820
- results.append(
821
- {
822
- "icon": f"https://duckduckgo.com{icon}" if icon else "",
823
- "text": row["Text"],
824
- "topic": None,
825
- "url": row["FirstURL"],
826
- }
827
- )
828
- else:
829
- for subrow in row["Topics"]:
830
- icon = subrow["Icon"].get("URL")
831
- results.append(
832
- {
833
- "icon": f"https://duckduckgo.com{icon}" if icon else "",
834
- "text": subrow["Text"],
835
- "topic": topic,
836
- "url": subrow["FirstURL"],
837
- }
838
- )
839
-
840
- return results
841
-
842
- def suggestions(self, keywords: str, region: str = "wt-wt") -> list[dict[str, str]]:
843
- """webscout suggestions. Query params: https://duckduckgo.com/params.
844
-
845
- Args:
846
- keywords: keywords for query.
847
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
848
-
849
- Returns:
850
- List of dictionaries with suggestions results.
851
-
852
- Raises:
853
- WebscoutE: Base exception for webscout errors.
854
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
855
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
856
- """
857
- assert keywords, "keywords is mandatory"
858
-
859
- payload = {
860
- "q": keywords,
861
- "kl": region,
862
- }
863
- resp_content = self._get_url("GET", "https://duckduckgo.com/ac/", params=payload)
864
- page_data = json_loads(resp_content)
865
- return [r for r in page_data]
866
-
867
- def maps(
868
- self,
869
- keywords: str,
870
- place: str | None = None,
871
- street: str | None = None,
872
- city: str | None = None,
873
- county: str | None = None,
874
- state: str | None = None,
875
- country: str | None = None,
876
- postalcode: str | None = None,
877
- latitude: str | None = None,
878
- longitude: str | None = None,
879
- radius: int = 0,
880
- max_results: int | None = None,
881
- ) -> list[dict[str, str]]:
882
- """webscout maps search. Query params: https://duckduckgo.com/params.
883
-
884
- Args:
885
- keywords: keywords for query
886
- place: if set, the other parameters are not used. Defaults to None.
887
- street: house number/street. Defaults to None.
888
- city: city of search. Defaults to None.
889
- county: county of search. Defaults to None.
890
- state: state of search. Defaults to None.
891
- country: country of search. Defaults to None.
892
- postalcode: postalcode of search. Defaults to None.
893
- latitude: geographic coordinate (north-south position). Defaults to None.
894
- longitude: geographic coordinate (east-west position); if latitude and
895
- longitude are set, the other parameters are not used. Defaults to None.
896
- radius: expand the search square by the distance in kilometers. Defaults to 0.
897
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
898
-
899
- Returns:
900
- List of dictionaries with maps search results, or None if there was an error.
901
-
902
- Raises:
903
- WebscoutE: Base exception for webscout errors.
904
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
905
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
906
- """
907
- assert keywords, "keywords is mandatory"
908
-
909
- vqd = self._get_vqd(keywords)
910
-
911
- # if longitude and latitude are specified, skip the request about bbox to the nominatim api
912
- if latitude and longitude:
913
- lat_t = Decimal(latitude.replace(",", "."))
914
- lat_b = Decimal(latitude.replace(",", "."))
915
- lon_l = Decimal(longitude.replace(",", "."))
916
- lon_r = Decimal(longitude.replace(",", "."))
917
- if radius == 0:
918
- radius = 1
919
- # otherwise request about bbox to nominatim api
920
- else:
921
- if place:
922
- params = {
923
- "q": place,
924
- "polygon_geojson": "0",
925
- "format": "jsonv2",
926
- }
927
- else:
928
- params = {
929
- "polygon_geojson": "0",
930
- "format": "jsonv2",
931
- }
932
- if street:
933
- params["street"] = street
934
- if city:
935
- params["city"] = city
936
- if county:
937
- params["county"] = county
938
- if state:
939
- params["state"] = state
940
- if country:
941
- params["country"] = country
942
- if postalcode:
943
- params["postalcode"] = postalcode
944
- # request nominatim api to get coordinates box
945
- resp_content = self._get_url(
946
- "GET",
947
- "https://nominatim.openstreetmap.org/search.php",
948
- params=params,
949
- )
950
- if resp_content == b"[]":
951
- raise WebscoutE("maps() Coordinates are not found, check function parameters.")
952
- resp_json = json_loads(resp_content)
953
- coordinates = resp_json[0]["boundingbox"]
954
- lat_t, lon_l = Decimal(coordinates[1]), Decimal(coordinates[2])
955
- lat_b, lon_r = Decimal(coordinates[0]), Decimal(coordinates[3])
956
-
957
- # if a radius is specified, expand the search square
958
- lat_t += Decimal(radius) * Decimal(0.008983)
959
- lat_b -= Decimal(radius) * Decimal(0.008983)
960
- lon_l -= Decimal(radius) * Decimal(0.008983)
961
- lon_r += Decimal(radius) * Decimal(0.008983)
962
- # logger.debug(f"bbox coordinates\n{lat_t} {lon_l}\n{lat_b} {lon_r}")
963
-
964
- cache = set()
965
- results: list[dict[str, str]] = []
966
-
967
- def _maps_page(
968
- bbox: tuple[Decimal, Decimal, Decimal, Decimal],
969
- ) -> list[dict[str, str]] | None:
970
- if max_results and len(results) >= max_results:
971
- return None
972
- lat_t, lon_l, lat_b, lon_r = bbox
973
- params = {
974
- "q": keywords,
975
- "vqd": vqd,
976
- "tg": "maps_places",
977
- "rt": "D",
978
- "mkexp": "b",
979
- "wiki_info": "1",
980
- "is_requery": "1",
981
- "bbox_tl": f"{lat_t},{lon_l}",
982
- "bbox_br": f"{lat_b},{lon_r}",
983
- "strict_bbox": "1",
984
- }
985
- resp_content = self._get_url("GET", "https://duckduckgo.com/local.js", params=params)
986
- resp_json = json_loads(resp_content)
987
- page_data = resp_json.get("results", [])
988
-
989
- page_results = []
990
- for res in page_data:
991
- r_name = f'{res["name"]} {res["address"]}'
992
- if r_name in cache:
993
- continue
994
- else:
995
- cache.add(r_name)
996
- result = {
997
- "title": res["name"],
998
- "address": res["address"],
999
- "country_code": res["country_code"],
1000
- "url": _normalize_url(res["website"]),
1001
- "phone": res["phone"] or "",
1002
- "latitude": res["coordinates"]["latitude"],
1003
- "longitude": res["coordinates"]["longitude"],
1004
- "source": _normalize_url(res["url"]),
1005
- "image": x.get("image", "") if (x := res["embed"]) else "",
1006
- "desc": x.get("description", "") if (x := res["embed"]) else "",
1007
- "hours": res["hours"] or "",
1008
- "category": res["ddg_category"] or "",
1009
- "facebook": f"www.facebook.com/profile.php?id={x}" if (x := res["facebook_id"]) else "",
1010
- "instagram": f"https://www.instagram.com/{x}" if (x := res["instagram_id"]) else "",
1011
- "twitter": f"https://twitter.com/{x}" if (x := res["twitter_id"]) else "",
1012
- }
1013
- page_results.append(result)
1014
- return page_results
1015
-
1016
- # search squares (bboxes)
1017
- start_bbox = (lat_t, lon_l, lat_b, lon_r)
1018
- work_bboxes = [start_bbox]
1019
- while work_bboxes:
1020
- queue_bboxes = [] # for next iteration, at the end of the iteration work_bboxes = queue_bboxes
1021
- tasks = []
1022
- for bbox in work_bboxes:
1023
- tasks.append(bbox)
1024
- # if distance between coordinates > 1, divide the square into 4 parts and save them in queue_bboxes
1025
- if _calculate_distance(lat_t, lon_l, lat_b, lon_r) > 1:
1026
- lat_t, lon_l, lat_b, lon_r = bbox
1027
- lat_middle = (lat_t + lat_b) / 2
1028
- lon_middle = (lon_l + lon_r) / 2
1029
- bbox1 = (lat_t, lon_l, lat_middle, lon_middle)
1030
- bbox2 = (lat_t, lon_middle, lat_middle, lon_r)
1031
- bbox3 = (lat_middle, lon_l, lat_b, lon_middle)
1032
- bbox4 = (lat_middle, lon_middle, lat_b, lon_r)
1033
- queue_bboxes.extend([bbox1, bbox2, bbox3, bbox4])
1034
-
1035
- # gather tasks using asyncio.wait_for and timeout
1036
- work_bboxes_results = []
1037
- try:
1038
- for r in self._executor.map(_maps_page, tasks):
1039
- if r:
1040
- work_bboxes_results.extend(r)
1041
- except Exception as e:
1042
- raise e
1043
-
1044
- for x in work_bboxes_results:
1045
- if isinstance(x, list):
1046
- results.extend(x)
1047
- elif isinstance(x, dict):
1048
- results.append(x)
1049
-
1050
- work_bboxes = queue_bboxes
1051
- if not max_results or len(results) >= max_results or len(work_bboxes_results) == 0:
1052
- break
1053
-
1054
- return list(islice(results, max_results))
1055
-
1056
- def translate(self, keywords: list[str] | str, from_: str | None = None, to: str = "en") -> list[dict[str, str]]:
1057
- """webscout translate.
1058
-
1059
- Args:
1060
- keywords: string or list of strings to translate.
1061
- from_: translate from (defaults automatically). Defaults to None.
1062
- to: what language to translate. Defaults to "en".
1063
-
1064
- Returns:
1065
- List od dictionaries with translated keywords.
1066
-
1067
- Raises:
1068
- WebscoutE: Base exception for webscout errors.
1069
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
1070
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
1071
- """
1072
- assert keywords, "keywords is mandatory"
1073
-
1074
- vqd = self._get_vqd("translate")
1075
-
1076
- payload = {
1077
- "vqd": vqd,
1078
- "query": "translate",
1079
- "to": to,
1080
- }
1081
- if from_:
1082
- payload["from"] = from_
1083
-
1084
- def _translate_keyword(keyword: str) -> dict[str, str]:
1085
- resp_content = self._get_url(
1086
- "POST",
1087
- "https://duckduckgo.com/translation.js",
1088
- params=payload,
1089
- content=keyword.encode(),
1090
- )
1091
- page_data: dict[str, str] = json_loads(resp_content)
1092
- page_data["original"] = keyword
1093
- return page_data
1094
-
1095
- if isinstance(keywords, str):
1096
- keywords = [keywords]
1097
-
1098
- results = []
1099
- try:
1100
- for r in self._executor.map(_translate_keyword, keywords):
1101
- results.append(r)
1102
- except Exception as e:
1103
- raise e
1104
-
1
+ from __future__ import annotations
2
+
3
+ # import logging
4
+ import warnings
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from datetime import datetime, timezone
7
+ from decimal import Decimal
8
+ from functools import cached_property
9
+ from itertools import cycle, islice
10
+ from random import choice, shuffle
11
+ from threading import Event
12
+ from time import sleep, time
13
+ from types import TracebackType
14
+ from typing import cast
15
+
16
+ import primp # type: ignore
17
+
18
+ try:
19
+ from lxml.etree import _Element
20
+ from lxml.html import HTMLParser as LHTMLParser
21
+ from lxml.html import document_fromstring
22
+
23
+ LXML_AVAILABLE = True
24
+ except ImportError:
25
+ LXML_AVAILABLE = False
26
+
27
+ from .exceptions import ConversationLimitException, WebscoutE, RatelimitE, TimeoutE
28
+ from .utils import (
29
+ _calculate_distance,
30
+ _expand_proxy_tb_alias,
31
+ _extract_vqd,
32
+ _normalize,
33
+ _normalize_url,
34
+ _text_extract_json,
35
+ json_loads,
36
+ )
37
+
38
+ # logger = logging.getLogger("webscout.WEBS")
39
+
40
+
41
+ class WEBS:
42
+ """webscout class to get search results from duckduckgo.com."""
43
+
44
+ _executor: ThreadPoolExecutor = ThreadPoolExecutor()
45
+ _impersonates = (
46
+ "chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107", "chrome_108",
47
+ "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118", "chrome_119", "chrome_120",
48
+ #"chrome_123", "chrome_124", "chrome_126",
49
+ "chrome_127", "chrome_128", "chrome_129",
50
+ "safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_15.3", "safari_15.5", "safari_15.6.1",
51
+ "safari_16", "safari_16.5", "safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5", "safari_18",
52
+ "safari_ipad_18",
53
+ "edge_101", "edge_122", "edge_127",
54
+ ) # fmt: skip
55
+
56
+ def __init__(
57
+ self,
58
+ headers: dict[str, str] | None = None,
59
+ proxy: str | None = None,
60
+ proxies: dict[str, str] | str | None = None, # deprecated
61
+ timeout: int | None = 10,
62
+ ) -> None:
63
+ """Initialize the WEBS object.
64
+
65
+ Args:
66
+ headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
67
+ proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
68
+ example: "http://user:pass@example.com:3128". Defaults to None.
69
+ timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
70
+ """
71
+ self.proxy: str | None = _expand_proxy_tb_alias(proxy)
72
+ assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
73
+ if not proxy and proxies:
74
+ warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
75
+ self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
76
+
77
+ default_headers = {
78
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
79
+ "Accept-Language": "en-US,en;q=0.5",
80
+ "Accept-Encoding": "gzip, deflate, br",
81
+ "DNT": "1",
82
+ "Connection": "keep-alive",
83
+ "Upgrade-Insecure-Requests": "1",
84
+ "Sec-Fetch-Dest": "document",
85
+ "Sec-Fetch-Mode": "navigate",
86
+ "Sec-Fetch-Site": "none",
87
+ "Sec-Fetch-User": "?1",
88
+ "Referer": "https://duckduckgo.com/",
89
+ }
90
+
91
+ self.headers = headers if headers else {}
92
+ self.headers.update(default_headers)
93
+
94
+ self.client = primp.Client(
95
+ headers=self.headers,
96
+ proxy=self.proxy,
97
+ timeout=timeout,
98
+ cookie_store=True,
99
+ referer=True,
100
+ impersonate=choice(self._impersonates),
101
+ follow_redirects=True,
102
+ verify=False,
103
+ )
104
+ self.sleep_timestamp = 0.0
105
+
106
+ self._exception_event = Event()
107
+ self._chat_messages: list[dict[str, str]] = []
108
+ self._chat_tokens_count = 0
109
+ self._chat_vqd: str = ""
110
+
111
+ def __enter__(self) -> WEBS:
112
+ return self
113
+
114
+ def __exit__(
115
+ self,
116
+ exc_type: type[BaseException] | None = None,
117
+ exc_val: BaseException | None = None,
118
+ exc_tb: TracebackType | None = None,
119
+ ) -> None:
120
+ pass
121
+
122
+ @cached_property
123
+ def parser(self) -> LHTMLParser:
124
+ """Get HTML parser."""
125
+ return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
126
+
127
+ def _sleep(self, sleeptime: float = 2.0) -> None:
128
+ """Sleep between API requests."""
129
+ delay = sleeptime if not self.sleep_timestamp else sleeptime if time() - self.sleep_timestamp >= 30 else sleeptime * 2
130
+ self.sleep_timestamp = time()
131
+ sleep(delay)
132
+
133
+ def _get_url(
134
+ self,
135
+ method: str,
136
+ url: str,
137
+ params: dict[str, str] | None = None,
138
+ content: bytes | None = None,
139
+ data: dict[str, str] | None = None,
140
+ ) -> bytes:
141
+ """Make HTTP request with proper rate limiting."""
142
+ self._sleep()
143
+ try:
144
+ resp = self.client.request(method, url, params=params, content=content, data=data)
145
+
146
+ # Add additional delay if we get a 429 or similar status
147
+ if resp.status_code in (429, 403, 503):
148
+ sleep(5.0) # Additional delay for rate limit responses
149
+ resp = self.client.request(method, url, params=params, content=content, data=data)
150
+
151
+ except Exception as ex:
152
+ if "time" in str(ex).lower():
153
+ raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
154
+ raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
155
+
156
+ if resp.status_code == 200:
157
+ return resp.content
158
+ elif resp.status_code in (202, 301, 403, 429, 503):
159
+ raise RatelimitE(f"{url} {resp.status_code} Ratelimit - Please wait a few minutes before retrying")
160
+ raise WebscoutE(f"{url} return None. {params=} {content=} {data=}")
161
+
162
+ def _get_vqd(self, keywords: str) -> str:
163
+ """Get vqd value for a search query."""
164
+ resp_content = self._get_url("GET", "https://duckduckgo.com", params={"q": keywords})
165
+ return _extract_vqd(resp_content, keywords)
166
+
167
+ def chat(self, keywords: str, model: str = "gpt-4o-mini", timeout: int = 30) -> str:
168
+ """Initiates a chat session with webscout AI.
169
+
170
+ Args:
171
+ keywords (str): The initial message or question to send to the AI.
172
+ model (str): The model to use: "gpt-4o-mini", "claude-3-haiku", "llama-3.1-70b", "mixtral-8x7b".
173
+ Defaults to "gpt-4o-mini".
174
+ timeout (int): Timeout value for the HTTP client. Defaults to 20.
175
+
176
+ Returns:
177
+ str: The response from the AI.
178
+ """
179
+ models_deprecated = {
180
+ "gpt-3.5": "gpt-4o-mini",
181
+ "llama-3-70b": "llama-3.1-70b",
182
+ }
183
+ if model in models_deprecated:
184
+ # logger.info(f"{model=} is deprecated, using {models_deprecated[model]}")
185
+ model = models_deprecated[model]
186
+ models = {
187
+ "claude-3-haiku": "claude-3-haiku-20240307",
188
+ "gpt-4o-mini": "gpt-4o-mini",
189
+ "llama-3.1-70b": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
190
+ "mixtral-8x7b": "mistralai/Mixtral-8x7B-Instruct-v0.1",
191
+ }
192
+ # vqd
193
+ if not self._chat_vqd:
194
+ resp = self.client.get("https://duckduckgo.com/duckchat/v1/status", headers={"x-vqd-accept": "1"})
195
+ self._chat_vqd = resp.headers.get("x-vqd-4", "")
196
+
197
+ self._chat_messages.append({"role": "user", "content": keywords})
198
+ self._chat_tokens_count += len(keywords) // 4 if len(keywords) >= 4 else 1 # approximate number of tokens
199
+
200
+ json_data = {
201
+ "model": models[model],
202
+ "messages": self._chat_messages,
203
+ }
204
+ resp = self.client.post(
205
+ "https://duckduckgo.com/duckchat/v1/chat",
206
+ headers={"x-vqd-4": self._chat_vqd},
207
+ json=json_data,
208
+ timeout=timeout,
209
+ )
210
+ self._chat_vqd = resp.headers.get("x-vqd-4", "")
211
+
212
+ data = ",".join(line.strip() for line in resp.text.rstrip("[DONE]LIMT_CVRSA\n").split("data:") if line.strip())
213
+ data = json_loads("[" + data + "]")
214
+
215
+ results = []
216
+ for x in data:
217
+ if x.get("action") == "error":
218
+ err_message = x.get("type", "")
219
+ if x.get("status") == 429:
220
+ raise (
221
+ ConversationLimitException(err_message)
222
+ if err_message == "ERR_CONVERSATION_LIMIT"
223
+ else RatelimitE(err_message)
224
+ )
225
+ raise WebscoutE(err_message)
226
+ elif message := x.get("message"):
227
+ results.append(message)
228
+ result = "".join(results)
229
+
230
+ self._chat_messages.append({"role": "assistant", "content": result})
231
+ self._chat_tokens_count += len(results)
232
+ return result
233
+
234
+ def text(
235
+ self,
236
+ keywords: str,
237
+ region: str = "wt-wt",
238
+ safesearch: str = "moderate",
239
+ timelimit: str | None = None,
240
+ backend: str = "auto",
241
+ max_results: int | None = None,
242
+ ) -> list[dict[str, str]]:
243
+ """webscout text search. Query params: https://duckduckgo.com/params.
244
+
245
+ Args:
246
+ keywords: keywords for query.
247
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
248
+ safesearch: on, moderate, off. Defaults to "moderate".
249
+ timelimit: d, w, m, y. Defaults to None.
250
+ backend: auto, html, lite. Defaults to auto.
251
+ auto - try all backends in random order,
252
+ html - collect data from https://html.duckduckgo.com,
253
+ lite - collect data from https://lite.duckduckgo.com.
254
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
255
+
256
+ Returns:
257
+ List of dictionaries with search results.
258
+
259
+ Raises:
260
+ WebscoutE: Base exception for webscout errors.
261
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
262
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
263
+ """
264
+ if backend in ("api", "ecosia"):
265
+ warnings.warn(f"{backend=} is deprecated, using backend='auto'", stacklevel=2)
266
+ backend = "auto"
267
+ backends = ["html", "lite"] if backend == "auto" else [backend]
268
+ shuffle(backends)
269
+
270
+ results, err = [], None
271
+ for b in backends:
272
+ try:
273
+ if b == "html":
274
+ results = self._text_html(keywords, region, timelimit, max_results)
275
+ elif b == "lite":
276
+ results = self._text_lite(keywords, region, timelimit, max_results)
277
+ return results
278
+ except Exception as ex:
279
+ err = ex
280
+
281
+ raise WebscoutE(err)
282
+
283
+ def _text_api(
284
+ self,
285
+ keywords: str,
286
+ region: str = "wt-wt",
287
+ safesearch: str = "moderate",
288
+ timelimit: str | None = None,
289
+ max_results: int | None = None,
290
+ ) -> list[dict[str, str]]:
291
+ """webscout text search. Query params: https://duckduckgo.com/params.
292
+
293
+ Args:
294
+ keywords: keywords for query.
295
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
296
+ safesearch: on, moderate, off. Defaults to "moderate".
297
+ timelimit: d, w, m, y. Defaults to None.
298
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
299
+
300
+ Returns:
301
+ List of dictionaries with search results.
302
+
303
+ Raises:
304
+ WebscoutE: Base exception for webscout errors.
305
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
306
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
307
+ """
308
+ assert keywords, "keywords is mandatory"
309
+
310
+ vqd = self._get_vqd(keywords)
311
+
312
+ payload = {
313
+ "q": keywords,
314
+ "kl": region,
315
+ "l": region,
316
+ "p": "",
317
+ "s": "0",
318
+ "df": "",
319
+ "vqd": vqd,
320
+ "bing_market": f"{region[3:]}-{region[:2].upper()}",
321
+ "ex": "",
322
+ }
323
+ safesearch = safesearch.lower()
324
+ if safesearch == "moderate":
325
+ payload["ex"] = "-1"
326
+ elif safesearch == "off":
327
+ payload["ex"] = "-2"
328
+ elif safesearch == "on": # strict
329
+ payload["p"] = "1"
330
+ if timelimit:
331
+ payload["df"] = timelimit
332
+
333
+ cache = set()
334
+ results: list[dict[str, str]] = []
335
+
336
+ def _text_api_page(s: int) -> list[dict[str, str]]:
337
+ payload["s"] = f"{s}"
338
+ resp_content = self._get_url("GET", "https://links.duckduckgo.com/d.js", params=payload)
339
+ page_data = _text_extract_json(resp_content, keywords)
340
+ page_results = []
341
+ for row in page_data:
342
+ href = row.get("u", None)
343
+ if href and href not in cache and href != f"http://www.google.com/search?q={keywords}":
344
+ cache.add(href)
345
+ body = _normalize(row["a"])
346
+ if body:
347
+ result = {
348
+ "title": _normalize(row["t"]),
349
+ "href": _normalize_url(href),
350
+ "body": body,
351
+ }
352
+ page_results.append(result)
353
+ return page_results
354
+
355
+ slist = [0]
356
+ if max_results:
357
+ max_results = min(max_results, 2023)
358
+ slist.extend(range(23, max_results, 50))
359
+ try:
360
+ for r in self._executor.map(_text_api_page, slist):
361
+ results.extend(r)
362
+ except Exception as e:
363
+ raise e
364
+
365
+ return list(islice(results, max_results))
366
+
367
+ def _text_html(
368
+ self,
369
+ keywords: str,
370
+ region: str = "wt-wt",
371
+ timelimit: str | None = None,
372
+ max_results: int | None = None,
373
+ ) -> list[dict[str, str]]:
374
+ """webscout text search. Query params: https://duckduckgo.com/params.
375
+
376
+ Args:
377
+ keywords: keywords for query.
378
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
379
+ timelimit: d, w, m, y. Defaults to None.
380
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
381
+
382
+ Returns:
383
+ List of dictionaries with search results.
384
+
385
+ Raises:
386
+ WebscoutE: Base exception for webscout errors.
387
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
388
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
389
+ """
390
+ assert keywords, "keywords is mandatory"
391
+
392
+ payload = {
393
+ "q": keywords,
394
+ "s": "0",
395
+ "o": "json",
396
+ "api": "d.js",
397
+ "vqd": "",
398
+ "kl": region,
399
+ "bing_market": region,
400
+ }
401
+ if timelimit:
402
+ payload["df"] = timelimit
403
+ if max_results and max_results > 20:
404
+ vqd = self._get_vqd(keywords)
405
+ payload["vqd"] = vqd
406
+
407
+ cache = set()
408
+ results: list[dict[str, str]] = []
409
+
410
+ def _text_html_page(s: int) -> list[dict[str, str]]:
411
+ payload["s"] = f"{s}"
412
+ resp_content = self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
413
+ if b"No results." in resp_content:
414
+ return []
415
+
416
+ page_results = []
417
+ tree = document_fromstring(resp_content, self.parser)
418
+ elements = tree.xpath("//div[h2]")
419
+ if not isinstance(elements, list):
420
+ return []
421
+ for e in elements:
422
+ if isinstance(e, _Element):
423
+ hrefxpath = e.xpath("./a/@href")
424
+ href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
425
+ if (
426
+ href
427
+ and href not in cache
428
+ and not href.startswith(
429
+ ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
430
+ )
431
+ ):
432
+ cache.add(href)
433
+ titlexpath = e.xpath("./h2/a/text()")
434
+ title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
435
+ bodyxpath = e.xpath("./a//text()")
436
+ body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
437
+ result = {
438
+ "title": _normalize(title),
439
+ "href": _normalize_url(href),
440
+ "body": _normalize(body),
441
+ }
442
+ page_results.append(result)
443
+ return page_results
444
+
445
+ slist = [0]
446
+ if max_results:
447
+ max_results = min(max_results, 2023)
448
+ slist.extend(range(23, max_results, 50))
449
+ try:
450
+ for r in self._executor.map(_text_html_page, slist):
451
+ results.extend(r)
452
+ except Exception as e:
453
+ raise e
454
+
455
+ return list(islice(results, max_results))
456
+
457
+ def _text_lite(
458
+ self,
459
+ keywords: str,
460
+ region: str = "wt-wt",
461
+ timelimit: str | None = None,
462
+ max_results: int | None = None,
463
+ ) -> list[dict[str, str]]:
464
+ """webscout text search. Query params: https://duckduckgo.com/params.
465
+
466
+ Args:
467
+ keywords: keywords for query.
468
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
469
+ timelimit: d, w, m, y. Defaults to None.
470
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
471
+
472
+ Returns:
473
+ List of dictionaries with search results.
474
+
475
+ Raises:
476
+ WebscoutE: Base exception for webscout errors.
477
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
478
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
479
+ """
480
+ assert keywords, "keywords is mandatory"
481
+
482
+ payload = {
483
+ "q": keywords,
484
+ "s": "0",
485
+ "o": "json",
486
+ "api": "d.js",
487
+ "vqd": "",
488
+ "kl": region,
489
+ "bing_market": region,
490
+ }
491
+ if timelimit:
492
+ payload["df"] = timelimit
493
+
494
+ cache = set()
495
+ results: list[dict[str, str]] = []
496
+
497
+ def _text_lite_page(s: int) -> list[dict[str, str]]:
498
+ payload["s"] = f"{s}"
499
+ resp_content = self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
500
+ if b"No more results." in resp_content:
501
+ return []
502
+
503
+ page_results = []
504
+ tree = document_fromstring(resp_content, self.parser)
505
+ elements = tree.xpath("//table[last()]//tr")
506
+ if not isinstance(elements, list):
507
+ return []
508
+
509
+ data = zip(cycle(range(1, 5)), elements)
510
+ for i, e in data:
511
+ if isinstance(e, _Element):
512
+ if i == 1:
513
+ hrefxpath = e.xpath(".//a//@href")
514
+ href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
515
+ if (
516
+ href is None
517
+ or href in cache
518
+ or href.startswith(
519
+ ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
520
+ )
521
+ ):
522
+ [next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
523
+ else:
524
+ cache.add(href)
525
+ titlexpath = e.xpath(".//a//text()")
526
+ title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
527
+ elif i == 2:
528
+ bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
529
+ body = (
530
+ "".join(str(x) for x in bodyxpath).strip()
531
+ if bodyxpath and isinstance(bodyxpath, list)
532
+ else ""
533
+ )
534
+ if href:
535
+ result = {
536
+ "title": _normalize(title),
537
+ "href": _normalize_url(href),
538
+ "body": _normalize(body),
539
+ }
540
+ page_results.append(result)
541
+ return page_results
542
+
543
+ slist = [0]
544
+ if max_results:
545
+ max_results = min(max_results, 2023)
546
+ slist.extend(range(23, max_results, 50))
547
+ try:
548
+ for r in self._executor.map(_text_lite_page, slist):
549
+ results.extend(r)
550
+ except Exception as e:
551
+ raise e
552
+
553
+ return list(islice(results, max_results))
554
+
555
+ def images(
556
+ self,
557
+ keywords: str,
558
+ region: str = "wt-wt",
559
+ safesearch: str = "moderate",
560
+ timelimit: str | None = None,
561
+ size: str | None = None,
562
+ color: str | None = None,
563
+ type_image: str | None = None,
564
+ layout: str | None = None,
565
+ license_image: str | None = None,
566
+ max_results: int | None = None,
567
+ ) -> list[dict[str, str]]:
568
+ """webscout images search. Query params: https://duckduckgo.com/params.
569
+
570
+ Args:
571
+ keywords: keywords for query.
572
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
573
+ safesearch: on, moderate, off. Defaults to "moderate".
574
+ timelimit: Day, Week, Month, Year. Defaults to None.
575
+ size: Small, Medium, Large, Wallpaper. Defaults to None.
576
+ color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
577
+ Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
578
+ type_image: photo, clipart, gif, transparent, line.
579
+ Defaults to None.
580
+ layout: Square, Tall, Wide. Defaults to None.
581
+ license_image: any (All Creative Commons), Public (PublicDomain),
582
+ Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
583
+ Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
584
+ Use Commercially). Defaults to None.
585
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
586
+
587
+ Returns:
588
+ List of dictionaries with images search results.
589
+
590
+ Raises:
591
+ WebscoutE: Base exception for webscout errors.
592
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
593
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
594
+ """
595
+ assert keywords, "keywords is mandatory"
596
+
597
+ vqd = self._get_vqd(keywords)
598
+
599
+ safesearch_base = {"on": "1", "moderate": "1", "off": "-1"}
600
+ timelimit = f"time:{timelimit}" if timelimit else ""
601
+ size = f"size:{size}" if size else ""
602
+ color = f"color:{color}" if color else ""
603
+ type_image = f"type:{type_image}" if type_image else ""
604
+ layout = f"layout:{layout}" if layout else ""
605
+ license_image = f"license:{license_image}" if license_image else ""
606
+ payload = {
607
+ "l": region,
608
+ "o": "json",
609
+ "q": keywords,
610
+ "vqd": vqd,
611
+ "f": f"{timelimit},{size},{color},{type_image},{layout},{license_image}",
612
+ "p": safesearch_base[safesearch.lower()],
613
+ }
614
+
615
+ cache = set()
616
+ results: list[dict[str, str]] = []
617
+
618
+ def _images_page(s: int) -> list[dict[str, str]]:
619
+ payload["s"] = f"{s}"
620
+ resp_content = self._get_url("GET", "https://duckduckgo.com/i.js", params=payload)
621
+ resp_json = json_loads(resp_content)
622
+
623
+ page_data = resp_json.get("results", [])
624
+ page_results = []
625
+ for row in page_data:
626
+ image_url = row.get("image")
627
+ if image_url and image_url not in cache:
628
+ cache.add(image_url)
629
+ result = {
630
+ "title": row["title"],
631
+ "image": _normalize_url(image_url),
632
+ "thumbnail": _normalize_url(row["thumbnail"]),
633
+ "url": _normalize_url(row["url"]),
634
+ "height": row["height"],
635
+ "width": row["width"],
636
+ "source": row["source"],
637
+ }
638
+ page_results.append(result)
639
+ return page_results
640
+
641
+ slist = [0]
642
+ if max_results:
643
+ max_results = min(max_results, 500)
644
+ slist.extend(range(100, max_results, 100))
645
+ try:
646
+ for r in self._executor.map(_images_page, slist):
647
+ results.extend(r)
648
+ except Exception as e:
649
+ raise e
650
+
651
+ return list(islice(results, max_results))
652
+
653
+ def videos(
654
+ self,
655
+ keywords: str,
656
+ region: str = "wt-wt",
657
+ safesearch: str = "moderate",
658
+ timelimit: str | None = None,
659
+ resolution: str | None = None,
660
+ duration: str | None = None,
661
+ license_videos: str | None = None,
662
+ max_results: int | None = None,
663
+ ) -> list[dict[str, str]]:
664
+ """webscout videos search. Query params: https://duckduckgo.com/params.
665
+
666
+ Args:
667
+ keywords: keywords for query.
668
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
669
+ safesearch: on, moderate, off. Defaults to "moderate".
670
+ timelimit: d, w, m. Defaults to None.
671
+ resolution: high, standart. Defaults to None.
672
+ duration: short, medium, long. Defaults to None.
673
+ license_videos: creativeCommon, youtube. Defaults to None.
674
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
675
+
676
+ Returns:
677
+ List of dictionaries with videos search results.
678
+
679
+ Raises:
680
+ WebscoutE: Base exception for webscout errors.
681
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
682
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
683
+ """
684
+ assert keywords, "keywords is mandatory"
685
+
686
+ vqd = self._get_vqd(keywords)
687
+
688
+ safesearch_base = {"on": "1", "moderate": "-1", "off": "-2"}
689
+ timelimit = f"publishedAfter:{timelimit}" if timelimit else ""
690
+ resolution = f"videoDefinition:{resolution}" if resolution else ""
691
+ duration = f"videoDuration:{duration}" if duration else ""
692
+ license_videos = f"videoLicense:{license_videos}" if license_videos else ""
693
+ payload = {
694
+ "l": region,
695
+ "o": "json",
696
+ "q": keywords,
697
+ "vqd": vqd,
698
+ "f": f"{timelimit},{resolution},{duration},{license_videos}",
699
+ "p": safesearch_base[safesearch.lower()],
700
+ }
701
+
702
+ cache = set()
703
+ results: list[dict[str, str]] = []
704
+
705
+ def _videos_page(s: int) -> list[dict[str, str]]:
706
+ payload["s"] = f"{s}"
707
+ resp_content = self._get_url("GET", "https://duckduckgo.com/v.js", params=payload)
708
+ resp_json = json_loads(resp_content)
709
+
710
+ page_data = resp_json.get("results", [])
711
+ page_results = []
712
+ for row in page_data:
713
+ if row["content"] not in cache:
714
+ cache.add(row["content"])
715
+ page_results.append(row)
716
+ return page_results
717
+
718
+ slist = [0]
719
+ if max_results:
720
+ max_results = min(max_results, 400)
721
+ slist.extend(range(60, max_results, 60))
722
+ try:
723
+ for r in self._executor.map(_videos_page, slist):
724
+ results.extend(r)
725
+ except Exception as e:
726
+ raise e
727
+
728
+ return list(islice(results, max_results))
729
+
730
+ def news(
731
+ self,
732
+ keywords: str,
733
+ region: str = "wt-wt",
734
+ safesearch: str = "moderate",
735
+ timelimit: str | None = None,
736
+ max_results: int | None = None,
737
+ ) -> list[dict[str, str]]:
738
+ """webscout news search. Query params: https://duckduckgo.com/params.
739
+
740
+ Args:
741
+ keywords: keywords for query.
742
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
743
+ safesearch: on, moderate, off. Defaults to "moderate".
744
+ timelimit: d, w, m. Defaults to None.
745
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
746
+
747
+ Returns:
748
+ List of dictionaries with news search results.
749
+
750
+ Raises:
751
+ WebscoutE: Base exception for webscout errors.
752
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
753
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
754
+ """
755
+ assert keywords, "keywords is mandatory"
756
+
757
+ vqd = self._get_vqd(keywords)
758
+
759
+ safesearch_base = {"on": "1", "moderate": "-1", "off": "-2"}
760
+ payload = {
761
+ "l": region,
762
+ "o": "json",
763
+ "noamp": "1",
764
+ "q": keywords,
765
+ "vqd": vqd,
766
+ "p": safesearch_base[safesearch.lower()],
767
+ }
768
+ if timelimit:
769
+ payload["df"] = timelimit
770
+
771
+ cache = set()
772
+ results: list[dict[str, str]] = []
773
+
774
+ def _news_page(s: int) -> list[dict[str, str]]:
775
+ payload["s"] = f"{s}"
776
+ resp_content = self._get_url("GET", "https://duckduckgo.com/news.js", params=payload)
777
+ resp_json = json_loads(resp_content)
778
+ page_data = resp_json.get("results", [])
779
+ page_results = []
780
+ for row in page_data:
781
+ if row["url"] not in cache:
782
+ cache.add(row["url"])
783
+ image_url = row.get("image", None)
784
+ result = {
785
+ "date": datetime.fromtimestamp(row["date"], timezone.utc).isoformat(),
786
+ "title": row["title"],
787
+ "body": _normalize(row["excerpt"]),
788
+ "url": _normalize_url(row["url"]),
789
+ "image": _normalize_url(image_url),
790
+ "source": row["source"],
791
+ }
792
+ page_results.append(result)
793
+ return page_results
794
+
795
+ slist = [0]
796
+ if max_results:
797
+ max_results = min(max_results, 120)
798
+ slist.extend(range(30, max_results, 30))
799
+ try:
800
+ for r in self._executor.map(_news_page, slist):
801
+ results.extend(r)
802
+ except Exception as e:
803
+ raise e
804
+
805
+ return list(islice(results, max_results))
806
+
807
+ def answers(self, keywords: str) -> list[dict[str, str]]:
808
+ """webscout instant answers. Query params: https://duckduckgo.com/params.
809
+
810
+ Args:
811
+ keywords: keywords for query,
812
+
813
+ Returns:
814
+ List of dictionaries with instant answers results.
815
+
816
+ Raises:
817
+ WebscoutE: Base exception for webscout errors.
818
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
819
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
820
+ """
821
+ assert keywords, "keywords is mandatory"
822
+
823
+ payload = {
824
+ "q": f"what is {keywords}",
825
+ "format": "json",
826
+ }
827
+ resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload)
828
+ page_data = json_loads(resp_content)
829
+
830
+ results = []
831
+ answer = page_data.get("AbstractText")
832
+ url = page_data.get("AbstractURL")
833
+ if answer:
834
+ results.append(
835
+ {
836
+ "icon": None,
837
+ "text": answer,
838
+ "topic": None,
839
+ "url": url,
840
+ }
841
+ )
842
+
843
+ # related
844
+ payload = {
845
+ "q": f"{keywords}",
846
+ "format": "json",
847
+ }
848
+ resp_content = self._get_url("GET", "https://api.duckduckgo.com/", params=payload)
849
+ resp_json = json_loads(resp_content)
850
+ page_data = resp_json.get("RelatedTopics", [])
851
+
852
+ for row in page_data:
853
+ topic = row.get("Name")
854
+ if not topic:
855
+ icon = row["Icon"].get("URL")
856
+ results.append(
857
+ {
858
+ "icon": f"https://duckduckgo.com{icon}" if icon else "",
859
+ "text": row["Text"],
860
+ "topic": None,
861
+ "url": row["FirstURL"],
862
+ }
863
+ )
864
+ else:
865
+ for subrow in row["Topics"]:
866
+ icon = subrow["Icon"].get("URL")
867
+ results.append(
868
+ {
869
+ "icon": f"https://duckduckgo.com{icon}" if icon else "",
870
+ "text": subrow["Text"],
871
+ "topic": topic,
872
+ "url": subrow["FirstURL"],
873
+ }
874
+ )
875
+
876
+ return results
877
+
878
+ def suggestions(self, keywords: str, region: str = "wt-wt") -> list[dict[str, str]]:
879
+ """webscout suggestions. Query params: https://duckduckgo.com/params.
880
+
881
+ Args:
882
+ keywords: keywords for query.
883
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
884
+
885
+ Returns:
886
+ List of dictionaries with suggestions results.
887
+
888
+ Raises:
889
+ WebscoutE: Base exception for webscout errors.
890
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
891
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
892
+ """
893
+ assert keywords, "keywords is mandatory"
894
+
895
+ payload = {
896
+ "q": keywords,
897
+ "kl": region,
898
+ }
899
+ resp_content = self._get_url("GET", "https://duckduckgo.com/ac/", params=payload)
900
+ page_data = json_loads(resp_content)
901
+ return [r for r in page_data]
902
+
903
+ def maps(
904
+ self,
905
+ keywords: str,
906
+ place: str | None = None,
907
+ street: str | None = None,
908
+ city: str | None = None,
909
+ county: str | None = None,
910
+ state: str | None = None,
911
+ country: str | None = None,
912
+ postalcode: str | None = None,
913
+ latitude: str | None = None,
914
+ longitude: str | None = None,
915
+ radius: int = 0,
916
+ max_results: int | None = None,
917
+ ) -> list[dict[str, str]]:
918
+ """webscout maps search. Query params: https://duckduckgo.com/params.
919
+
920
+ Args:
921
+ keywords: keywords for query
922
+ place: if set, the other parameters are not used. Defaults to None.
923
+ street: house number/street. Defaults to None.
924
+ city: city of search. Defaults to None.
925
+ county: county of search. Defaults to None.
926
+ state: state of search. Defaults to None.
927
+ country: country of search. Defaults to None.
928
+ postalcode: postalcode of search. Defaults to None.
929
+ latitude: geographic coordinate (north-south position). Defaults to None.
930
+ longitude: geographic coordinate (east-west position); if latitude and
931
+ longitude are set, the other parameters are not used. Defaults to None.
932
+ radius: expand the search square by the distance in kilometers. Defaults to 0.
933
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
934
+
935
+ Returns:
936
+ List of dictionaries with maps search results, or None if there was an error.
937
+
938
+ Raises:
939
+ WebscoutE: Base exception for webscout errors.
940
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
941
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
942
+ """
943
+ assert keywords, "keywords is mandatory"
944
+
945
+ vqd = self._get_vqd(keywords)
946
+
947
+ # if longitude and latitude are specified, skip the request about bbox to the nominatim api
948
+ if latitude and longitude:
949
+ lat_t = Decimal(latitude.replace(",", "."))
950
+ lat_b = Decimal(latitude.replace(",", "."))
951
+ lon_l = Decimal(longitude.replace(",", "."))
952
+ lon_r = Decimal(longitude.replace(",", "."))
953
+ if radius == 0:
954
+ radius = 1
955
+ # otherwise request about bbox to nominatim api
956
+ else:
957
+ if place:
958
+ params = {
959
+ "q": place,
960
+ "polygon_geojson": "0",
961
+ "format": "jsonv2",
962
+ }
963
+ else:
964
+ params = {
965
+ "polygon_geojson": "0",
966
+ "format": "jsonv2",
967
+ }
968
+ if street:
969
+ params["street"] = street
970
+ if city:
971
+ params["city"] = city
972
+ if county:
973
+ params["county"] = county
974
+ if state:
975
+ params["state"] = state
976
+ if country:
977
+ params["country"] = country
978
+ if postalcode:
979
+ params["postalcode"] = postalcode
980
+ # request nominatim api to get coordinates box
981
+ resp_content = self._get_url(
982
+ "GET",
983
+ "https://nominatim.openstreetmap.org/search.php",
984
+ params=params,
985
+ )
986
+ if resp_content == b"[]":
987
+ raise WebscoutE("maps() Coordinates are not found, check function parameters.")
988
+ resp_json = json_loads(resp_content)
989
+ coordinates = resp_json[0]["boundingbox"]
990
+ lat_t, lon_l = Decimal(coordinates[1]), Decimal(coordinates[2])
991
+ lat_b, lon_r = Decimal(coordinates[0]), Decimal(coordinates[3])
992
+
993
+ # if a radius is specified, expand the search square
994
+ lat_t += Decimal(radius) * Decimal(0.008983)
995
+ lat_b -= Decimal(radius) * Decimal(0.008983)
996
+ lon_l -= Decimal(radius) * Decimal(0.008983)
997
+ lon_r += Decimal(radius) * Decimal(0.008983)
998
+ # logger.debug(f"bbox coordinates\n{lat_t} {lon_l}\n{lat_b} {lon_r}")
999
+
1000
+ cache = set()
1001
+ results: list[dict[str, str]] = []
1002
+
1003
+ def _maps_page(
1004
+ bbox: tuple[Decimal, Decimal, Decimal, Decimal],
1005
+ ) -> list[dict[str, str]] | None:
1006
+ if max_results and len(results) >= max_results:
1007
+ return None
1008
+ lat_t, lon_l, lat_b, lon_r = bbox
1009
+ params = {
1010
+ "q": keywords,
1011
+ "vqd": vqd,
1012
+ "tg": "maps_places",
1013
+ "rt": "D",
1014
+ "mkexp": "b",
1015
+ "wiki_info": "1",
1016
+ "is_requery": "1",
1017
+ "bbox_tl": f"{lat_t},{lon_l}",
1018
+ "bbox_br": f"{lat_b},{lon_r}",
1019
+ "strict_bbox": "1",
1020
+ }
1021
+ resp_content = self._get_url("GET", "https://duckduckgo.com/local.js", params=params)
1022
+ resp_json = json_loads(resp_content)
1023
+ page_data = resp_json.get("results", [])
1024
+
1025
+ page_results = []
1026
+ for res in page_data:
1027
+ r_name = f'{res["name"]} {res["address"]}'
1028
+ if r_name in cache:
1029
+ continue
1030
+ else:
1031
+ cache.add(r_name)
1032
+ result = {
1033
+ "title": res["name"],
1034
+ "address": res["address"],
1035
+ "country_code": res["country_code"],
1036
+ "url": _normalize_url(res["website"]),
1037
+ "phone": res["phone"] or "",
1038
+ "latitude": res["coordinates"]["latitude"],
1039
+ "longitude": res["coordinates"]["longitude"],
1040
+ "source": _normalize_url(res["url"]),
1041
+ "image": x.get("image", "") if (x := res["embed"]) else "",
1042
+ "desc": x.get("description", "") if (x := res["embed"]) else "",
1043
+ "hours": res["hours"] or "",
1044
+ "category": res["ddg_category"] or "",
1045
+ "facebook": f"www.facebook.com/profile.php?id={x}" if (x := res["facebook_id"]) else "",
1046
+ "instagram": f"https://www.instagram.com/{x}" if (x := res["instagram_id"]) else "",
1047
+ "twitter": f"https://twitter.com/{x}" if (x := res["twitter_id"]) else "",
1048
+ }
1049
+ page_results.append(result)
1050
+ return page_results
1051
+
1052
+ # search squares (bboxes)
1053
+ start_bbox = (lat_t, lon_l, lat_b, lon_r)
1054
+ work_bboxes = [start_bbox]
1055
+ while work_bboxes:
1056
+ queue_bboxes = [] # for next iteration, at the end of the iteration work_bboxes = queue_bboxes
1057
+ tasks = []
1058
+ for bbox in work_bboxes:
1059
+ tasks.append(bbox)
1060
+ # if distance between coordinates > 1, divide the square into 4 parts and save them in queue_bboxes
1061
+ if _calculate_distance(lat_t, lon_l, lat_b, lon_r) > 1:
1062
+ lat_t, lon_l, lat_b, lon_r = bbox
1063
+ lat_middle = (lat_t + lat_b) / 2
1064
+ lon_middle = (lon_l + lon_r) / 2
1065
+ bbox1 = (lat_t, lon_l, lat_middle, lon_middle)
1066
+ bbox2 = (lat_t, lon_middle, lat_middle, lon_r)
1067
+ bbox3 = (lat_middle, lon_l, lat_b, lon_middle)
1068
+ bbox4 = (lat_middle, lon_middle, lat_b, lon_r)
1069
+ queue_bboxes.extend([bbox1, bbox2, bbox3, bbox4])
1070
+
1071
+ # gather tasks using asyncio.wait_for and timeout
1072
+ work_bboxes_results = []
1073
+ try:
1074
+ for r in self._executor.map(_maps_page, tasks):
1075
+ if r:
1076
+ work_bboxes_results.extend(r)
1077
+ except Exception as e:
1078
+ raise e
1079
+
1080
+ for x in work_bboxes_results:
1081
+ if isinstance(x, list):
1082
+ results.extend(x)
1083
+ elif isinstance(x, dict):
1084
+ results.append(x)
1085
+
1086
+ work_bboxes = queue_bboxes
1087
+ if not max_results or len(results) >= max_results or len(work_bboxes_results) == 0:
1088
+ break
1089
+
1090
+ return list(islice(results, max_results))
1091
+
1092
+ def translate(self, keywords: list[str] | str, from_: str | None = None, to: str = "en") -> list[dict[str, str]]:
1093
+ """webscout translate.
1094
+
1095
+ Args:
1096
+ keywords: string or list of strings to translate.
1097
+ from_: translate from (defaults automatically). Defaults to None.
1098
+ to: what language to translate. Defaults to "en".
1099
+
1100
+ Returns:
1101
+ List od dictionaries with translated keywords.
1102
+
1103
+ Raises:
1104
+ WebscoutE: Base exception for webscout errors.
1105
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
1106
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
1107
+ """
1108
+ assert keywords, "keywords is mandatory"
1109
+
1110
+ vqd = self._get_vqd("translate")
1111
+
1112
+ payload = {
1113
+ "vqd": vqd,
1114
+ "query": "translate",
1115
+ "to": to,
1116
+ }
1117
+ if from_:
1118
+ payload["from"] = from_
1119
+
1120
+ def _translate_keyword(keyword: str) -> dict[str, str]:
1121
+ resp_content = self._get_url(
1122
+ "POST",
1123
+ "https://duckduckgo.com/translation.js",
1124
+ params=payload,
1125
+ content=keyword.encode(),
1126
+ )
1127
+ page_data: dict[str, str] = json_loads(resp_content)
1128
+ page_data["original"] = keyword
1129
+ return page_data
1130
+
1131
+ if isinstance(keywords, str):
1132
+ keywords = [keywords]
1133
+
1134
+ results = []
1135
+ try:
1136
+ for r in self._executor.map(_translate_keyword, keywords):
1137
+ results.append(r)
1138
+ except Exception as e:
1139
+ raise e
1140
+
1105
1141
  return results