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.
- webscout/AIauto.py +191 -191
- webscout/AIbase.py +122 -122
- webscout/AIutel.py +440 -440
- webscout/Bard.py +343 -161
- webscout/DWEBS.py +489 -492
- webscout/Extra/YTToolkit/YTdownloader.py +995 -995
- webscout/Extra/YTToolkit/__init__.py +2 -2
- webscout/Extra/YTToolkit/transcriber.py +476 -479
- webscout/Extra/YTToolkit/ytapi/channel.py +307 -307
- webscout/Extra/YTToolkit/ytapi/playlist.py +58 -58
- webscout/Extra/YTToolkit/ytapi/pool.py +7 -7
- webscout/Extra/YTToolkit/ytapi/utils.py +62 -62
- webscout/Extra/YTToolkit/ytapi/video.py +103 -103
- webscout/Extra/autocoder/__init__.py +9 -9
- webscout/Extra/autocoder/autocoder_utiles.py +199 -199
- webscout/Extra/autocoder/rawdog.py +5 -7
- webscout/Extra/autollama.py +230 -230
- webscout/Extra/gguf.py +3 -3
- webscout/Extra/weather.py +171 -171
- webscout/LLM.py +442 -442
- webscout/Litlogger/__init__.py +67 -681
- webscout/Litlogger/core/__init__.py +6 -0
- webscout/Litlogger/core/level.py +20 -0
- webscout/Litlogger/core/logger.py +123 -0
- webscout/Litlogger/handlers/__init__.py +12 -0
- webscout/Litlogger/handlers/console.py +50 -0
- webscout/Litlogger/handlers/file.py +143 -0
- webscout/Litlogger/handlers/network.py +174 -0
- webscout/Litlogger/styles/__init__.py +7 -0
- webscout/Litlogger/styles/colors.py +231 -0
- webscout/Litlogger/styles/formats.py +377 -0
- webscout/Litlogger/styles/text.py +87 -0
- webscout/Litlogger/utils/__init__.py +6 -0
- webscout/Litlogger/utils/detectors.py +154 -0
- webscout/Litlogger/utils/formatters.py +200 -0
- webscout/Provider/AISEARCH/DeepFind.py +250 -250
- webscout/Provider/Blackboxai.py +136 -137
- webscout/Provider/ChatGPTGratis.py +226 -0
- webscout/Provider/Cloudflare.py +91 -78
- webscout/Provider/DeepSeek.py +218 -0
- webscout/Provider/Deepinfra.py +59 -35
- webscout/Provider/Free2GPT.py +131 -124
- webscout/Provider/Gemini.py +100 -115
- webscout/Provider/Glider.py +74 -59
- webscout/Provider/Groq.py +30 -18
- webscout/Provider/Jadve.py +108 -77
- webscout/Provider/Llama3.py +117 -94
- webscout/Provider/Marcus.py +191 -137
- webscout/Provider/Netwrck.py +62 -50
- webscout/Provider/PI.py +79 -124
- webscout/Provider/PizzaGPT.py +129 -83
- webscout/Provider/QwenLM.py +311 -0
- webscout/Provider/TTI/AiForce/__init__.py +22 -22
- webscout/Provider/TTI/AiForce/async_aiforce.py +257 -257
- webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -242
- webscout/Provider/TTI/Nexra/__init__.py +22 -22
- webscout/Provider/TTI/Nexra/async_nexra.py +286 -286
- webscout/Provider/TTI/Nexra/sync_nexra.py +258 -258
- webscout/Provider/TTI/PollinationsAI/__init__.py +23 -23
- webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -330
- webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -285
- webscout/Provider/TTI/artbit/__init__.py +22 -22
- webscout/Provider/TTI/artbit/async_artbit.py +184 -184
- webscout/Provider/TTI/artbit/sync_artbit.py +176 -176
- webscout/Provider/TTI/blackbox/__init__.py +4 -4
- webscout/Provider/TTI/blackbox/async_blackbox.py +212 -212
- webscout/Provider/TTI/blackbox/sync_blackbox.py +199 -199
- webscout/Provider/TTI/deepinfra/__init__.py +4 -4
- webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -227
- webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -199
- webscout/Provider/TTI/huggingface/__init__.py +22 -22
- webscout/Provider/TTI/huggingface/async_huggingface.py +199 -199
- webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -195
- webscout/Provider/TTI/imgninza/__init__.py +4 -4
- webscout/Provider/TTI/imgninza/async_ninza.py +214 -214
- webscout/Provider/TTI/imgninza/sync_ninza.py +209 -209
- webscout/Provider/TTI/talkai/__init__.py +4 -4
- webscout/Provider/TTI/talkai/async_talkai.py +229 -229
- webscout/Provider/TTI/talkai/sync_talkai.py +207 -207
- webscout/Provider/TTS/deepgram.py +182 -182
- webscout/Provider/TTS/elevenlabs.py +136 -136
- webscout/Provider/TTS/gesserit.py +150 -150
- webscout/Provider/TTS/murfai.py +138 -138
- webscout/Provider/TTS/parler.py +133 -134
- webscout/Provider/TTS/streamElements.py +360 -360
- webscout/Provider/TTS/utils.py +280 -280
- webscout/Provider/TTS/voicepod.py +116 -116
- webscout/Provider/TextPollinationsAI.py +74 -47
- webscout/Provider/WiseCat.py +193 -0
- webscout/Provider/__init__.py +144 -136
- webscout/Provider/cerebras.py +242 -227
- webscout/Provider/chatglm.py +204 -204
- webscout/Provider/dgaf.py +67 -39
- webscout/Provider/gaurish.py +105 -66
- webscout/Provider/geminiapi.py +208 -208
- webscout/Provider/granite.py +223 -0
- webscout/Provider/hermes.py +218 -218
- webscout/Provider/llama3mitril.py +179 -179
- webscout/Provider/llamatutor.py +72 -62
- webscout/Provider/llmchat.py +60 -35
- webscout/Provider/meta.py +794 -794
- webscout/Provider/multichat.py +331 -230
- webscout/Provider/typegpt.py +359 -356
- webscout/Provider/yep.py +5 -5
- webscout/__main__.py +5 -5
- webscout/cli.py +319 -319
- webscout/conversation.py +241 -242
- webscout/exceptions.py +328 -328
- webscout/litagent/__init__.py +28 -28
- webscout/litagent/agent.py +2 -3
- webscout/litprinter/__init__.py +0 -58
- webscout/scout/__init__.py +8 -8
- webscout/scout/core.py +884 -884
- webscout/scout/element.py +459 -459
- webscout/scout/parsers/__init__.py +69 -69
- webscout/scout/parsers/html5lib_parser.py +172 -172
- webscout/scout/parsers/html_parser.py +236 -236
- webscout/scout/parsers/lxml_parser.py +178 -178
- webscout/scout/utils.py +38 -38
- webscout/swiftcli/__init__.py +811 -811
- webscout/update_checker.py +2 -12
- webscout/version.py +1 -1
- webscout/webscout_search.py +1142 -1140
- webscout/webscout_search_async.py +635 -635
- webscout/zeroart/__init__.py +54 -54
- webscout/zeroart/base.py +60 -60
- webscout/zeroart/effects.py +99 -99
- webscout/zeroart/fonts.py +816 -816
- {webscout-7.0.dist-info → webscout-7.2.dist-info}/METADATA +21 -28
- webscout-7.2.dist-info/RECORD +217 -0
- webstoken/__init__.py +30 -30
- webstoken/classifier.py +189 -189
- webstoken/keywords.py +216 -216
- webstoken/language.py +128 -128
- webstoken/ner.py +164 -164
- webstoken/normalizer.py +35 -35
- webstoken/processor.py +77 -77
- webstoken/sentiment.py +206 -206
- webstoken/stemmer.py +73 -73
- webstoken/tagger.py +60 -60
- webstoken/tokenizer.py +158 -158
- webscout/Provider/RUBIKSAI.py +0 -272
- webscout-7.0.dist-info/RECORD +0 -199
- {webscout-7.0.dist-info → webscout-7.2.dist-info}/LICENSE.md +0 -0
- {webscout-7.0.dist-info → webscout-7.2.dist-info}/WHEEL +0 -0
- {webscout-7.0.dist-info → webscout-7.2.dist-info}/entry_points.txt +0 -0
- {webscout-7.0.dist-info → webscout-7.2.dist-info}/top_level.txt +0 -0
webscout/webscout_search.py
CHANGED
|
@@ -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.
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
model
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
"
|
|
189
|
-
"
|
|
190
|
-
"
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
results = self.
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
"
|
|
316
|
-
"
|
|
317
|
-
"
|
|
318
|
-
"
|
|
319
|
-
"
|
|
320
|
-
"
|
|
321
|
-
"
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
payload["ex"] = "-
|
|
328
|
-
elif safesearch == "
|
|
329
|
-
payload["
|
|
330
|
-
|
|
331
|
-
payload["
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
"
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
"
|
|
396
|
-
"
|
|
397
|
-
"
|
|
398
|
-
"
|
|
399
|
-
"
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
if
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
"
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
"
|
|
486
|
-
"
|
|
487
|
-
"
|
|
488
|
-
"
|
|
489
|
-
"
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
"
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
Defaults to None.
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
Use
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
"
|
|
610
|
-
"
|
|
611
|
-
"
|
|
612
|
-
"
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
"
|
|
633
|
-
"
|
|
634
|
-
"
|
|
635
|
-
"
|
|
636
|
-
"
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
"
|
|
697
|
-
"
|
|
698
|
-
"
|
|
699
|
-
"
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
"
|
|
764
|
-
"
|
|
765
|
-
"
|
|
766
|
-
"
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
"
|
|
788
|
-
"
|
|
789
|
-
"
|
|
790
|
-
"
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
"
|
|
839
|
-
"
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
"
|
|
861
|
-
"
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
"
|
|
872
|
-
"
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
"
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
if
|
|
971
|
-
params["
|
|
972
|
-
if
|
|
973
|
-
params["
|
|
974
|
-
if
|
|
975
|
-
params["
|
|
976
|
-
if
|
|
977
|
-
params["
|
|
978
|
-
if
|
|
979
|
-
params["
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
"
|
|
1013
|
-
"
|
|
1014
|
-
"
|
|
1015
|
-
"
|
|
1016
|
-
"
|
|
1017
|
-
"
|
|
1018
|
-
"
|
|
1019
|
-
"
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
"
|
|
1036
|
-
"
|
|
1037
|
-
"
|
|
1038
|
-
"
|
|
1039
|
-
"
|
|
1040
|
-
"
|
|
1041
|
-
"
|
|
1042
|
-
"
|
|
1043
|
-
"
|
|
1044
|
-
"
|
|
1045
|
-
"
|
|
1046
|
-
"
|
|
1047
|
-
"
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
for
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
results.
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
"
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
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
|