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