webscout 8.2.2__py3-none-any.whl → 8.2.7__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 (306) hide show
  1. webscout/AIauto.py +112 -22
  2. webscout/AIbase.py +144 -7
  3. webscout/AIutel.py +249 -131
  4. webscout/Bard.py +579 -206
  5. webscout/DWEBS.py +78 -35
  6. webscout/__init__.py +0 -1
  7. webscout/cli.py +256 -0
  8. webscout/conversation.py +307 -436
  9. webscout/exceptions.py +23 -0
  10. webscout/prompt_manager.py +56 -42
  11. webscout/version.py +1 -1
  12. webscout/webscout_search.py +65 -47
  13. webscout/webscout_search_async.py +81 -126
  14. webscout/yep_search.py +93 -43
  15. {webscout-8.2.2.dist-info → webscout-8.2.7.dist-info}/METADATA +172 -52
  16. webscout-8.2.7.dist-info/RECORD +26 -0
  17. {webscout-8.2.2.dist-info → webscout-8.2.7.dist-info}/WHEEL +1 -1
  18. webscout-8.2.7.dist-info/entry_points.txt +3 -0
  19. webscout-8.2.7.dist-info/top_level.txt +1 -0
  20. inferno/__init__.py +0 -6
  21. inferno/__main__.py +0 -9
  22. inferno/cli.py +0 -6
  23. webscout/Extra/GitToolkit/__init__.py +0 -10
  24. webscout/Extra/GitToolkit/gitapi/__init__.py +0 -12
  25. webscout/Extra/GitToolkit/gitapi/repository.py +0 -195
  26. webscout/Extra/GitToolkit/gitapi/user.py +0 -96
  27. webscout/Extra/GitToolkit/gitapi/utils.py +0 -62
  28. webscout/Extra/YTToolkit/YTdownloader.py +0 -957
  29. webscout/Extra/YTToolkit/__init__.py +0 -3
  30. webscout/Extra/YTToolkit/transcriber.py +0 -476
  31. webscout/Extra/YTToolkit/ytapi/__init__.py +0 -6
  32. webscout/Extra/YTToolkit/ytapi/channel.py +0 -307
  33. webscout/Extra/YTToolkit/ytapi/errors.py +0 -13
  34. webscout/Extra/YTToolkit/ytapi/extras.py +0 -45
  35. webscout/Extra/YTToolkit/ytapi/https.py +0 -88
  36. webscout/Extra/YTToolkit/ytapi/patterns.py +0 -61
  37. webscout/Extra/YTToolkit/ytapi/playlist.py +0 -59
  38. webscout/Extra/YTToolkit/ytapi/pool.py +0 -8
  39. webscout/Extra/YTToolkit/ytapi/query.py +0 -40
  40. webscout/Extra/YTToolkit/ytapi/stream.py +0 -63
  41. webscout/Extra/YTToolkit/ytapi/utils.py +0 -62
  42. webscout/Extra/YTToolkit/ytapi/video.py +0 -232
  43. webscout/Extra/__init__.py +0 -7
  44. webscout/Extra/autocoder/__init__.py +0 -9
  45. webscout/Extra/autocoder/autocoder.py +0 -849
  46. webscout/Extra/autocoder/autocoder_utiles.py +0 -332
  47. webscout/Extra/gguf.py +0 -682
  48. webscout/Extra/tempmail/__init__.py +0 -28
  49. webscout/Extra/tempmail/async_utils.py +0 -141
  50. webscout/Extra/tempmail/base.py +0 -161
  51. webscout/Extra/tempmail/cli.py +0 -187
  52. webscout/Extra/tempmail/emailnator.py +0 -84
  53. webscout/Extra/tempmail/mail_tm.py +0 -361
  54. webscout/Extra/tempmail/temp_mail_io.py +0 -292
  55. webscout/Extra/weather.py +0 -194
  56. webscout/Extra/weather_ascii.py +0 -76
  57. webscout/LLM.py +0 -442
  58. webscout/Litlogger/__init__.py +0 -67
  59. webscout/Litlogger/core/__init__.py +0 -6
  60. webscout/Litlogger/core/level.py +0 -23
  61. webscout/Litlogger/core/logger.py +0 -165
  62. webscout/Litlogger/handlers/__init__.py +0 -12
  63. webscout/Litlogger/handlers/console.py +0 -33
  64. webscout/Litlogger/handlers/file.py +0 -143
  65. webscout/Litlogger/handlers/network.py +0 -173
  66. webscout/Litlogger/styles/__init__.py +0 -7
  67. webscout/Litlogger/styles/colors.py +0 -249
  68. webscout/Litlogger/styles/formats.py +0 -458
  69. webscout/Litlogger/styles/text.py +0 -87
  70. webscout/Litlogger/utils/__init__.py +0 -6
  71. webscout/Litlogger/utils/detectors.py +0 -153
  72. webscout/Litlogger/utils/formatters.py +0 -200
  73. webscout/Local/__init__.py +0 -12
  74. webscout/Local/__main__.py +0 -9
  75. webscout/Local/api.py +0 -576
  76. webscout/Local/cli.py +0 -516
  77. webscout/Local/config.py +0 -75
  78. webscout/Local/llm.py +0 -287
  79. webscout/Local/model_manager.py +0 -253
  80. webscout/Local/server.py +0 -721
  81. webscout/Local/utils.py +0 -93
  82. webscout/Provider/AI21.py +0 -177
  83. webscout/Provider/AISEARCH/DeepFind.py +0 -250
  84. webscout/Provider/AISEARCH/ISou.py +0 -256
  85. webscout/Provider/AISEARCH/Perplexity.py +0 -359
  86. webscout/Provider/AISEARCH/__init__.py +0 -10
  87. webscout/Provider/AISEARCH/felo_search.py +0 -228
  88. webscout/Provider/AISEARCH/genspark_search.py +0 -208
  89. webscout/Provider/AISEARCH/hika_search.py +0 -194
  90. webscout/Provider/AISEARCH/iask_search.py +0 -436
  91. webscout/Provider/AISEARCH/monica_search.py +0 -246
  92. webscout/Provider/AISEARCH/scira_search.py +0 -324
  93. webscout/Provider/AISEARCH/webpilotai_search.py +0 -281
  94. webscout/Provider/Aitopia.py +0 -292
  95. webscout/Provider/AllenAI.py +0 -413
  96. webscout/Provider/Andi.py +0 -228
  97. webscout/Provider/Blackboxai.py +0 -229
  98. webscout/Provider/C4ai.py +0 -432
  99. webscout/Provider/ChatGPTClone.py +0 -226
  100. webscout/Provider/ChatGPTES.py +0 -237
  101. webscout/Provider/ChatGPTGratis.py +0 -194
  102. webscout/Provider/Chatify.py +0 -175
  103. webscout/Provider/Cloudflare.py +0 -273
  104. webscout/Provider/Cohere.py +0 -208
  105. webscout/Provider/DeepSeek.py +0 -196
  106. webscout/Provider/Deepinfra.py +0 -297
  107. webscout/Provider/ElectronHub.py +0 -709
  108. webscout/Provider/ExaAI.py +0 -261
  109. webscout/Provider/ExaChat.py +0 -342
  110. webscout/Provider/Free2GPT.py +0 -241
  111. webscout/Provider/GPTWeb.py +0 -193
  112. webscout/Provider/Gemini.py +0 -169
  113. webscout/Provider/GithubChat.py +0 -367
  114. webscout/Provider/Glider.py +0 -211
  115. webscout/Provider/Groq.py +0 -670
  116. webscout/Provider/HF_space/__init__.py +0 -0
  117. webscout/Provider/HF_space/qwen_qwen2.py +0 -206
  118. webscout/Provider/HeckAI.py +0 -233
  119. webscout/Provider/HuggingFaceChat.py +0 -462
  120. webscout/Provider/Hunyuan.py +0 -272
  121. webscout/Provider/Jadve.py +0 -266
  122. webscout/Provider/Koboldai.py +0 -381
  123. webscout/Provider/LambdaChat.py +0 -392
  124. webscout/Provider/Llama.py +0 -200
  125. webscout/Provider/Llama3.py +0 -204
  126. webscout/Provider/Marcus.py +0 -148
  127. webscout/Provider/Netwrck.py +0 -228
  128. webscout/Provider/OLLAMA.py +0 -396
  129. webscout/Provider/OPENAI/__init__.py +0 -25
  130. webscout/Provider/OPENAI/base.py +0 -46
  131. webscout/Provider/OPENAI/c4ai.py +0 -367
  132. webscout/Provider/OPENAI/chatgpt.py +0 -549
  133. webscout/Provider/OPENAI/chatgptclone.py +0 -460
  134. webscout/Provider/OPENAI/deepinfra.py +0 -272
  135. webscout/Provider/OPENAI/e2b.py +0 -1350
  136. webscout/Provider/OPENAI/exaai.py +0 -404
  137. webscout/Provider/OPENAI/exachat.py +0 -433
  138. webscout/Provider/OPENAI/freeaichat.py +0 -352
  139. webscout/Provider/OPENAI/glider.py +0 -316
  140. webscout/Provider/OPENAI/heckai.py +0 -337
  141. webscout/Provider/OPENAI/llmchatco.py +0 -327
  142. webscout/Provider/OPENAI/netwrck.py +0 -348
  143. webscout/Provider/OPENAI/opkfc.py +0 -488
  144. webscout/Provider/OPENAI/scirachat.py +0 -463
  145. webscout/Provider/OPENAI/sonus.py +0 -294
  146. webscout/Provider/OPENAI/standardinput.py +0 -425
  147. webscout/Provider/OPENAI/textpollinations.py +0 -285
  148. webscout/Provider/OPENAI/toolbaz.py +0 -405
  149. webscout/Provider/OPENAI/typegpt.py +0 -346
  150. webscout/Provider/OPENAI/uncovrAI.py +0 -455
  151. webscout/Provider/OPENAI/utils.py +0 -211
  152. webscout/Provider/OPENAI/venice.py +0 -413
  153. webscout/Provider/OPENAI/wisecat.py +0 -381
  154. webscout/Provider/OPENAI/writecream.py +0 -156
  155. webscout/Provider/OPENAI/x0gpt.py +0 -371
  156. webscout/Provider/OPENAI/yep.py +0 -327
  157. webscout/Provider/OpenGPT.py +0 -199
  158. webscout/Provider/Openai.py +0 -496
  159. webscout/Provider/PI.py +0 -344
  160. webscout/Provider/Perplexitylabs.py +0 -415
  161. webscout/Provider/Phind.py +0 -535
  162. webscout/Provider/PizzaGPT.py +0 -198
  163. webscout/Provider/QwenLM.py +0 -254
  164. webscout/Provider/Reka.py +0 -214
  165. webscout/Provider/StandardInput.py +0 -278
  166. webscout/Provider/TTI/AiForce/__init__.py +0 -22
  167. webscout/Provider/TTI/AiForce/async_aiforce.py +0 -224
  168. webscout/Provider/TTI/AiForce/sync_aiforce.py +0 -245
  169. webscout/Provider/TTI/FreeAIPlayground/__init__.py +0 -9
  170. webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +0 -181
  171. webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +0 -180
  172. webscout/Provider/TTI/ImgSys/__init__.py +0 -23
  173. webscout/Provider/TTI/ImgSys/async_imgsys.py +0 -202
  174. webscout/Provider/TTI/ImgSys/sync_imgsys.py +0 -195
  175. webscout/Provider/TTI/MagicStudio/__init__.py +0 -2
  176. webscout/Provider/TTI/MagicStudio/async_magicstudio.py +0 -111
  177. webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +0 -109
  178. webscout/Provider/TTI/Nexra/__init__.py +0 -22
  179. webscout/Provider/TTI/Nexra/async_nexra.py +0 -286
  180. webscout/Provider/TTI/Nexra/sync_nexra.py +0 -258
  181. webscout/Provider/TTI/PollinationsAI/__init__.py +0 -23
  182. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +0 -311
  183. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +0 -265
  184. webscout/Provider/TTI/__init__.py +0 -12
  185. webscout/Provider/TTI/aiarta/__init__.py +0 -2
  186. webscout/Provider/TTI/aiarta/async_aiarta.py +0 -482
  187. webscout/Provider/TTI/aiarta/sync_aiarta.py +0 -440
  188. webscout/Provider/TTI/artbit/__init__.py +0 -22
  189. webscout/Provider/TTI/artbit/async_artbit.py +0 -155
  190. webscout/Provider/TTI/artbit/sync_artbit.py +0 -148
  191. webscout/Provider/TTI/fastflux/__init__.py +0 -22
  192. webscout/Provider/TTI/fastflux/async_fastflux.py +0 -261
  193. webscout/Provider/TTI/fastflux/sync_fastflux.py +0 -252
  194. webscout/Provider/TTI/huggingface/__init__.py +0 -22
  195. webscout/Provider/TTI/huggingface/async_huggingface.py +0 -199
  196. webscout/Provider/TTI/huggingface/sync_huggingface.py +0 -195
  197. webscout/Provider/TTI/piclumen/__init__.py +0 -23
  198. webscout/Provider/TTI/piclumen/async_piclumen.py +0 -268
  199. webscout/Provider/TTI/piclumen/sync_piclumen.py +0 -233
  200. webscout/Provider/TTI/pixelmuse/__init__.py +0 -4
  201. webscout/Provider/TTI/pixelmuse/async_pixelmuse.py +0 -249
  202. webscout/Provider/TTI/pixelmuse/sync_pixelmuse.py +0 -182
  203. webscout/Provider/TTI/talkai/__init__.py +0 -4
  204. webscout/Provider/TTI/talkai/async_talkai.py +0 -229
  205. webscout/Provider/TTI/talkai/sync_talkai.py +0 -207
  206. webscout/Provider/TTS/__init__.py +0 -7
  207. webscout/Provider/TTS/deepgram.py +0 -156
  208. webscout/Provider/TTS/elevenlabs.py +0 -111
  209. webscout/Provider/TTS/gesserit.py +0 -127
  210. webscout/Provider/TTS/murfai.py +0 -113
  211. webscout/Provider/TTS/parler.py +0 -111
  212. webscout/Provider/TTS/speechma.py +0 -180
  213. webscout/Provider/TTS/streamElements.py +0 -333
  214. webscout/Provider/TTS/utils.py +0 -280
  215. webscout/Provider/TeachAnything.py +0 -187
  216. webscout/Provider/TextPollinationsAI.py +0 -231
  217. webscout/Provider/TwoAI.py +0 -199
  218. webscout/Provider/Venice.py +0 -219
  219. webscout/Provider/VercelAI.py +0 -234
  220. webscout/Provider/WebSim.py +0 -228
  221. webscout/Provider/WiseCat.py +0 -196
  222. webscout/Provider/Writecream.py +0 -211
  223. webscout/Provider/WritingMate.py +0 -197
  224. webscout/Provider/Youchat.py +0 -330
  225. webscout/Provider/__init__.py +0 -198
  226. webscout/Provider/ai4chat.py +0 -202
  227. webscout/Provider/aimathgpt.py +0 -189
  228. webscout/Provider/akashgpt.py +0 -342
  229. webscout/Provider/askmyai.py +0 -158
  230. webscout/Provider/asksteve.py +0 -203
  231. webscout/Provider/bagoodex.py +0 -145
  232. webscout/Provider/cerebras.py +0 -242
  233. webscout/Provider/chatglm.py +0 -205
  234. webscout/Provider/cleeai.py +0 -213
  235. webscout/Provider/copilot.py +0 -428
  236. webscout/Provider/elmo.py +0 -234
  237. webscout/Provider/freeaichat.py +0 -271
  238. webscout/Provider/gaurish.py +0 -244
  239. webscout/Provider/geminiapi.py +0 -208
  240. webscout/Provider/geminiprorealtime.py +0 -160
  241. webscout/Provider/granite.py +0 -187
  242. webscout/Provider/hermes.py +0 -219
  243. webscout/Provider/julius.py +0 -223
  244. webscout/Provider/koala.py +0 -268
  245. webscout/Provider/labyrinth.py +0 -340
  246. webscout/Provider/learnfastai.py +0 -266
  247. webscout/Provider/lepton.py +0 -194
  248. webscout/Provider/llama3mitril.py +0 -180
  249. webscout/Provider/llamatutor.py +0 -192
  250. webscout/Provider/llmchat.py +0 -213
  251. webscout/Provider/llmchatco.py +0 -311
  252. webscout/Provider/meta.py +0 -794
  253. webscout/Provider/multichat.py +0 -325
  254. webscout/Provider/promptrefine.py +0 -193
  255. webscout/Provider/scira_chat.py +0 -277
  256. webscout/Provider/scnet.py +0 -187
  257. webscout/Provider/searchchat.py +0 -293
  258. webscout/Provider/sonus.py +0 -208
  259. webscout/Provider/talkai.py +0 -194
  260. webscout/Provider/toolbaz.py +0 -320
  261. webscout/Provider/turboseek.py +0 -219
  262. webscout/Provider/tutorai.py +0 -252
  263. webscout/Provider/typefully.py +0 -280
  264. webscout/Provider/typegpt.py +0 -232
  265. webscout/Provider/uncovr.py +0 -312
  266. webscout/Provider/x0gpt.py +0 -256
  267. webscout/Provider/yep.py +0 -376
  268. webscout/litagent/__init__.py +0 -29
  269. webscout/litagent/agent.py +0 -455
  270. webscout/litagent/constants.py +0 -60
  271. webscout/litprinter/__init__.py +0 -59
  272. webscout/scout/__init__.py +0 -8
  273. webscout/scout/core/__init__.py +0 -7
  274. webscout/scout/core/crawler.py +0 -140
  275. webscout/scout/core/scout.py +0 -568
  276. webscout/scout/core/search_result.py +0 -96
  277. webscout/scout/core/text_analyzer.py +0 -63
  278. webscout/scout/core/text_utils.py +0 -277
  279. webscout/scout/core/web_analyzer.py +0 -52
  280. webscout/scout/core.py +0 -881
  281. webscout/scout/element.py +0 -460
  282. webscout/scout/parsers/__init__.py +0 -69
  283. webscout/scout/parsers/html5lib_parser.py +0 -172
  284. webscout/scout/parsers/html_parser.py +0 -236
  285. webscout/scout/parsers/lxml_parser.py +0 -178
  286. webscout/scout/utils.py +0 -37
  287. webscout/swiftcli/__init__.py +0 -809
  288. webscout/zeroart/__init__.py +0 -55
  289. webscout/zeroart/base.py +0 -60
  290. webscout/zeroart/effects.py +0 -99
  291. webscout/zeroart/fonts.py +0 -816
  292. webscout-8.2.2.dist-info/RECORD +0 -309
  293. webscout-8.2.2.dist-info/entry_points.txt +0 -5
  294. webscout-8.2.2.dist-info/top_level.txt +0 -3
  295. webstoken/__init__.py +0 -30
  296. webstoken/classifier.py +0 -189
  297. webstoken/keywords.py +0 -216
  298. webstoken/language.py +0 -128
  299. webstoken/ner.py +0 -164
  300. webstoken/normalizer.py +0 -35
  301. webstoken/processor.py +0 -77
  302. webstoken/sentiment.py +0 -206
  303. webstoken/stemmer.py +0 -73
  304. webstoken/tagger.py +0 -60
  305. webstoken/tokenizer.py +0 -158
  306. {webscout-8.2.2.dist-info → webscout-8.2.7.dist-info/licenses}/LICENSE.md +0 -0
@@ -1,256 +0,0 @@
1
- import requests
2
- import json
3
- import re
4
- from typing import Dict, Optional, Generator, Any, Union
5
- from webscout.litagent import LitAgent
6
- from webscout import exceptions
7
- from webscout.AIbase import AISearch
8
-
9
-
10
- class Response:
11
- """A wrapper class for Felo API responses.
12
-
13
- This class automatically converts response objects to their text representation
14
- when printed or converted to string.
15
-
16
- Attributes:
17
- text (str): The text content of the response
18
-
19
- Example:
20
- >>> response = Response("Hello, world!")
21
- >>> print(response)
22
- Hello, world!
23
- >>> str(response)
24
- 'Hello, world!'
25
- """
26
- def __init__(self, text: str):
27
- self.text = text
28
-
29
- def __str__(self):
30
- return self.text
31
-
32
- def __repr__(self):
33
- return self.text
34
- class Isou(AISearch):
35
- """A class to interact with the Isou AI search API.
36
-
37
- Isou provides a powerful search interface that returns AI-generated responses
38
- based on web content. It supports both streaming and non-streaming responses.
39
-
40
- Basic Usage:
41
- >>> from webscout import Isou
42
- >>> ai = Isou()
43
- >>> # Non-streaming example
44
- >>> response = ai.search("What is Python?")
45
- >>> print(response)
46
- Python is a high-level programming language...
47
-
48
- >>> # Streaming example
49
- >>> for chunk in ai.search("Tell me about AI", stream=True):
50
- ... print(chunk, end="", flush=True)
51
- Artificial Intelligence is...
52
-
53
- >>> # Raw response format
54
- >>> for chunk in ai.search("Hello", stream=True, raw=True):
55
- ... print(chunk)
56
- {'text': 'Hello', 'links': ['http://...']}
57
-
58
- Args:
59
- timeout (int, optional): Request timeout in seconds. Defaults to 120.
60
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
61
- """
62
-
63
- def __init__(
64
- self,
65
- timeout: int = 120,
66
- proxies: Optional[dict] = None,
67
- model: str = "siliconflow:deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
68
- ):
69
- """Initialize the Isou API client.
70
-
71
- Args:
72
- timeout (int, optional): Request timeout in seconds. Defaults to 120.
73
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
74
- model (str, optional): Model to use for search. Defaults to DeepSeek-R1.
75
- """
76
- self.available_models = [
77
- "siliconflow:deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
78
- "siliconflow:Qwen/Qwen2.5-72B-Instruct-128K",
79
- "deepseek-reasoner"
80
- ]
81
-
82
- if model not in self.available_models:
83
- raise ValueError(
84
- f"Invalid model: {model}. Choose from: {self.available_models}"
85
- )
86
-
87
- self.session = requests.Session()
88
- self.api_endpoint = "https://isou.chat/api/search"
89
- self.stream_chunk_size = 64
90
- self.timeout = timeout
91
- self.last_response = {}
92
- self.model = model
93
- self.provider = "siliconflow" if model in self.available_models[:2] else "deepseek"
94
- self.mode = "simple" # or "deep"
95
- self.categories = "general" # or "science"
96
- self.reload = False
97
-
98
- self.headers = {
99
- "accept": "text/event-stream",
100
- "pragma": "no-cache",
101
- "referer": "https://isou.chat/search?q=hi",
102
- "accept-language": "en-US,en;q=0.9",
103
- "content-type": "application/json",
104
- "sec-ch-ua": '"Not(A:Brand";v="99", "Brave";v="133", "Chromium";v="133"',
105
- "sec-ch-ua-mobile": "?0",
106
- "sec-ch-ua-platform": '"Windows"',
107
- "sec-fetch-dest": "empty",
108
- "sec-fetch-mode": "cors",
109
- "sec-fetch-site": "same-origin",
110
- "sec-gpc": "1",
111
- "user-agent": LitAgent().random(),
112
- }
113
- self.session.headers.update(self.headers)
114
- self.proxies = proxies
115
-
116
- def search(
117
- self,
118
- prompt: str,
119
- stream: bool = False,
120
- raw: bool = False,
121
- ) -> Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
122
- """Search using the Isou API and get AI-generated responses.
123
-
124
- Args:
125
- prompt (str): The search query or prompt to send to the API.
126
- stream (bool, optional): If True, yields response chunks as they arrive.
127
- If False, returns complete response. Defaults to False.
128
- raw (bool, optional): If True, returns raw response dictionaries.
129
- If False, returns Response objects. Defaults to False.
130
-
131
- Returns:
132
- Union[Dict[str, Any], Generator[Dict[str, Any], None, None]]:
133
- - If stream=False: Returns complete response
134
- - If stream=True: Yields response chunks as they arrive
135
-
136
- Raises:
137
- APIConnectionError: If the API request fails
138
- """
139
- self.provider = "siliconflow" if self.model in self.available_models[:2] else "deepseek"
140
-
141
- payload = {
142
- "categories": [self.categories],
143
- "engine": "SEARXNG",
144
- "language": "all",
145
- "mode": self.mode,
146
- "model": self.model,
147
- "provider": self.provider,
148
- "reload": self.reload,
149
- "stream": stream,
150
- }
151
- params = {"q": prompt}
152
-
153
- def for_stream() -> Generator[Dict[str, Any], None, None]:
154
- full_text = ""
155
- links = []
156
- try:
157
- with self.session.post(
158
- self.api_endpoint,
159
- params=params,
160
- json=payload,
161
- stream=True,
162
- timeout=self.timeout,
163
- ) as response:
164
- response.raise_for_status()
165
- for line in response.iter_lines(chunk_size=self.stream_chunk_size, decode_unicode=True):
166
- if not line or not line.startswith('data:'):
167
- continue
168
- try:
169
- data = json.loads(line[5:].strip())
170
-
171
- # Handle nested data structure
172
- if 'data' in data and isinstance(data['data'], str):
173
- try:
174
- nested_data = json.loads(data['data'])
175
- data.update(nested_data)
176
- except json.JSONDecodeError:
177
- pass
178
-
179
- # Extract content and ensure it's properly decoded
180
- if 'content' in data:
181
- content = data['content']
182
- if isinstance(content, str):
183
- # Get only the new text (delta)
184
- delta = content[len(full_text):]
185
- full_text = content
186
-
187
- # Yield the chunk
188
- if raw:
189
- yield {"text": delta, "links": links}
190
- else:
191
- yield Response(delta)
192
-
193
- # Extract links
194
- if 'links' in data and isinstance(data['links'], list):
195
- links.extend(data['links'])
196
-
197
- except json.JSONDecodeError:
198
- continue
199
-
200
- except requests.exceptions.RequestException as e:
201
- raise exceptions.APIConnectionError(f"Request failed: {e}")
202
-
203
- def for_non_stream():
204
- full_response = ""
205
- all_links = []
206
- for chunk in for_stream():
207
- if raw:
208
- yield chunk
209
- else:
210
- full_response += str(chunk)
211
- if isinstance(chunk, dict):
212
- all_links.extend(chunk.get("links", []))
213
-
214
- if not raw:
215
- self.last_response = Response(full_response)
216
- return self.last_response
217
-
218
- return for_stream() if stream else for_non_stream()
219
-
220
- @staticmethod
221
- def format_response(text: str, links: list) -> str:
222
- """Format the response text with numbered citations and link list.
223
-
224
- Args:
225
- text (str): The response text with citation markers
226
- links (list): List of reference links
227
-
228
- Returns:
229
- str: Formatted text with numbered citations and link list
230
- """
231
- # Clean up text
232
- text = re.sub(r'\s+', ' ', text).strip()
233
-
234
- # Replace citations with numbers
235
- link_map = {f"citation:{i}]]": f"[{i}]" for i, _ in enumerate(links, start=1)}
236
- for key, value in link_map.items():
237
- text = text.replace(key, value)
238
- text = text.replace("[[[", "[")
239
-
240
- # Format link list
241
- link_list = "\n".join([f"{i}. {link}" for i, link in enumerate(links, start=1)])
242
-
243
- return f"{text}\n\nLinks:\n{link_list}"
244
-
245
- if __name__ == "__main__":
246
- from rich import print
247
-
248
- # Initialize with specific model and logging
249
- ai = Isou(
250
- model="siliconflow:deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
251
- )
252
-
253
- response = ai.search(input(">>> "), stream=True, raw=False)
254
- for chunk in response:
255
- print(chunk, end="", flush=True)
256
-
@@ -1,359 +0,0 @@
1
- import json
2
- import random
3
- from uuid import uuid4
4
- from typing import Dict, Optional, Generator, Union, Any
5
- from curl_cffi import requests
6
-
7
- from webscout.AIbase import AISearch
8
- from webscout import exceptions
9
- from webscout.litagent import LitAgent
10
-
11
-
12
- class Response:
13
- """A wrapper class for Perplexity API responses.
14
-
15
- This class automatically converts response objects to their text representation
16
- when printed or converted to string.
17
-
18
- Attributes:
19
- text (str): The text content of the response
20
-
21
- Example:
22
- >>> response = Response("Hello, world!")
23
- >>> print(response)
24
- Hello, world!
25
- >>> str(response)
26
- 'Hello, world!'
27
- """
28
- def __init__(self, text: str):
29
- self.text = text
30
-
31
- def __str__(self):
32
- return self.text
33
-
34
- def __repr__(self):
35
- return self.text
36
-
37
-
38
- class Perplexity(AISearch):
39
- """A class to interact with the Perplexity AI search API.
40
-
41
- Perplexity provides a powerful search interface that returns AI-generated responses
42
- based on web content. It supports both streaming and non-streaming responses,
43
- multiple search modes, and model selection.
44
-
45
- Basic Usage:
46
- >>> from webscout import Perplexity
47
- >>> ai = Perplexity()
48
- >>> # Non-streaming example
49
- >>> response = ai.search("What is Python?")
50
- >>> print(response)
51
- Python is a high-level programming language...
52
-
53
- >>> # Streaming example
54
- >>> for chunk in ai.search("Tell me about AI", stream=True):
55
- ... print(chunk, end="", flush=True)
56
- Artificial Intelligence is...
57
-
58
- >>> # Pro search with specific model (requires authentication via cookies)
59
- >>> cookies = {"perplexity-user": "your_cookie_value"}
60
- >>> ai_pro = Perplexity(cookies=cookies)
61
- >>> response = ai_pro.search("Latest AI research", mode="pro", model="gpt-4o")
62
- >>> print(response)
63
-
64
- >>> # Raw response format
65
- >>> for chunk in ai.search("Hello", stream=True, raw=True):
66
- ... print(chunk)
67
- {'text': 'Hello'}
68
- {'text': ' there!'}
69
-
70
- Args:
71
- cookies (dict, optional): Cookies to use for authentication. Defaults to None.
72
- timeout (int, optional): Request timeout in seconds. Defaults to 60.
73
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
74
- """
75
-
76
- def __init__(
77
- self,
78
- cookies: Optional[Dict[str, str]] = None,
79
- timeout: int = 60,
80
- proxies: Optional[Dict[str, str]] = None
81
- ):
82
- """
83
- Initialize the Perplexity client.
84
-
85
- Args:
86
- cookies (dict, optional): Cookies to use for authentication. Defaults to None.
87
- timeout (int, optional): Request timeout in seconds. Defaults to 60.
88
- proxies (dict, optional): Proxy configuration for requests. Defaults to None.
89
- """
90
- self.timeout = timeout
91
- self.agent = LitAgent()
92
- self.session = requests.Session(headers={
93
- 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
94
- 'accept-language': 'en-US,en;q=0.9',
95
- 'cache-control': 'max-age=0',
96
- 'dnt': '1',
97
- 'priority': 'u=0, i',
98
- 'sec-ch-ua': '"Not;A=Brand";v="24", "Chromium";v="128"',
99
- 'sec-ch-ua-arch': '"x86"',
100
- 'sec-ch-ua-bitness': '"64"',
101
- 'sec-ch-ua-full-version': '"128.0.6613.120"',
102
- 'sec-ch-ua-full-version-list': '"Not;A=Brand";v="24.0.0.0", "Chromium";v="128.0.6613.120"',
103
- 'sec-ch-ua-mobile': '?0',
104
- 'sec-ch-ua-model': '""',
105
- 'sec-ch-ua-platform': '"Windows"',
106
- 'sec-ch-ua-platform-version': '"19.0.0"',
107
- 'sec-fetch-dest': 'document',
108
- 'sec-fetch-mode': 'navigate',
109
- 'sec-fetch-site': 'same-origin',
110
- 'sec-fetch-user': '?1',
111
- 'upgrade-insecure-requests': '1',
112
- 'user-agent': self.agent.random(),
113
- }, cookies=cookies or {}, impersonate='chrome')
114
-
115
- # Apply proxies if provided
116
- if proxies:
117
- self.session.proxies.update(proxies)
118
-
119
- # Initialize session with socket.io
120
- self.timestamp = format(random.getrandbits(32), '08x')
121
-
122
- # Get socket.io session ID
123
- response = self.session.get(f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.timestamp}')
124
- self.sid = json.loads(response.text[1:])['sid']
125
-
126
- # Initialize socket.io connection
127
- assert (self.session.post(
128
- f'https://www.perplexity.ai/socket.io/?EIO=4&transport=polling&t={self.timestamp}&sid={self.sid}',
129
- data='40{"jwt":"anonymous-ask-user"}'
130
- )).text == 'OK'
131
-
132
- # Get session info
133
- self.session.get('https://www.perplexity.ai/api/auth/session')
134
-
135
- # Set default values
136
- self.copilot = 0 if not cookies else float('inf')
137
- self.file_upload = 0 if not cookies else float('inf')
138
-
139
- def _extract_answer(self, response):
140
- """
141
- Extract the answer from the response.
142
-
143
- Args:
144
- response (dict): The response from Perplexity AI.
145
-
146
- Returns:
147
- str: The extracted answer text.
148
- """
149
- if not response:
150
- return ""
151
-
152
- # Find the FINAL step in the text array
153
- final_step = None
154
- if 'text' in response and isinstance(response['text'], list):
155
- for step in response['text']:
156
- if step.get('step_type') == 'FINAL' and 'content' in step and 'answer' in step['content']:
157
- final_step = step
158
- break
159
-
160
- if not final_step:
161
- return ""
162
-
163
- try:
164
- # Parse the answer JSON string
165
- answer_json = json.loads(final_step['content']['answer'])
166
- return answer_json.get('answer', '')
167
- except (json.JSONDecodeError, KeyError):
168
- return ""
169
-
170
- def search(
171
- self,
172
- prompt: str,
173
- mode: str = 'auto',
174
- model: Optional[str] = None,
175
- sources: Optional[list] = None,
176
- stream: bool = False,
177
- raw: bool = False,
178
- language: str = 'en-US',
179
- follow_up: Optional[Dict[str, Any]] = None,
180
- incognito: bool = False
181
- ) -> Union[Response, Generator[Union[Dict[str, str], Response], None, None]]:
182
- """Search using the Perplexity API and get AI-generated responses.
183
-
184
- This method sends a search query to Perplexity and returns the AI-generated response.
185
- It supports both streaming and non-streaming modes, as well as raw response format.
186
-
187
- Args:
188
- prompt (str): The search query or prompt to send to the API.
189
- mode (str, optional): Search mode. Options: 'auto', 'pro', 'reasoning', 'deep research'.
190
- Defaults to 'auto'.
191
- model (str, optional): Model to use. Available models depend on the mode. Defaults to None.
192
- sources (list, optional): Sources to use. Options: 'web', 'scholar', 'social'.
193
- Defaults to ['web'].
194
- stream (bool, optional): If True, yields response chunks as they arrive.
195
- If False, returns complete response. Defaults to False.
196
- raw (bool, optional): If True, returns raw response dictionaries.
197
- If False, returns Response objects that convert to text automatically.
198
- Defaults to False.
199
- language (str, optional): Language to use. Defaults to 'en-US'.
200
- follow_up (dict, optional): Follow-up information. Defaults to None.
201
- incognito (bool, optional): Whether to use incognito mode. Defaults to False.
202
-
203
- Returns:
204
- If stream=True: Generator yielding response chunks as they arrive
205
- If stream=False: Complete response
206
-
207
- Raises:
208
- ValueError: If invalid mode or model is provided
209
- exceptions.APIConnectionError: If connection to API fails
210
- exceptions.FailedToGenerateResponseError: If response generation fails
211
- """
212
- if sources is None:
213
- sources = ['web']
214
-
215
- # Validate inputs
216
- if mode not in ['auto', 'pro', 'reasoning', 'deep research']:
217
- raise ValueError('Search modes -> ["auto", "pro", "reasoning", "deep research"]')
218
-
219
- if not all([source in ('web', 'scholar', 'social') for source in sources]):
220
- raise ValueError('Sources -> ["web", "scholar", "social"]')
221
-
222
- # Check if model is valid for the selected mode
223
- valid_models = {
224
- 'auto': [None],
225
- 'pro': [None, 'sonar', 'gpt-4.5', 'gpt-4o', 'claude 3.7 sonnet', 'gemini 2.0 flash', 'grok-2'],
226
- 'reasoning': [None, 'r1', 'o3-mini', 'claude 3.7 sonnet'],
227
- 'deep research': [None]
228
- }
229
-
230
- if mode in valid_models and model not in valid_models[mode] and model is not None:
231
- raise ValueError(f'Invalid model for {mode} mode. Valid models: {valid_models[mode]}')
232
-
233
- # Prepare request data
234
- json_data = {
235
- 'query_str': prompt,
236
- 'params': {
237
- 'attachments': follow_up['attachments'] if follow_up else [],
238
- 'frontend_context_uuid': str(uuid4()),
239
- 'frontend_uuid': str(uuid4()),
240
- 'is_incognito': incognito,
241
- 'language': language,
242
- 'last_backend_uuid': follow_up['backend_uuid'] if follow_up else None,
243
- 'mode': 'concise' if mode == 'auto' else 'copilot',
244
- 'model_preference': {
245
- 'auto': {
246
- None: 'turbo'
247
- },
248
- 'pro': {
249
- None: 'pplx_pro',
250
- 'sonar': 'experimental',
251
- 'gpt-4.5': 'gpt45',
252
- 'gpt-4o': 'gpt4o',
253
- 'claude 3.7 sonnet': 'claude2',
254
- 'gemini 2.0 flash': 'gemini2flash',
255
- 'grok-2': 'grok'
256
- },
257
- 'reasoning': {
258
- None: 'pplx_reasoning',
259
- 'r1': 'r1',
260
- 'o3-mini': 'o3mini',
261
- 'claude 3.7 sonnet': 'claude37sonnetthinking'
262
- },
263
- 'deep research': {
264
- None: 'pplx_alpha'
265
- }
266
- }[mode][model],
267
- 'source': 'default',
268
- 'sources': sources,
269
- 'version': '2.18'
270
- }
271
- }
272
-
273
- try:
274
- # Make the request
275
- resp = self.session.post(
276
- 'https://www.perplexity.ai/rest/sse/perplexity_ask',
277
- json=json_data,
278
- stream=True,
279
- timeout=self.timeout
280
- )
281
-
282
- if resp.status_code != 200:
283
- raise exceptions.APIConnectionError(f"API returned status code {resp.status_code}")
284
-
285
- # Define streaming response handler
286
- def stream_response():
287
- for chunk in resp.iter_lines(delimiter=b'\r\n\r\n'):
288
- content = chunk.decode('utf-8')
289
- if content.startswith('event: message\r\n'):
290
- content_json = json.loads(content[len('event: message\r\ndata: '):])
291
- if 'text' in content_json:
292
- try:
293
- # If text is a string, try to parse it as JSON
294
- if isinstance(content_json['text'], str):
295
- content_json['text'] = json.loads(content_json['text'])
296
- except json.JSONDecodeError:
297
- pass
298
-
299
- if raw:
300
- yield content_json
301
- else:
302
- # For non-raw responses, extract text from each chunk
303
- if 'text' in content_json and isinstance(content_json['text'], list):
304
- for step in content_json['text']:
305
- if step.get('type') == 'answer' and 'value' in step:
306
- yield Response(step['value'])
307
- elif step.get('type') == 'thinking' and 'value' in step:
308
- yield Response(step['value'])
309
- elif content.startswith('event: end_of_stream\r\n'):
310
- return
311
-
312
- # Handle streaming or non-streaming response
313
- if stream:
314
- return stream_response()
315
- else:
316
- chunks = []
317
- final_response = None
318
-
319
- for chunk in resp.iter_lines(delimiter=b'\r\n\r\n'):
320
- content = chunk.decode('utf-8')
321
- if content.startswith('event: message\r\n'):
322
- content_json = json.loads(content[len('event: message\r\ndata: '):])
323
- if 'text' in content_json:
324
- try:
325
- # If text is a string, try to parse it as JSON
326
- if isinstance(content_json['text'], str):
327
- content_json['text'] = json.loads(content_json['text'])
328
- except json.JSONDecodeError:
329
- pass
330
- chunks.append(content_json)
331
- final_response = content_json
332
- elif content.startswith('event: end_of_stream\r\n'):
333
- # Process the final response to extract the answer
334
- if final_response:
335
- answer_text = self._extract_answer(final_response)
336
- return Response(answer_text) if not raw else final_response
337
- elif chunks:
338
- answer_text = self._extract_answer(chunks[-1])
339
- return Response(answer_text) if not raw else chunks[-1]
340
- else:
341
- return Response("") if not raw else {}
342
-
343
- # If we get here, something went wrong
344
- raise exceptions.FailedToGenerateResponseError("Failed to get complete response")
345
-
346
- except requests.RequestsError as e:
347
- raise exceptions.APIConnectionError(f"Connection error: {str(e)}")
348
- except json.JSONDecodeError:
349
- raise exceptions.FailedToGenerateResponseError("Failed to parse response JSON")
350
- except Exception as e:
351
- raise exceptions.FailedToGenerateResponseError(f"Error: {str(e)}")
352
-
353
-
354
- if __name__ == "__main__":
355
- # Simple test
356
- ai = Perplexity()
357
- response = ai.search("What is Python?")
358
- print(response)
359
-
@@ -1,10 +0,0 @@
1
- from .felo_search import *
2
- from .DeepFind import *
3
- from .ISou import *
4
- from .genspark_search import *
5
- from .monica_search import *
6
- from .webpilotai_search import *
7
- from .hika_search import *
8
- from .scira_search import *
9
- from .iask_search import *
10
- from .Perplexity import *