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