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,636 +1,636 @@
1
- from __future__ import annotations
2
-
3
- import asyncio
4
- import logging
5
- import os
6
- import warnings
7
- from datetime import datetime, timezone
8
- from functools import cached_property
9
- from itertools import cycle
10
- from random import choice, shuffle
11
- from time import time
12
- from types import TracebackType
13
- from typing import Any, Dict, List, Optional, Type, Union, cast
14
-
15
- import httpx
16
- from lxml.etree import _Element
17
- from lxml.html import HTMLParser as LHTMLParser
18
- from lxml.html import document_fromstring
19
-
20
- from .exceptions import RatelimitE, TimeoutE, WebscoutE
21
- from .utils import (
22
- _expand_proxy_tb_alias,
23
- _extract_vqd,
24
- _normalize,
25
- _normalize_url,
26
- json_loads,
27
- )
28
-
29
- logger = logging.getLogger("webscout.AsyncWEBS")
30
-
31
-
32
- class AsyncWEBS:
33
- """Asynchronous webscout class to get search results."""
34
-
35
- _impersonates = (
36
- "chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107",
37
- "chrome_108", "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118",
38
- "chrome_119", "chrome_120", "chrome_123", "chrome_124", "chrome_126", "chrome_127",
39
- "chrome_128", "chrome_129", "chrome_130", "chrome_131",
40
- "safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_ios_18.1.1",
41
- "safari_15.3", "safari_15.5", "safari_15.6.1", "safari_16", "safari_16.5",
42
- "safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5",
43
- "safari_18", "safari_18.2",
44
- "safari_ipad_18",
45
- "edge_101", "edge_122", "edge_127", "edge_131",
46
- "firefox_109", "firefox_117", "firefox_128", "firefox_133",
47
- )
48
-
49
- def __init__(
50
- self,
51
- headers: Optional[Dict[str, str]] = None,
52
- proxy: Optional[str] = None,
53
- proxies: Union[Dict[str, str], str, None] = None, # deprecated
54
- timeout: Optional[int] = 10,
55
- ) -> None:
56
- """Initialize the AsyncWEBS object.
57
-
58
- Args:
59
- headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
60
- proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
61
- example: "http://user:pass@example.com:3128". Defaults to None.
62
- timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
63
- """
64
- self.proxy: Optional[str] = _expand_proxy_tb_alias(proxy)
65
- assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
66
- if not proxy and proxies:
67
- warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
68
- self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
69
-
70
- default_headers = {
71
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
72
- "Accept-Language": "en-US,en;q=0.5",
73
- "Accept-Encoding": "gzip, deflate, br",
74
- "DNT": "1",
75
- "Connection": "keep-alive",
76
- "Upgrade-Insecure-Requests": "1",
77
- "Sec-Fetch-Dest": "document",
78
- "Sec-Fetch-Mode": "navigate",
79
- "Sec-Fetch-Site": "none",
80
- "Sec-Fetch-User": "?1",
81
- "Referer": "https://duckduckgo.com/",
82
- }
83
-
84
- self.headers = headers if headers else {}
85
- self.headers.update(default_headers)
86
-
87
- self.client = httpx.AsyncClient(
88
- headers=self.headers,
89
- proxies=self.proxy,
90
- timeout=timeout,
91
- follow_redirects=True,
92
- verify=False,
93
- )
94
- self.sleep_timestamp = 0.0
95
-
96
- async def __aenter__(self) -> AsyncWEBS:
97
- return self
98
-
99
- async def __aexit__(
100
- self,
101
- exc_type: Optional[Type[BaseException]] = None,
102
- exc_val: Optional[BaseException] = None,
103
- exc_tb: Optional[TracebackType] = None,
104
- ) -> None:
105
- await self.client.aclose()
106
-
107
- @cached_property
108
- def parser(self) -> LHTMLParser:
109
- """Get HTML parser."""
110
- return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
111
-
112
- async def _sleep(self, sleeptime: float = 2.0) -> None:
113
- """Sleep between API requests."""
114
- delay = sleeptime if not self.sleep_timestamp else sleeptime if time() - self.sleep_timestamp >= 30 else sleeptime * 2
115
- self.sleep_timestamp = time()
116
- await asyncio.sleep(delay)
117
-
118
- async def _get_url(
119
- self,
120
- method: str,
121
- url: str,
122
- params: Optional[Dict[str, str]] = None,
123
- content: Optional[bytes] = None,
124
- data: Optional[Dict[str, str]] = None,
125
- ) -> bytes:
126
- """Make HTTP request with proper rate limiting."""
127
- await self._sleep()
128
- try:
129
- resp = await self.client.request(method, url, params=params, content=content, data=data)
130
-
131
- # Add additional delay if we get a 429 or similar status
132
- if resp.status_code in (429, 403, 503):
133
- await asyncio.sleep(5.0) # Additional delay for rate limit responses
134
- resp = await self.client.request(method, url, params=params, content=content, data=data)
135
-
136
- except Exception as ex:
137
- if "time" in str(ex).lower():
138
- raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
139
- raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
140
-
141
- if resp.status_code == 200:
142
- return resp.content
143
- elif resp.status_code in (202, 301, 403, 429, 503):
144
- raise RatelimitE(f"{url} {resp.status_code} Ratelimit - Please wait a few minutes before retrying")
145
- raise WebscoutE(f"{url} return None. {params=} {content=} {data=}")
146
-
147
- async def achat(self, keywords: str, model: str = "gpt-3.5") -> str:
148
- """Initiates async chat session with webscout AI.
149
-
150
- Args:
151
- keywords (str): The initial message or question to send to the AI.
152
- model (str): The model to use: "gpt-3.5", "claude-3-haiku", "llama-3-70b", "mixtral-8x7b".
153
- Defaults to "gpt-3.5".
154
-
155
- Returns:
156
- str: The response from the AI.
157
- """
158
- result = await self._loop.run_in_executor(self._executor, super().chat, keywords, model)
159
- return result
160
-
161
- async def atext(
162
- self,
163
- keywords: str,
164
- region: str = "wt-wt",
165
- safesearch: str = "moderate",
166
- timelimit: Optional[str] = None,
167
- backend: str = "auto",
168
- max_results: Optional[int] = None,
169
- ) -> List[Dict[str, str]]:
170
- """webscout async text search. Query params: https://duckduckgo.com/params.
171
-
172
- Args:
173
- keywords: keywords for query.
174
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
175
- safesearch: on, moderate, off. Defaults to "moderate".
176
- timelimit: d, w, m, y. Defaults to None.
177
- backend: auto, html, lite. Defaults to auto.
178
- auto - try all backends in random order,
179
- html - collect data from https://html.duckduckgo.com,
180
- lite - collect data from https://lite.duckduckgo.com.
181
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
182
-
183
- Returns:
184
- List of dictionaries with search results.
185
-
186
- Raises:
187
- WebscoutE: Base exception for webscout errors.
188
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
189
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
190
- """
191
- if backend in ("api", "ecosia"):
192
- warnings.warn(f"{backend=} is deprecated, using backend='auto'", stacklevel=2)
193
- backend = "auto"
194
- backends = ["html", "lite"] if backend == "auto" else [backend]
195
- shuffle(backends)
196
-
197
- results, err = [], None
198
- for b in backends:
199
- try:
200
- if b == "html":
201
- results = await self._text_html(keywords, region, timelimit, max_results)
202
- elif b == "lite":
203
- results = await self._text_lite(keywords, region, timelimit, max_results)
204
- return results
205
- except Exception as ex:
206
- err = ex
207
-
208
- raise WebscoutE(err)
209
-
210
- async def _text_html(
211
- self,
212
- keywords: str,
213
- region: str = "wt-wt",
214
- timelimit: Optional[str] = None,
215
- max_results: Optional[int] = None,
216
- ) -> List[Dict[str, str]]:
217
- """HTML backend for text search."""
218
- assert keywords, "keywords is mandatory"
219
-
220
- payload = {
221
- "q": keywords,
222
- "s": "0",
223
- "o": "json",
224
- "api": "d.js",
225
- "vqd": "",
226
- "kl": region,
227
- "bing_market": region,
228
- }
229
- if timelimit:
230
- payload["df"] = timelimit
231
-
232
- cache = set()
233
- results: List[Dict[str, str]] = []
234
-
235
- for _ in range(5):
236
- resp_content = await self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
237
- if b"No results." in resp_content:
238
- return results
239
-
240
- tree = document_fromstring(resp_content, self.parser)
241
- elements = tree.xpath("//div[h2]")
242
- if not isinstance(elements, list):
243
- return results
244
-
245
- for e in elements:
246
- if isinstance(e, _Element):
247
- hrefxpath = e.xpath("./a/@href")
248
- href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
249
- if (
250
- href
251
- and href not in cache
252
- and not href.startswith(
253
- ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
254
- )
255
- ):
256
- cache.add(href)
257
- titlexpath = e.xpath("./h2/a/text()")
258
- title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
259
- bodyxpath = e.xpath("./a//text()")
260
- body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
261
- results.append(
262
- {
263
- "title": _normalize(title),
264
- "href": _normalize_url(href),
265
- "body": _normalize(body),
266
- }
267
- )
268
- if max_results and len(results) >= max_results:
269
- return results
270
-
271
- npx = tree.xpath('.//div[@class="nav-link"]')
272
- if not npx or not max_results:
273
- return results
274
- next_page = npx[-1] if isinstance(npx, list) else None
275
- if isinstance(next_page, _Element):
276
- names = next_page.xpath('.//input[@type="hidden"]/@name')
277
- values = next_page.xpath('.//input[@type="hidden"]/@value')
278
- if isinstance(names, list) and isinstance(values, list):
279
- payload = {str(n): str(v) for n, v in zip(names, values)}
280
-
281
- return results
282
-
283
- async def _text_lite(
284
- self,
285
- keywords: str,
286
- region: str = "wt-wt",
287
- timelimit: Optional[str] = None,
288
- max_results: Optional[int] = None,
289
- ) -> List[Dict[str, str]]:
290
- """Lite backend for text search."""
291
- assert keywords, "keywords is mandatory"
292
-
293
- payload = {
294
- "q": keywords,
295
- "s": "0",
296
- "o": "json",
297
- "api": "d.js",
298
- "vqd": "",
299
- "kl": region,
300
- "bing_market": region,
301
- }
302
- if timelimit:
303
- payload["df"] = timelimit
304
-
305
- cache = set()
306
- results: List[Dict[str, str]] = []
307
-
308
- for _ in range(5):
309
- resp_content = await self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
310
- if b"No more results." in resp_content:
311
- return results
312
-
313
- tree = document_fromstring(resp_content, self.parser)
314
- elements = tree.xpath("//table[last()]//tr")
315
- if not isinstance(elements, list):
316
- return results
317
-
318
- data = zip(cycle(range(1, 5)), elements)
319
- for i, e in data:
320
- if isinstance(e, _Element):
321
- if i == 1:
322
- hrefxpath = e.xpath(".//a//@href")
323
- href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
324
- if (
325
- href is None
326
- or href in cache
327
- or href.startswith(
328
- ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
329
- )
330
- ):
331
- [next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
332
- else:
333
- cache.add(href)
334
- titlexpath = e.xpath(".//a//text()")
335
- title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
336
- elif i == 2:
337
- bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
338
- body = (
339
- "".join(str(x) for x in bodyxpath).strip()
340
- if bodyxpath and isinstance(bodyxpath, list)
341
- else ""
342
- )
343
- if href:
344
- results.append(
345
- {
346
- "title": _normalize(title),
347
- "href": _normalize_url(href),
348
- "body": _normalize(body),
349
- }
350
- )
351
- if max_results and len(results) >= max_results:
352
- return results
353
-
354
- next_page_s = tree.xpath("//form[./input[contains(@value, 'ext')]]/input[@name='s']/@value")
355
- if not next_page_s or not max_results:
356
- return results
357
- elif isinstance(next_page_s, list):
358
- payload["s"] = str(next_page_s[0])
359
-
360
- return results
361
-
362
- async def aimages(
363
- self,
364
- keywords: str,
365
- region: str = "wt-wt",
366
- safesearch: str = "moderate",
367
- timelimit: Optional[str] = None,
368
- size: Optional[str] = None,
369
- color: Optional[str] = None,
370
- type_image: Optional[str] = None,
371
- layout: Optional[str] = None,
372
- license_image: Optional[str] = None,
373
- max_results: Optional[int] = None,
374
- ) -> List[Dict[str, str]]:
375
- """webscout async images search. Query params: https://duckduckgo.com/params.
376
-
377
- Args:
378
- keywords: keywords for query.
379
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
380
- safesearch: on, moderate, off. Defaults to "moderate".
381
- timelimit: Day, Week, Month, Year. Defaults to None.
382
- size: Small, Medium, Large, Wallpaper. Defaults to None.
383
- color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
384
- Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
385
- type_image: photo, clipart, gif, transparent, line.
386
- Defaults to None.
387
- layout: Square, Tall, Wide. Defaults to None.
388
- license_image: any (All Creative Commons), Public (PublicDomain),
389
- Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
390
- Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
391
- Use Commercially). Defaults to None.
392
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
393
-
394
- Returns:
395
- List of dictionaries with images search results.
396
-
397
- Raises:
398
- WebscoutE: Base exception for webscout errors.
399
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
400
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
401
- """
402
- result = await self._loop.run_in_executor(
403
- self._executor,
404
- super().images,
405
- keywords,
406
- region,
407
- safesearch,
408
- timelimit,
409
- size,
410
- color,
411
- type_image,
412
- layout,
413
- license_image,
414
- max_results,
415
- )
416
- return result
417
-
418
- async def avideos(
419
- self,
420
- keywords: str,
421
- region: str = "wt-wt",
422
- safesearch: str = "moderate",
423
- timelimit: Optional[str] = None,
424
- resolution: Optional[str] = None,
425
- duration: Optional[str] = None,
426
- license_videos: Optional[str] = None,
427
- max_results: Optional[int] = None,
428
- ) -> List[Dict[str, str]]:
429
- """webscout async videos search. Query params: https://duckduckgo.com/params.
430
-
431
- Args:
432
- keywords: keywords for query.
433
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
434
- safesearch: on, moderate, off. Defaults to "moderate".
435
- timelimit: d, w, m. Defaults to None.
436
- resolution: high, standart. Defaults to None.
437
- duration: short, medium, long. Defaults to None.
438
- license_videos: creativeCommon, youtube. Defaults to None.
439
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
440
-
441
- Returns:
442
- List of dictionaries with videos search results.
443
-
444
- Raises:
445
- WebscoutE: Base exception for webscout errors.
446
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
447
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
448
- """
449
- result = await self._loop.run_in_executor(
450
- self._executor,
451
- super().videos,
452
- keywords,
453
- region,
454
- safesearch,
455
- timelimit,
456
- resolution,
457
- duration,
458
- license_videos,
459
- max_results,
460
- )
461
- return result
462
-
463
- async def anews(
464
- self,
465
- keywords: str,
466
- region: str = "wt-wt",
467
- safesearch: str = "moderate",
468
- timelimit: Optional[str] = None,
469
- max_results: Optional[int] = None,
470
- ) -> List[Dict[str, str]]:
471
- """webscout async news search. Query params: https://duckduckgo.com/params.
472
-
473
- Args:
474
- keywords: keywords for query.
475
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
476
- safesearch: on, moderate, off. Defaults to "moderate".
477
- timelimit: d, w, m. Defaults to None.
478
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
479
-
480
- Returns:
481
- List of dictionaries with news search results.
482
-
483
- Raises:
484
- WebscoutE: Base exception for webscout errors.
485
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
486
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
487
- """
488
- result = await self._loop.run_in_executor(
489
- self._executor,
490
- super().news,
491
- keywords,
492
- region,
493
- safesearch,
494
- timelimit,
495
- max_results,
496
- )
497
- return result
498
-
499
- async def aanswers(
500
- self,
501
- keywords: str,
502
- ) -> List[Dict[str, str]]:
503
- """webscout async instant answers. Query params: https://duckduckgo.com/params.
504
-
505
- Args:
506
- keywords: keywords for query,
507
-
508
- Returns:
509
- List of dictionaries with instant answers results.
510
-
511
- Raises:
512
- WebscoutE: Base exception for webscout errors.
513
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
514
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
515
- """
516
- result = await self._loop.run_in_executor(
517
- self._executor,
518
- super().answers,
519
- keywords,
520
- )
521
- return result
522
-
523
- async def asuggestions(
524
- self,
525
- keywords: str,
526
- region: str = "wt-wt",
527
- ) -> List[Dict[str, str]]:
528
- """webscout async suggestions. Query params: https://duckduckgo.com/params.
529
-
530
- Args:
531
- keywords: keywords for query.
532
- region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
533
-
534
- Returns:
535
- List of dictionaries with suggestions results.
536
-
537
- Raises:
538
- WebscoutE: Base exception for webscout errors.
539
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
540
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
541
- """
542
- result = await self._loop.run_in_executor(
543
- self._executor,
544
- super().suggestions,
545
- keywords,
546
- region,
547
- )
548
- return result
549
-
550
- async def amaps(
551
- self,
552
- keywords: str,
553
- place: Optional[str] = None,
554
- street: Optional[str] = None,
555
- city: Optional[str] = None,
556
- county: Optional[str] = None,
557
- state: Optional[str] = None,
558
- country: Optional[str] = None,
559
- postalcode: Optional[str] = None,
560
- latitude: Optional[str] = None,
561
- longitude: Optional[str] = None,
562
- radius: int = 0,
563
- max_results: Optional[int] = None,
564
- ) -> List[Dict[str, str]]:
565
- """webscout async maps search. Query params: https://duckduckgo.com/params.
566
-
567
- Args:
568
- keywords: keywords for query
569
- place: if set, the other parameters are not used. Defaults to None.
570
- street: house number/street. Defaults to None.
571
- city: city of search. Defaults to None.
572
- county: county of search. Defaults to None.
573
- state: state of search. Defaults to None.
574
- country: country of search. Defaults to None.
575
- postalcode: postalcode of search. Defaults to None.
576
- latitude: geographic coordinate (north-south position). Defaults to None.
577
- longitude: geographic coordinate (east-west position); if latitude and
578
- longitude are set, the other parameters are not used. Defaults to None.
579
- radius: expand the search square by the distance in kilometers. Defaults to 0.
580
- max_results: max number of results. If None, returns results only from the first response. Defaults to None.
581
-
582
- Returns:
583
- List of dictionaries with maps search results, or None if there was an error.
584
-
585
- Raises:
586
- WebscoutE: Base exception for webscout errors.
587
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
588
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
589
- """
590
- result = await self._loop.run_in_executor(
591
- self._executor,
592
- super().maps,
593
- keywords,
594
- place,
595
- street,
596
- city,
597
- county,
598
- state,
599
- country,
600
- postalcode,
601
- latitude,
602
- longitude,
603
- radius,
604
- max_results,
605
- )
606
- return result
607
-
608
- async def atranslate(
609
- self,
610
- keywords: Union[List[str], str],
611
- from_: Optional[str] = None,
612
- to: str = "en",
613
- ) -> List[Dict[str, str]]:
614
- """webscout async translate.
615
-
616
- Args:
617
- keywords: string or list of strings to translate.
618
- from_: translate from (defaults automatically). Defaults to None.
619
- to: what language to translate. Defaults to "en".
620
-
621
- Returns:
622
- List od dictionaries with translated keywords.
623
-
624
- Raises:
625
- WebscoutE: Base exception for webscout errors.
626
- RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
627
- TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
628
- """
629
- result = await self._loop.run_in_executor(
630
- self._executor,
631
- super().translate,
632
- keywords,
633
- from_,
634
- to,
635
- )
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import logging
5
+ import os
6
+ import warnings
7
+ from datetime import datetime, timezone
8
+ from functools import cached_property
9
+ from itertools import cycle
10
+ from random import choice, shuffle
11
+ from time import time
12
+ from types import TracebackType
13
+ from typing import Any, Dict, List, Optional, Type, Union, cast
14
+
15
+ import httpx
16
+ from lxml.etree import _Element
17
+ from lxml.html import HTMLParser as LHTMLParser
18
+ from lxml.html import document_fromstring
19
+
20
+ from .exceptions import RatelimitE, TimeoutE, WebscoutE
21
+ from .utils import (
22
+ _expand_proxy_tb_alias,
23
+ _extract_vqd,
24
+ _normalize,
25
+ _normalize_url,
26
+ json_loads,
27
+ )
28
+
29
+ logger = logging.getLogger("webscout.AsyncWEBS")
30
+
31
+
32
+ class AsyncWEBS:
33
+ """Asynchronous webscout class to get search results."""
34
+
35
+ _impersonates = (
36
+ "chrome_100", "chrome_101", "chrome_104", "chrome_105", "chrome_106", "chrome_107",
37
+ "chrome_108", "chrome_109", "chrome_114", "chrome_116", "chrome_117", "chrome_118",
38
+ "chrome_119", "chrome_120", "chrome_123", "chrome_124", "chrome_126", "chrome_127",
39
+ "chrome_128", "chrome_129", "chrome_130", "chrome_131",
40
+ "safari_ios_16.5", "safari_ios_17.2", "safari_ios_17.4.1", "safari_ios_18.1.1",
41
+ "safari_15.3", "safari_15.5", "safari_15.6.1", "safari_16", "safari_16.5",
42
+ "safari_17.0", "safari_17.2.1", "safari_17.4.1", "safari_17.5",
43
+ "safari_18", "safari_18.2",
44
+ "safari_ipad_18",
45
+ "edge_101", "edge_122", "edge_127", "edge_131",
46
+ "firefox_109", "firefox_117", "firefox_128", "firefox_133",
47
+ )
48
+
49
+ def __init__(
50
+ self,
51
+ headers: Optional[Dict[str, str]] = None,
52
+ proxy: Optional[str] = None,
53
+ proxies: Union[Dict[str, str], str, None] = None, # deprecated
54
+ timeout: Optional[int] = 10,
55
+ ) -> None:
56
+ """Initialize the AsyncWEBS object.
57
+
58
+ Args:
59
+ headers (dict, optional): Dictionary of headers for the HTTP client. Defaults to None.
60
+ proxy (str, optional): proxy for the HTTP client, supports http/https/socks5 protocols.
61
+ example: "http://user:pass@example.com:3128". Defaults to None.
62
+ timeout (int, optional): Timeout value for the HTTP client. Defaults to 10.
63
+ """
64
+ self.proxy: Optional[str] = _expand_proxy_tb_alias(proxy)
65
+ assert self.proxy is None or isinstance(self.proxy, str), "proxy must be a str"
66
+ if not proxy and proxies:
67
+ warnings.warn("'proxies' is deprecated, use 'proxy' instead.", stacklevel=1)
68
+ self.proxy = proxies.get("http") or proxies.get("https") if isinstance(proxies, dict) else proxies
69
+
70
+ default_headers = {
71
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
72
+ "Accept-Language": "en-US,en;q=0.5",
73
+ "Accept-Encoding": "gzip, deflate, br",
74
+ "DNT": "1",
75
+ "Connection": "keep-alive",
76
+ "Upgrade-Insecure-Requests": "1",
77
+ "Sec-Fetch-Dest": "document",
78
+ "Sec-Fetch-Mode": "navigate",
79
+ "Sec-Fetch-Site": "none",
80
+ "Sec-Fetch-User": "?1",
81
+ "Referer": "https://duckduckgo.com/",
82
+ }
83
+
84
+ self.headers = headers if headers else {}
85
+ self.headers.update(default_headers)
86
+
87
+ self.client = httpx.AsyncClient(
88
+ headers=self.headers,
89
+ proxies=self.proxy,
90
+ timeout=timeout,
91
+ follow_redirects=True,
92
+ verify=False,
93
+ )
94
+ self.sleep_timestamp = 0.0
95
+
96
+ async def __aenter__(self) -> AsyncWEBS:
97
+ return self
98
+
99
+ async def __aexit__(
100
+ self,
101
+ exc_type: Optional[Type[BaseException]] = None,
102
+ exc_val: Optional[BaseException] = None,
103
+ exc_tb: Optional[TracebackType] = None,
104
+ ) -> None:
105
+ await self.client.aclose()
106
+
107
+ @cached_property
108
+ def parser(self) -> LHTMLParser:
109
+ """Get HTML parser."""
110
+ return LHTMLParser(remove_blank_text=True, remove_comments=True, remove_pis=True, collect_ids=False)
111
+
112
+ async def _sleep(self, sleeptime: float = 2.0) -> None:
113
+ """Sleep between API requests."""
114
+ delay = sleeptime if not self.sleep_timestamp else sleeptime if time() - self.sleep_timestamp >= 30 else sleeptime * 2
115
+ self.sleep_timestamp = time()
116
+ await asyncio.sleep(delay)
117
+
118
+ async def _get_url(
119
+ self,
120
+ method: str,
121
+ url: str,
122
+ params: Optional[Dict[str, str]] = None,
123
+ content: Optional[bytes] = None,
124
+ data: Optional[Dict[str, str]] = None,
125
+ ) -> bytes:
126
+ """Make HTTP request with proper rate limiting."""
127
+ await self._sleep()
128
+ try:
129
+ resp = await self.client.request(method, url, params=params, content=content, data=data)
130
+
131
+ # Add additional delay if we get a 429 or similar status
132
+ if resp.status_code in (429, 403, 503):
133
+ await asyncio.sleep(5.0) # Additional delay for rate limit responses
134
+ resp = await self.client.request(method, url, params=params, content=content, data=data)
135
+
136
+ except Exception as ex:
137
+ if "time" in str(ex).lower():
138
+ raise TimeoutE(f"{url} {type(ex).__name__}: {ex}") from ex
139
+ raise WebscoutE(f"{url} {type(ex).__name__}: {ex}") from ex
140
+
141
+ if resp.status_code == 200:
142
+ return resp.content
143
+ elif resp.status_code in (202, 301, 403, 429, 503):
144
+ raise RatelimitE(f"{url} {resp.status_code} Ratelimit - Please wait a few minutes before retrying")
145
+ raise WebscoutE(f"{url} return None. {params=} {content=} {data=}")
146
+
147
+ async def achat(self, keywords: str, model: str = "gpt-4o-mini") -> str:
148
+ """Initiates async chat session with webscout AI.
149
+
150
+ Args:
151
+ keywords (str): The initial message or question to send to the AI.
152
+ model (str): The model to use: "gpt-4o-mini", "claude-3-haiku", "llama-3-70b", "mixtral-8x7b", "o3-mini".
153
+ Defaults to "gpt-4o-mini".
154
+
155
+ Returns:
156
+ str: The response from the AI.
157
+ """
158
+ result = await self._loop.run_in_executor(self._executor, super().chat, keywords, model)
159
+ return result
160
+
161
+ async def atext(
162
+ self,
163
+ keywords: str,
164
+ region: str = "wt-wt",
165
+ safesearch: str = "moderate",
166
+ timelimit: Optional[str] = None,
167
+ backend: str = "auto",
168
+ max_results: Optional[int] = None,
169
+ ) -> List[Dict[str, str]]:
170
+ """webscout async text search. Query params: https://duckduckgo.com/params.
171
+
172
+ Args:
173
+ keywords: keywords for query.
174
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
175
+ safesearch: on, moderate, off. Defaults to "moderate".
176
+ timelimit: d, w, m, y. Defaults to None.
177
+ backend: auto, html, lite. Defaults to auto.
178
+ auto - try all backends in random order,
179
+ html - collect data from https://html.duckduckgo.com,
180
+ lite - collect data from https://lite.duckduckgo.com.
181
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
182
+
183
+ Returns:
184
+ List of dictionaries with search results.
185
+
186
+ Raises:
187
+ WebscoutE: Base exception for webscout errors.
188
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
189
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
190
+ """
191
+ if backend in ("api", "ecosia"):
192
+ warnings.warn(f"{backend=} is deprecated, using backend='auto'", stacklevel=2)
193
+ backend = "auto"
194
+ backends = ["html", "lite"] if backend == "auto" else [backend]
195
+ shuffle(backends)
196
+
197
+ results, err = [], None
198
+ for b in backends:
199
+ try:
200
+ if b == "html":
201
+ results = await self._text_html(keywords, region, timelimit, max_results)
202
+ elif b == "lite":
203
+ results = await self._text_lite(keywords, region, timelimit, max_results)
204
+ return results
205
+ except Exception as ex:
206
+ err = ex
207
+
208
+ raise WebscoutE(err)
209
+
210
+ async def _text_html(
211
+ self,
212
+ keywords: str,
213
+ region: str = "wt-wt",
214
+ timelimit: Optional[str] = None,
215
+ max_results: Optional[int] = None,
216
+ ) -> List[Dict[str, str]]:
217
+ """HTML backend for text search."""
218
+ assert keywords, "keywords is mandatory"
219
+
220
+ payload = {
221
+ "q": keywords,
222
+ "s": "0",
223
+ "o": "json",
224
+ "api": "d.js",
225
+ "vqd": "",
226
+ "kl": region,
227
+ "bing_market": region,
228
+ }
229
+ if timelimit:
230
+ payload["df"] = timelimit
231
+
232
+ cache = set()
233
+ results: List[Dict[str, str]] = []
234
+
235
+ for _ in range(5):
236
+ resp_content = await self._get_url("POST", "https://html.duckduckgo.com/html", data=payload)
237
+ if b"No results." in resp_content:
238
+ return results
239
+
240
+ tree = document_fromstring(resp_content, self.parser)
241
+ elements = tree.xpath("//div[h2]")
242
+ if not isinstance(elements, list):
243
+ return results
244
+
245
+ for e in elements:
246
+ if isinstance(e, _Element):
247
+ hrefxpath = e.xpath("./a/@href")
248
+ href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
249
+ if (
250
+ href
251
+ and href not in cache
252
+ and not href.startswith(
253
+ ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
254
+ )
255
+ ):
256
+ cache.add(href)
257
+ titlexpath = e.xpath("./h2/a/text()")
258
+ title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
259
+ bodyxpath = e.xpath("./a//text()")
260
+ body = "".join(str(x) for x in bodyxpath) if bodyxpath and isinstance(bodyxpath, list) else ""
261
+ results.append(
262
+ {
263
+ "title": _normalize(title),
264
+ "href": _normalize_url(href),
265
+ "body": _normalize(body),
266
+ }
267
+ )
268
+ if max_results and len(results) >= max_results:
269
+ return results
270
+
271
+ npx = tree.xpath('.//div[@class="nav-link"]')
272
+ if not npx or not max_results:
273
+ return results
274
+ next_page = npx[-1] if isinstance(npx, list) else None
275
+ if isinstance(next_page, _Element):
276
+ names = next_page.xpath('.//input[@type="hidden"]/@name')
277
+ values = next_page.xpath('.//input[@type="hidden"]/@value')
278
+ if isinstance(names, list) and isinstance(values, list):
279
+ payload = {str(n): str(v) for n, v in zip(names, values)}
280
+
281
+ return results
282
+
283
+ async def _text_lite(
284
+ self,
285
+ keywords: str,
286
+ region: str = "wt-wt",
287
+ timelimit: Optional[str] = None,
288
+ max_results: Optional[int] = None,
289
+ ) -> List[Dict[str, str]]:
290
+ """Lite backend for text search."""
291
+ assert keywords, "keywords is mandatory"
292
+
293
+ payload = {
294
+ "q": keywords,
295
+ "s": "0",
296
+ "o": "json",
297
+ "api": "d.js",
298
+ "vqd": "",
299
+ "kl": region,
300
+ "bing_market": region,
301
+ }
302
+ if timelimit:
303
+ payload["df"] = timelimit
304
+
305
+ cache = set()
306
+ results: List[Dict[str, str]] = []
307
+
308
+ for _ in range(5):
309
+ resp_content = await self._get_url("POST", "https://lite.duckduckgo.com/lite/", data=payload)
310
+ if b"No more results." in resp_content:
311
+ return results
312
+
313
+ tree = document_fromstring(resp_content, self.parser)
314
+ elements = tree.xpath("//table[last()]//tr")
315
+ if not isinstance(elements, list):
316
+ return results
317
+
318
+ data = zip(cycle(range(1, 5)), elements)
319
+ for i, e in data:
320
+ if isinstance(e, _Element):
321
+ if i == 1:
322
+ hrefxpath = e.xpath(".//a//@href")
323
+ href = str(hrefxpath[0]) if hrefxpath and isinstance(hrefxpath, list) else None
324
+ if (
325
+ href is None
326
+ or href in cache
327
+ or href.startswith(
328
+ ("http://www.google.com/search?q=", "https://duckduckgo.com/y.js?ad_domain")
329
+ )
330
+ ):
331
+ [next(data, None) for _ in range(3)] # skip block(i=1,2,3,4)
332
+ else:
333
+ cache.add(href)
334
+ titlexpath = e.xpath(".//a//text()")
335
+ title = str(titlexpath[0]) if titlexpath and isinstance(titlexpath, list) else ""
336
+ elif i == 2:
337
+ bodyxpath = e.xpath(".//td[@class='result-snippet']//text()")
338
+ body = (
339
+ "".join(str(x) for x in bodyxpath).strip()
340
+ if bodyxpath and isinstance(bodyxpath, list)
341
+ else ""
342
+ )
343
+ if href:
344
+ results.append(
345
+ {
346
+ "title": _normalize(title),
347
+ "href": _normalize_url(href),
348
+ "body": _normalize(body),
349
+ }
350
+ )
351
+ if max_results and len(results) >= max_results:
352
+ return results
353
+
354
+ next_page_s = tree.xpath("//form[./input[contains(@value, 'ext')]]/input[@name='s']/@value")
355
+ if not next_page_s or not max_results:
356
+ return results
357
+ elif isinstance(next_page_s, list):
358
+ payload["s"] = str(next_page_s[0])
359
+
360
+ return results
361
+
362
+ async def aimages(
363
+ self,
364
+ keywords: str,
365
+ region: str = "wt-wt",
366
+ safesearch: str = "moderate",
367
+ timelimit: Optional[str] = None,
368
+ size: Optional[str] = None,
369
+ color: Optional[str] = None,
370
+ type_image: Optional[str] = None,
371
+ layout: Optional[str] = None,
372
+ license_image: Optional[str] = None,
373
+ max_results: Optional[int] = None,
374
+ ) -> List[Dict[str, str]]:
375
+ """webscout async images search. Query params: https://duckduckgo.com/params.
376
+
377
+ Args:
378
+ keywords: keywords for query.
379
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
380
+ safesearch: on, moderate, off. Defaults to "moderate".
381
+ timelimit: Day, Week, Month, Year. Defaults to None.
382
+ size: Small, Medium, Large, Wallpaper. Defaults to None.
383
+ color: color, Monochrome, Red, Orange, Yellow, Green, Blue,
384
+ Purple, Pink, Brown, Black, Gray, Teal, White. Defaults to None.
385
+ type_image: photo, clipart, gif, transparent, line.
386
+ Defaults to None.
387
+ layout: Square, Tall, Wide. Defaults to None.
388
+ license_image: any (All Creative Commons), Public (PublicDomain),
389
+ Share (Free to Share and Use), ShareCommercially (Free to Share and Use Commercially),
390
+ Modify (Free to Modify, Share, and Use), ModifyCommercially (Free to Modify, Share, and
391
+ Use Commercially). Defaults to None.
392
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
393
+
394
+ Returns:
395
+ List of dictionaries with images search results.
396
+
397
+ Raises:
398
+ WebscoutE: Base exception for webscout errors.
399
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
400
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
401
+ """
402
+ result = await self._loop.run_in_executor(
403
+ self._executor,
404
+ super().images,
405
+ keywords,
406
+ region,
407
+ safesearch,
408
+ timelimit,
409
+ size,
410
+ color,
411
+ type_image,
412
+ layout,
413
+ license_image,
414
+ max_results,
415
+ )
416
+ return result
417
+
418
+ async def avideos(
419
+ self,
420
+ keywords: str,
421
+ region: str = "wt-wt",
422
+ safesearch: str = "moderate",
423
+ timelimit: Optional[str] = None,
424
+ resolution: Optional[str] = None,
425
+ duration: Optional[str] = None,
426
+ license_videos: Optional[str] = None,
427
+ max_results: Optional[int] = None,
428
+ ) -> List[Dict[str, str]]:
429
+ """webscout async videos search. Query params: https://duckduckgo.com/params.
430
+
431
+ Args:
432
+ keywords: keywords for query.
433
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
434
+ safesearch: on, moderate, off. Defaults to "moderate".
435
+ timelimit: d, w, m. Defaults to None.
436
+ resolution: high, standart. Defaults to None.
437
+ duration: short, medium, long. Defaults to None.
438
+ license_videos: creativeCommon, youtube. Defaults to None.
439
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
440
+
441
+ Returns:
442
+ List of dictionaries with videos search results.
443
+
444
+ Raises:
445
+ WebscoutE: Base exception for webscout errors.
446
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
447
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
448
+ """
449
+ result = await self._loop.run_in_executor(
450
+ self._executor,
451
+ super().videos,
452
+ keywords,
453
+ region,
454
+ safesearch,
455
+ timelimit,
456
+ resolution,
457
+ duration,
458
+ license_videos,
459
+ max_results,
460
+ )
461
+ return result
462
+
463
+ async def anews(
464
+ self,
465
+ keywords: str,
466
+ region: str = "wt-wt",
467
+ safesearch: str = "moderate",
468
+ timelimit: Optional[str] = None,
469
+ max_results: Optional[int] = None,
470
+ ) -> List[Dict[str, str]]:
471
+ """webscout async news search. Query params: https://duckduckgo.com/params.
472
+
473
+ Args:
474
+ keywords: keywords for query.
475
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
476
+ safesearch: on, moderate, off. Defaults to "moderate".
477
+ timelimit: d, w, m. Defaults to None.
478
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
479
+
480
+ Returns:
481
+ List of dictionaries with news search results.
482
+
483
+ Raises:
484
+ WebscoutE: Base exception for webscout errors.
485
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
486
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
487
+ """
488
+ result = await self._loop.run_in_executor(
489
+ self._executor,
490
+ super().news,
491
+ keywords,
492
+ region,
493
+ safesearch,
494
+ timelimit,
495
+ max_results,
496
+ )
497
+ return result
498
+
499
+ async def aanswers(
500
+ self,
501
+ keywords: str,
502
+ ) -> List[Dict[str, str]]:
503
+ """webscout async instant answers. Query params: https://duckduckgo.com/params.
504
+
505
+ Args:
506
+ keywords: keywords for query,
507
+
508
+ Returns:
509
+ List of dictionaries with instant answers results.
510
+
511
+ Raises:
512
+ WebscoutE: Base exception for webscout errors.
513
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
514
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
515
+ """
516
+ result = await self._loop.run_in_executor(
517
+ self._executor,
518
+ super().answers,
519
+ keywords,
520
+ )
521
+ return result
522
+
523
+ async def asuggestions(
524
+ self,
525
+ keywords: str,
526
+ region: str = "wt-wt",
527
+ ) -> List[Dict[str, str]]:
528
+ """webscout async suggestions. Query params: https://duckduckgo.com/params.
529
+
530
+ Args:
531
+ keywords: keywords for query.
532
+ region: wt-wt, us-en, uk-en, ru-ru, etc. Defaults to "wt-wt".
533
+
534
+ Returns:
535
+ List of dictionaries with suggestions results.
536
+
537
+ Raises:
538
+ WebscoutE: Base exception for webscout errors.
539
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
540
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
541
+ """
542
+ result = await self._loop.run_in_executor(
543
+ self._executor,
544
+ super().suggestions,
545
+ keywords,
546
+ region,
547
+ )
548
+ return result
549
+
550
+ async def amaps(
551
+ self,
552
+ keywords: str,
553
+ place: Optional[str] = None,
554
+ street: Optional[str] = None,
555
+ city: Optional[str] = None,
556
+ county: Optional[str] = None,
557
+ state: Optional[str] = None,
558
+ country: Optional[str] = None,
559
+ postalcode: Optional[str] = None,
560
+ latitude: Optional[str] = None,
561
+ longitude: Optional[str] = None,
562
+ radius: int = 0,
563
+ max_results: Optional[int] = None,
564
+ ) -> List[Dict[str, str]]:
565
+ """webscout async maps search. Query params: https://duckduckgo.com/params.
566
+
567
+ Args:
568
+ keywords: keywords for query
569
+ place: if set, the other parameters are not used. Defaults to None.
570
+ street: house number/street. Defaults to None.
571
+ city: city of search. Defaults to None.
572
+ county: county of search. Defaults to None.
573
+ state: state of search. Defaults to None.
574
+ country: country of search. Defaults to None.
575
+ postalcode: postalcode of search. Defaults to None.
576
+ latitude: geographic coordinate (north-south position). Defaults to None.
577
+ longitude: geographic coordinate (east-west position); if latitude and
578
+ longitude are set, the other parameters are not used. Defaults to None.
579
+ radius: expand the search square by the distance in kilometers. Defaults to 0.
580
+ max_results: max number of results. If None, returns results only from the first response. Defaults to None.
581
+
582
+ Returns:
583
+ List of dictionaries with maps search results, or None if there was an error.
584
+
585
+ Raises:
586
+ WebscoutE: Base exception for webscout errors.
587
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
588
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
589
+ """
590
+ result = await self._loop.run_in_executor(
591
+ self._executor,
592
+ super().maps,
593
+ keywords,
594
+ place,
595
+ street,
596
+ city,
597
+ county,
598
+ state,
599
+ country,
600
+ postalcode,
601
+ latitude,
602
+ longitude,
603
+ radius,
604
+ max_results,
605
+ )
606
+ return result
607
+
608
+ async def atranslate(
609
+ self,
610
+ keywords: Union[List[str], str],
611
+ from_: Optional[str] = None,
612
+ to: str = "en",
613
+ ) -> List[Dict[str, str]]:
614
+ """webscout async translate.
615
+
616
+ Args:
617
+ keywords: string or list of strings to translate.
618
+ from_: translate from (defaults automatically). Defaults to None.
619
+ to: what language to translate. Defaults to "en".
620
+
621
+ Returns:
622
+ List od dictionaries with translated keywords.
623
+
624
+ Raises:
625
+ WebscoutE: Base exception for webscout errors.
626
+ RatelimitE: Inherits from WebscoutE, raised for exceeding API request rate limits.
627
+ TimeoutE: Inherits from WebscoutE, raised for API request timeouts.
628
+ """
629
+ result = await self._loop.run_in_executor(
630
+ self._executor,
631
+ super().translate,
632
+ keywords,
633
+ from_,
634
+ to,
635
+ )
636
636
  return result