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,428 +0,0 @@
1
- import os
2
- import json
3
- import base64
4
- import asyncio
5
- import requests
6
- from urllib.parse import quote
7
- from typing import Optional, Dict, Any, List, Union, Generator
8
-
9
- from curl_cffi.requests import Session, CurlWsFlag
10
-
11
- from webscout.AIutel import Optimizers
12
- from webscout.AIutel import Conversation
13
- from webscout.AIutel import AwesomePrompts, sanitize_stream
14
- from webscout.AIbase import Provider, AsyncProvider
15
- from webscout import exceptions
16
- from webscout.litagent import LitAgent
17
-
18
- try:
19
- has_curl_cffi = True
20
- except ImportError:
21
- has_curl_cffi = False
22
-
23
- try:
24
- import nodriver
25
- has_nodriver = True
26
- except ImportError:
27
- has_nodriver = False
28
-
29
-
30
- class NoValidHarFileError(Exception):
31
- pass
32
-
33
-
34
- class CopilotConversation:
35
- conversation_id: str
36
-
37
- def __init__(self, conversation_id: str):
38
- self.conversation_id = conversation_id
39
-
40
-
41
- class Copilot(Provider):
42
- """
43
- A class to interact with the Microsoft Copilot API.
44
- """
45
-
46
- label = "Microsoft Copilot"
47
- url = "https://copilot.microsoft.com"
48
- websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
49
- conversation_url = f"{url}/c/api/conversations"
50
- AVAILABLE_MODELS = ["Copilot", "Think Deeper"]
51
- _access_token: str = None
52
- _cookies: dict = None
53
-
54
- def __init__(
55
- self,
56
- is_conversation: bool = True,
57
- max_tokens: int = 2000,
58
- timeout: int = 900,
59
- intro: str = None,
60
- filepath: str = None,
61
- update_file: bool = True,
62
- proxies: dict = {},
63
- history_offset: int = 10250,
64
- act: str = None,
65
- model: str = "Copilot"
66
- ):
67
- """Initializes the Copilot API client."""
68
- if model not in self.AVAILABLE_MODELS:
69
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
70
-
71
- # Use LitAgent for user-agent
72
- self.headers = {
73
- 'User-Agent': LitAgent().random(),
74
- 'Accept-Language': 'en-US,en;q=0.9',
75
- 'Connection': 'keep-alive',
76
- 'Content-Type': 'application/json',
77
- 'Origin': self.url,
78
- 'Referer': f'{self.url}/',
79
- 'Sec-Fetch-Dest': 'empty',
80
- 'Sec-Fetch-Mode': 'cors',
81
- 'Sec-Fetch-Site': 'same-origin',
82
- }
83
-
84
- self.is_conversation = is_conversation
85
- self.max_tokens_to_sample = max_tokens
86
- self.timeout = timeout
87
- self.last_response = {}
88
- self.model = model
89
- self.proxies = proxies
90
-
91
- self.__available_optimizers = (
92
- method
93
- for method in dir(Optimizers)
94
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
95
- )
96
- Conversation.intro = (
97
- AwesomePrompts().get_act(
98
- act, raise_not_found=True, default=None, case_insensitive=True
99
- )
100
- if act
101
- else intro or Conversation.intro
102
- )
103
-
104
- self.conversation = Conversation(
105
- is_conversation, self.max_tokens_to_sample, filepath, update_file
106
- )
107
- self.conversation.history_offset = history_offset
108
-
109
- def ask(
110
- self,
111
- prompt: str,
112
- stream: bool = True,
113
- raw: bool = False,
114
- optimizer: str = None,
115
- conversationally: bool = False,
116
- images = None,
117
- api_key: str = None,
118
- **kwargs
119
- ) -> Union[Dict[str, Any], Generator]:
120
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
121
- if optimizer:
122
- if optimizer in self.__available_optimizers:
123
- conversation_prompt = getattr(Optimizers, optimizer)(
124
- conversation_prompt if conversationally else prompt
125
- )
126
- else:
127
- raise Exception(f"Optimizer is not one of {self.__available_optimizers}")
128
-
129
- # Main logic for calling Copilot API
130
- def for_stream():
131
- try:
132
- if not has_curl_cffi:
133
- raise Exception('Install or update "curl_cffi" package | pip install -U curl_cffi')
134
-
135
- websocket_url = self.websocket_url
136
- headers = None
137
-
138
- if images is not None:
139
- if api_key is not None:
140
- self._access_token = api_key
141
- if self._access_token is None:
142
- try:
143
- self._access_token, self._cookies = readHAR(self.url)
144
- except NoValidHarFileError as h:
145
- # print(f"Copilot: {h}")
146
- if has_nodriver:
147
- yield {"type": "login", "provider": self.label, "url": os.environ.get("webscout_login", "")}
148
- self._access_token, self._cookies = asyncio.run(get_access_token_and_cookies(self.url, self.proxies.get("https")))
149
- else:
150
- raise h
151
- websocket_url = f"{websocket_url}&accessToken={quote(self._access_token)}"
152
- headers = {"authorization": f"Bearer {self._access_token}"}
153
-
154
- with Session(
155
- timeout=self.timeout,
156
- proxy=self.proxies.get("https"),
157
- impersonate="chrome",
158
- headers=headers,
159
- cookies=self._cookies,
160
- ) as session:
161
- if self._access_token is not None:
162
- self._cookies = session.cookies.jar if hasattr(session.cookies, "jar") else session.cookies
163
-
164
- response = session.get(f"{self.url}/c/api/user")
165
- if response.status_code == 401:
166
- raise exceptions.AuthenticationError("Status 401: Invalid access token")
167
- if response.status_code != 200:
168
- raise exceptions.APIConnectionError(f"Status {response.status_code}: {response.text}")
169
- user = response.json().get('firstName')
170
- if user is None:
171
- self._access_token = None
172
- # print(f"Copilot: User: {user or 'null'}")
173
-
174
- # Create or use existing conversation
175
- conversation = kwargs.get("conversation", None)
176
- if conversation is None:
177
- response = session.post(self.conversation_url)
178
- if response.status_code != 200:
179
- raise exceptions.APIConnectionError(f"Status {response.status_code}: {response.text}")
180
- conversation_id = response.json().get("id")
181
- conversation = CopilotConversation(conversation_id)
182
- if kwargs.get("return_conversation", False):
183
- yield conversation
184
- # print(f"Copilot: Created conversation: {conversation_id}")
185
- else:
186
- conversation_id = conversation.conversation_id
187
- # print(f"Copilot: Use conversation: {conversation_id}")
188
-
189
- # Handle image uploads if any
190
- uploaded_images = []
191
- if images is not None:
192
- for image, _ in images:
193
- # Convert image to bytes if needed
194
- if isinstance(image, str):
195
- if image.startswith("data:"):
196
- # Data URL
197
- header, encoded = image.split(",", 1)
198
- data = base64.b64decode(encoded)
199
- else:
200
- # File path or URL
201
- with open(image, "rb") as f:
202
- data = f.read()
203
- else:
204
- data = image
205
-
206
- # Get content type
207
- content_type = "image/jpeg" # Default
208
- if data[:2] == b'\xff\xd8':
209
- content_type = "image/jpeg"
210
- elif data[:8] == b'\x89PNG\r\n\x1a\n':
211
- content_type = "image/png"
212
- elif data[:6] in (b'GIF87a', b'GIF89a'):
213
- content_type = "image/gif"
214
- elif data[:2] in (b'BM', b'BA'):
215
- content_type = "image/bmp"
216
-
217
- response = session.post(
218
- f"{self.url}/c/api/attachments",
219
- headers={"content-type": content_type},
220
- data=data
221
- )
222
- if response.status_code != 200:
223
- raise exceptions.APIConnectionError(f"Status {response.status_code}: {response.text}")
224
- uploaded_images.append({"type":"image", "url": response.json().get("url")})
225
- break
226
-
227
- # Connect to WebSocket
228
- wss = session.ws_connect(websocket_url)
229
- wss.send(json.dumps({"event":"setOptions","supportedCards":["weather","local","image","sports","video","ads","finance"],"ads":{"supportedTypes":["multimedia","product","tourActivity","propertyPromotion","text"]}}));
230
- wss.send(json.dumps({
231
- "event": "send",
232
- "conversationId": conversation_id,
233
- "content": [*uploaded_images, {
234
- "type": "text",
235
- "text": conversation_prompt,
236
- }],
237
- "mode": "reasoning" if "Think" in self.model else "chat"
238
- }).encode(), CurlWsFlag.TEXT)
239
-
240
- # Process response
241
- is_started = False
242
- msg = None
243
- image_prompt: str = None
244
- last_msg = None
245
- streaming_text = ""
246
-
247
- try:
248
- while True:
249
- try:
250
- msg = wss.recv()[0]
251
- msg = json.loads(msg)
252
- except:
253
- break
254
- last_msg = msg
255
- if msg.get("event") == "appendText":
256
- is_started = True
257
- content = msg.get("text")
258
- streaming_text += content
259
- resp = {"text": content}
260
- yield resp if raw else resp
261
- elif msg.get("event") == "generatingImage":
262
- image_prompt = msg.get("prompt")
263
- elif msg.get("event") == "imageGenerated":
264
- yield {"type": "image", "url": msg.get("url"), "prompt": image_prompt, "preview": msg.get("thumbnailUrl")}
265
- elif msg.get("event") == "done":
266
- break
267
- elif msg.get("event") == "suggestedFollowups":
268
- yield {"type": "suggested_followups", "suggestions": msg.get("suggestions")}
269
- break
270
- elif msg.get("event") == "replaceText":
271
- content = msg.get("text")
272
- streaming_text += content
273
- resp = {"text": content}
274
- yield resp if raw else resp
275
- elif msg.get("event") == "error":
276
- raise exceptions.FailedToGenerateResponseError(f"Error: {msg}")
277
- elif msg.get("event") not in ["received", "startMessage", "citation", "partCompleted"]:
278
- print(f"Copilot Message: {msg}")
279
-
280
- if not is_started:
281
- raise exceptions.FailedToGenerateResponseError(f"Invalid response: {last_msg}")
282
-
283
- # Update conversation history
284
- self.conversation.update_chat_history(prompt, streaming_text)
285
- self.last_response = {"text": streaming_text}
286
-
287
- finally:
288
- wss.close()
289
-
290
- except requests.RequestException as e:
291
- raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
292
- except Exception as e:
293
- raise exceptions.FailedToGenerateResponseError(f"Error: {str(e)}")
294
-
295
- def for_non_stream():
296
- streaming_text = ""
297
- for response in for_stream():
298
- if isinstance(response, dict) and "text" in response:
299
- streaming_text += response["text"]
300
- self.last_response = {"text": streaming_text}
301
- return self.last_response
302
-
303
- return for_stream() if stream else for_non_stream()
304
-
305
- def chat(
306
- self,
307
- prompt: str,
308
- stream: bool = True,
309
- optimizer: str = None,
310
- conversationally: bool = False,
311
- images = None,
312
- api_key: str = None,
313
- **kwargs
314
- ) -> Union[str, Generator]:
315
- def for_stream():
316
- for response in self.ask(prompt, True, optimizer=optimizer,
317
- conversationally=conversationally,
318
- images=images, api_key=api_key, **kwargs):
319
- if isinstance(response, dict):
320
- if "text" in response:
321
- yield response["text"]
322
- elif "type" in response:
323
- if response["type"] == "image":
324
- yield f"\n![Image]({response['url']})\n"
325
- elif response["type"] == "suggested_followups":
326
- yield "\nSuggested follow-up questions:\n"
327
- for suggestion in response["suggestions"]:
328
- yield f"- {suggestion}\n"
329
-
330
- def for_non_stream():
331
- response = self.ask(prompt, False, optimizer=optimizer,
332
- conversationally=conversationally,
333
- images=images, api_key=api_key, **kwargs)
334
- return self.get_message(response)
335
-
336
- return for_stream() if stream else for_non_stream()
337
-
338
- def get_message(self, response: dict) -> str:
339
- assert isinstance(response, dict), "Response should be of dict data-type only"
340
- return response.get("text", "")
341
-
342
-
343
- async def get_access_token_and_cookies(url: str, proxy: str = None, target: str = "ChatAI"):
344
- browser, stop_browser = await get_nodriver(proxy=proxy, user_data_dir="copilot")
345
- try:
346
- page = await browser.get(url)
347
- access_token = None
348
- while access_token is None:
349
- access_token = await page.evaluate("""
350
- (() => {
351
- for (var i = 0; i < localStorage.length; i++) {
352
- try {
353
- item = JSON.parse(localStorage.getItem(localStorage.key(i)));
354
- if (item.credentialType == "AccessToken"
355
- && item.expiresOn > Math.floor(Date.now() / 1000)
356
- && item.target.includes("target")) {
357
- return item.secret;
358
- }
359
- } catch(e) {}
360
- }
361
- })()
362
- """.replace('"target"', json.dumps(target)))
363
- if access_token is None:
364
- await asyncio.sleep(1)
365
- cookies = {}
366
- for c in await page.send(nodriver.cdp.network.get_cookies([url])):
367
- cookies[c.name] = c.value
368
- await page.close()
369
- return access_token, cookies
370
- finally:
371
- stop_browser()
372
-
373
-
374
- def readHAR(url: str):
375
- api_key = None
376
- cookies = None
377
- har_files = []
378
- # Look for HAR files in common locations
379
- har_paths = [
380
- os.path.join(os.path.expanduser("~"), "Downloads"),
381
- os.path.join(os.path.expanduser("~"), "Desktop")
382
- ]
383
- for path in har_paths:
384
- if os.path.exists(path):
385
- for file in os.listdir(path):
386
- if file.endswith(".har"):
387
- har_files.append(os.path.join(path, file))
388
-
389
- for path in har_files:
390
- with open(path, 'rb') as file:
391
- try:
392
- harFile = json.loads(file.read())
393
- except json.JSONDecodeError:
394
- # Error: not a HAR file!
395
- continue
396
- for v in harFile['log']['entries']:
397
- if v['request']['url'].startswith(url):
398
- v_headers = {h['name'].lower(): h['value'] for h in v['request']['headers']}
399
- if "authorization" in v_headers:
400
- api_key = v_headers["authorization"].split(maxsplit=1).pop()
401
- if v['request']['cookies']:
402
- cookies = {c['name']: c['value'] for c in v['request']['cookies']}
403
- if api_key is None:
404
- raise NoValidHarFileError("No access token found in .har files")
405
-
406
- return api_key, cookies
407
-
408
-
409
- # def get_clarity() -> bytes:
410
- # body = base64.b64decode("H4sIAAAAAAAAA23RwU7DMAwG4HfJ2aqS2E5ibjxH1cMOnQYqYZvUTQPx7vyJRGGAemj01XWcP+9udg+j80MetDhSyrEISc5GrqrtZnmaTydHbrdUnSsWYT2u+8Obo0Ce/IQvaDBmjkwhUlKKIRNHmQgosqEArWPRDQMx90rxeUMPzB1j+UJvwNIxhTvsPcXyX1T+rizE4juK3mEEhpAUg/JvzW1/+U/tB1LATmhqotoiweMea50PLy2vui4LOY3XfD1dwnkor5fn/e18XBFgm6fHjSzZmCyV7d3aRByAEYextaTHEH3i5pgKGVP/s+DScE5PuLKIpW6FnCi1gY3Rbpqmj0/DI/+L7QEAAA==")
411
- # return body
412
-
413
-
414
- async def get_nodriver(proxy=None, user_data_dir=None):
415
- browser = await nodriver.Browser(
416
- headless=True,
417
- proxy=proxy,
418
- user_data_dir=user_data_dir
419
- )
420
- return browser, lambda: browser.close()
421
-
422
-
423
- if __name__ == "__main__":
424
- from rich import print
425
- ai = Copilot(timeout=900, model="Think Deeper")
426
- response = ai.chat(input("> "), stream=True)
427
- for chunk in response:
428
- print(chunk, end="", flush=True)
webscout/Provider/elmo.py DELETED
@@ -1,234 +0,0 @@
1
- import requests
2
- from webscout.AIutel import Optimizers
3
- from webscout.AIutel import Conversation
4
- from webscout.AIutel import AwesomePrompts
5
- from webscout.AIbase import Provider
6
- from webscout.litagent import LitAgent
7
-
8
- class Elmo(Provider):
9
- """
10
- A class to interact with the Elmo.chat API.
11
- """
12
-
13
- def __init__(
14
- self,
15
- is_conversation: bool = True,
16
- max_tokens: int = 600,
17
- timeout: int = 30,
18
- intro: str = None,
19
- filepath: str = None,
20
- update_file: bool = True,
21
- proxies: dict = {},
22
- history_offset: int = 10250,
23
- act: str = None,
24
- system_prompt: str = "You are a helpful AI assistant. Provide clear, concise, and well-structured information. Organize your responses into paragraphs for better readability.",
25
-
26
- ) -> None:
27
- """Instantiates Elmo
28
-
29
- Args:
30
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
31
- max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
32
- timeout (int, optional): Http request timeout. Defaults to 30.
33
- intro (str, optional): Conversation introductory prompt. Defaults to None.
34
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
35
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
36
- proxies (dict, optional): Http request proxies. Defaults to {}.
37
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
38
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
39
- system_prompt (str, optional): System prompt for Elmo. Defaults to the provided string.
40
- web_search (bool, optional): Enables web search mode when True. Defaults to False.
41
- """
42
- self.session = requests.Session()
43
- self.is_conversation = is_conversation
44
- self.max_tokens_to_sample = max_tokens
45
- self.api_endpoint = "https://www.elmo.chat/api/v1/prompt"
46
- self.stream_chunk_size = 64
47
- self.timeout = timeout
48
- self.last_response = {}
49
- self.system_prompt = system_prompt
50
- self.headers = {
51
- "accept": "*/*",
52
- "accept-encoding": "gzip, deflate, br, zstd",
53
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
54
- "content-length": "763",
55
- "content-type": "text/plain;charset=UTF-8",
56
- "dnt": "1",
57
- "origin": "chrome-extension://ipnlcfhfdicbfbchfoihipknbaeenenm",
58
- "priority": "u=1, i",
59
- "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128"',
60
- "sec-ch-ua-mobile": "?0",
61
- "sec-ch-ua-platform": '"Windows"',
62
- "sec-fetch-dest": "empty",
63
- "sec-fetch-mode": "cors",
64
- "sec-fetch-site": "cross-site",
65
- "user-agent": LitAgent().random(),
66
- }
67
-
68
- self.__available_optimizers = (
69
- method
70
- for method in dir(Optimizers)
71
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
72
- )
73
- self.session.headers.update(self.headers)
74
- Conversation.intro = (
75
- AwesomePrompts().get_act(
76
- act, raise_not_found=True, default=None, case_insensitive=True
77
- )
78
- if act
79
- else intro or Conversation.intro
80
- )
81
- self.conversation = Conversation(
82
- is_conversation, self.max_tokens_to_sample, filepath, update_file
83
- )
84
- self.conversation.history_offset = history_offset
85
- self.session.proxies = proxies
86
-
87
- def ask(
88
- self,
89
- prompt: str,
90
- stream: bool = False,
91
- raw: bool = False,
92
- optimizer: str = None,
93
- conversationally: bool = False,
94
- ) -> dict:
95
- """Chat with AI
96
-
97
- Args:
98
- prompt (str): Prompt to be send.
99
- stream (bool, optional): Flag for streaming response. Defaults to False.
100
- raw (bool, optional): Stream back raw response as received. Defaults to False.
101
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
102
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
103
- Returns:
104
- dict : {}
105
- ```json
106
- {
107
- "text" : "How may I assist you today?"
108
- }
109
- ```
110
- """
111
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
112
- if optimizer:
113
- if optimizer in self.__available_optimizers:
114
- conversation_prompt = getattr(Optimizers, optimizer)(
115
- conversation_prompt if conversationally else prompt
116
- )
117
- else:
118
- raise Exception(
119
- f"Optimizer is not one of {self.__available_optimizers}"
120
- )
121
-
122
-
123
- payload = {
124
- "metadata": {
125
- "system": {"language": "en-US"},
126
- "website": {
127
- "url": "chrome-extension://ipnlcfhfdicbfbchfoihipknbaeenenm/options.html",
128
- "origin": "chrome-extension://ipnlcfhfdicbfbchfoihipknbaeenenm",
129
- "title": "Elmo Chat - Your AI Web Copilot",
130
- "xpathIndexLength": 0,
131
- "favicons": [],
132
- "language": "en",
133
- "content": "",
134
- "type": "html",
135
- "selection": "",
136
- "hash": "d41d8cd98f00b204e9800998ecf8427e",
137
- },
138
- },
139
- "regenerate": True,
140
- "conversation": [
141
- {"role": "system", "content": self.system_prompt},
142
- {"role": "user", "content": conversation_prompt},
143
- ],
144
- "enableCache": False,
145
- }
146
-
147
- def for_stream():
148
- response = self.session.post(
149
- self.api_endpoint,
150
- headers=self.headers,
151
- json=payload,
152
- stream=True,
153
- timeout=self.timeout,
154
- )
155
- if not response.ok:
156
- raise Exception(
157
- f"Failed to generate response - ({response.status_code}, {response.reason}) - {response.text}"
158
- )
159
- full_response = ""
160
- for line in response.iter_lines(decode_unicode=True):
161
- if line:
162
- if line.startswith('0:'):
163
- chunk = line.split(':"')[1].strip('"')
164
- formatted_output = (
165
- chunk.replace("\\n", "\n").replace("\\n\\n", "\n\n")
166
- )
167
- full_response += formatted_output
168
- self.last_response.update(dict(text=full_response))
169
- yield formatted_output if raw else dict(text=formatted_output)
170
- self.conversation.update_chat_history(
171
- prompt, self.get_message(self.last_response)
172
- )
173
-
174
- def for_non_stream():
175
- for _ in for_stream():
176
- pass
177
- return self.last_response
178
-
179
- return for_stream() if stream else for_non_stream()
180
-
181
- def chat(
182
- self,
183
- prompt: str,
184
- stream: bool = False,
185
- optimizer: str = None,
186
- conversationally: bool = False,
187
- ) -> str:
188
- """Generate response `str`
189
- Args:
190
- prompt (str): Prompt to be send.
191
- stream (bool, optional): Flag for streaming response. Defaults to False.
192
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
193
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
194
- Returns:
195
- str: Response generated
196
- """
197
-
198
- def for_stream():
199
- for response in self.ask(
200
- prompt, True, optimizer=optimizer, conversationally=conversationally
201
- ):
202
- yield self.get_message(response)
203
-
204
- def for_non_stream():
205
- return self.get_message(
206
- self.ask(
207
- prompt,
208
- False,
209
- optimizer=optimizer,
210
- conversationally=conversationally,
211
- )
212
- )
213
-
214
- return for_stream() if stream else for_non_stream()
215
-
216
- def get_message(self, response: dict) -> str:
217
- """Retrieves message only from response
218
-
219
- Args:
220
- response (dict): Response generated by `self.ask`
221
-
222
- Returns:
223
- str: Message extracted
224
- """
225
- assert isinstance(response, dict), "Response should be of dict data-type only"
226
- return response["text"]
227
-
228
-
229
- if __name__ == "__main__":
230
- from rich import print
231
- ai = Elmo()
232
- response = ai.chat("write a poem about AI", stream=True)
233
- for chunk in response:
234
- print(chunk, end="", flush=True)