webscout 6.9__py3-none-any.whl → 7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


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

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