webscout 7.4__py3-none-any.whl → 7.6__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 +5 -53
- webscout/AIutel.py +8 -318
- webscout/DWEBS.py +460 -489
- webscout/Extra/YTToolkit/YTdownloader.py +14 -53
- webscout/Extra/YTToolkit/transcriber.py +12 -13
- webscout/Extra/YTToolkit/ytapi/video.py +0 -1
- webscout/Extra/__init__.py +0 -1
- webscout/Extra/autocoder/autocoder_utiles.py +0 -4
- webscout/Extra/autocoder/rawdog.py +13 -41
- webscout/Extra/gguf.py +652 -428
- webscout/Extra/weather.py +178 -156
- webscout/Extra/weather_ascii.py +70 -17
- webscout/Litlogger/core/logger.py +1 -2
- webscout/Litlogger/handlers/file.py +1 -1
- webscout/Litlogger/styles/formats.py +0 -2
- webscout/Litlogger/utils/detectors.py +0 -1
- webscout/Provider/AISEARCH/DeepFind.py +0 -1
- webscout/Provider/AISEARCH/ISou.py +1 -1
- webscout/Provider/AISEARCH/felo_search.py +0 -1
- webscout/Provider/AllenAI.py +24 -9
- webscout/Provider/C4ai.py +432 -0
- webscout/Provider/ChatGPTGratis.py +24 -56
- webscout/Provider/Cloudflare.py +18 -21
- webscout/Provider/DeepSeek.py +27 -48
- webscout/Provider/Deepinfra.py +129 -53
- webscout/Provider/Gemini.py +1 -1
- webscout/Provider/GithubChat.py +362 -0
- webscout/Provider/Glider.py +25 -8
- webscout/Provider/HF_space/qwen_qwen2.py +2 -2
- webscout/Provider/HeckAI.py +38 -5
- webscout/Provider/HuggingFaceChat.py +462 -0
- webscout/Provider/Jadve.py +20 -5
- webscout/Provider/Marcus.py +7 -50
- webscout/Provider/Netwrck.py +43 -67
- webscout/Provider/PI.py +4 -2
- webscout/Provider/Perplexitylabs.py +26 -6
- webscout/Provider/Phind.py +29 -3
- webscout/Provider/PizzaGPT.py +10 -51
- webscout/Provider/TTI/AiForce/async_aiforce.py +4 -37
- webscout/Provider/TTI/AiForce/sync_aiforce.py +41 -38
- webscout/Provider/TTI/FreeAIPlayground/__init__.py +9 -9
- webscout/Provider/TTI/FreeAIPlayground/async_freeaiplayground.py +206 -206
- webscout/Provider/TTI/FreeAIPlayground/sync_freeaiplayground.py +192 -192
- webscout/Provider/TTI/MagicStudio/__init__.py +2 -0
- webscout/Provider/TTI/MagicStudio/async_magicstudio.py +111 -0
- webscout/Provider/TTI/MagicStudio/sync_magicstudio.py +109 -0
- webscout/Provider/TTI/PollinationsAI/async_pollinations.py +5 -24
- webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +2 -22
- webscout/Provider/TTI/__init__.py +2 -3
- webscout/Provider/TTI/aiarta/__init__.py +2 -0
- webscout/Provider/TTI/aiarta/async_aiarta.py +482 -0
- webscout/Provider/TTI/aiarta/sync_aiarta.py +440 -0
- webscout/Provider/TTI/fastflux/__init__.py +22 -0
- webscout/Provider/TTI/fastflux/async_fastflux.py +257 -0
- webscout/Provider/TTI/fastflux/sync_fastflux.py +247 -0
- webscout/Provider/TTS/__init__.py +2 -2
- webscout/Provider/TTS/deepgram.py +12 -39
- webscout/Provider/TTS/elevenlabs.py +14 -40
- webscout/Provider/TTS/gesserit.py +11 -35
- webscout/Provider/TTS/murfai.py +13 -39
- webscout/Provider/TTS/parler.py +17 -40
- webscout/Provider/TTS/speechma.py +180 -0
- webscout/Provider/TTS/streamElements.py +17 -44
- webscout/Provider/TextPollinationsAI.py +39 -59
- webscout/Provider/Venice.py +217 -200
- webscout/Provider/WiseCat.py +27 -5
- webscout/Provider/Youchat.py +63 -36
- webscout/Provider/__init__.py +13 -8
- webscout/Provider/akashgpt.py +28 -10
- webscout/Provider/copilot.py +416 -0
- webscout/Provider/flowith.py +196 -0
- webscout/Provider/freeaichat.py +32 -45
- webscout/Provider/granite.py +17 -53
- webscout/Provider/koala.py +20 -5
- webscout/Provider/llamatutor.py +7 -47
- webscout/Provider/llmchat.py +36 -53
- webscout/Provider/multichat.py +92 -98
- webscout/Provider/talkai.py +1 -0
- webscout/Provider/turboseek.py +3 -0
- webscout/Provider/tutorai.py +2 -0
- webscout/Provider/typegpt.py +154 -64
- webscout/Provider/x0gpt.py +3 -1
- webscout/Provider/yep.py +102 -20
- webscout/__init__.py +3 -0
- webscout/cli.py +4 -40
- webscout/conversation.py +1 -10
- webscout/exceptions.py +19 -9
- webscout/litagent/__init__.py +2 -2
- webscout/litagent/agent.py +351 -20
- webscout/litagent/constants.py +34 -5
- webscout/litprinter/__init__.py +0 -3
- webscout/models.py +181 -0
- webscout/optimizers.py +1 -1
- webscout/prompt_manager.py +2 -8
- webscout/scout/core/scout.py +1 -4
- webscout/scout/core/search_result.py +1 -1
- webscout/scout/core/text_utils.py +1 -1
- webscout/scout/core.py +2 -5
- webscout/scout/element.py +1 -1
- webscout/scout/parsers/html_parser.py +1 -1
- webscout/scout/utils.py +0 -1
- webscout/swiftcli/__init__.py +1 -3
- webscout/tempid.py +1 -1
- webscout/update_checker.py +55 -95
- webscout/version.py +1 -1
- webscout/webscout_search_async.py +1 -2
- webscout/yep_search.py +297 -297
- webscout-7.6.dist-info/LICENSE.md +146 -0
- {webscout-7.4.dist-info → webscout-7.6.dist-info}/METADATA +104 -514
- {webscout-7.4.dist-info → webscout-7.6.dist-info}/RECORD +113 -120
- webscout/Extra/autollama.py +0 -231
- webscout/Local/__init__.py +0 -10
- webscout/Local/_version.py +0 -3
- webscout/Local/formats.py +0 -747
- webscout/Local/model.py +0 -1368
- webscout/Local/samplers.py +0 -125
- webscout/Local/thread.py +0 -539
- webscout/Local/ui.py +0 -401
- webscout/Local/utils.py +0 -388
- webscout/Provider/Amigo.py +0 -274
- webscout/Provider/Bing.py +0 -243
- webscout/Provider/DiscordRocks.py +0 -253
- webscout/Provider/TTI/blackbox/__init__.py +0 -4
- webscout/Provider/TTI/blackbox/async_blackbox.py +0 -212
- webscout/Provider/TTI/blackbox/sync_blackbox.py +0 -199
- webscout/Provider/TTI/deepinfra/__init__.py +0 -4
- webscout/Provider/TTI/deepinfra/async_deepinfra.py +0 -227
- webscout/Provider/TTI/deepinfra/sync_deepinfra.py +0 -199
- webscout/Provider/TTI/imgninza/__init__.py +0 -4
- webscout/Provider/TTI/imgninza/async_ninza.py +0 -214
- webscout/Provider/TTI/imgninza/sync_ninza.py +0 -209
- webscout/Provider/TTS/voicepod.py +0 -117
- webscout/Provider/dgaf.py +0 -214
- webscout-7.4.dist-info/LICENSE.md +0 -211
- {webscout-7.4.dist-info → webscout-7.6.dist-info}/WHEEL +0 -0
- {webscout-7.4.dist-info → webscout-7.6.dist-info}/entry_points.txt +0 -0
- {webscout-7.4.dist-info → webscout-7.6.dist-info}/top_level.txt +0 -0
webscout/Provider/__init__.py
CHANGED
|
@@ -23,7 +23,6 @@ from .Llama3 import *
|
|
|
23
23
|
from .DARKAI import *
|
|
24
24
|
from .koala import *
|
|
25
25
|
from .meta import *
|
|
26
|
-
from .DiscordRocks import *
|
|
27
26
|
from .julius import *
|
|
28
27
|
from .Youchat import *
|
|
29
28
|
from .yep import *
|
|
@@ -39,14 +38,12 @@ from .cerebras import *
|
|
|
39
38
|
from .lepton import *
|
|
40
39
|
from .geminiapi import *
|
|
41
40
|
from .elmo import *
|
|
42
|
-
from .Bing import *
|
|
43
41
|
from .GPTWeb import *
|
|
44
42
|
from .Netwrck import Netwrck
|
|
45
43
|
from .llamatutor import *
|
|
46
44
|
from .promptrefine import *
|
|
47
45
|
from .tutorai import *
|
|
48
46
|
from .ChatGPTES import *
|
|
49
|
-
from .Amigo import *
|
|
50
47
|
from .bagoodex import *
|
|
51
48
|
from .aimathgpt import *
|
|
52
49
|
from .gaurish import *
|
|
@@ -63,7 +60,6 @@ from .chatglm import *
|
|
|
63
60
|
from .hermes import *
|
|
64
61
|
from .TextPollinationsAI import *
|
|
65
62
|
from .Glider import *
|
|
66
|
-
from .dgaf import *
|
|
67
63
|
from .ChatGPTGratis import *
|
|
68
64
|
from .QwenLM import *
|
|
69
65
|
from .granite import *
|
|
@@ -76,9 +72,19 @@ from .AllenAI import *
|
|
|
76
72
|
from .HeckAI import *
|
|
77
73
|
from .TwoAI import *
|
|
78
74
|
from .Venice import *
|
|
75
|
+
from .ElectronHub import *
|
|
76
|
+
from .HuggingFaceChat import *
|
|
77
|
+
from .GithubChat import *
|
|
78
|
+
from .copilot import *
|
|
79
|
+
from .C4ai import *
|
|
80
|
+
from .flowith import *
|
|
79
81
|
__all__ = [
|
|
80
82
|
'LLAMA',
|
|
83
|
+
'Flowith',
|
|
84
|
+
'C4ai',
|
|
81
85
|
'Venice',
|
|
86
|
+
'Copilot',
|
|
87
|
+
'HuggingFaceChat',
|
|
82
88
|
'TwoAI',
|
|
83
89
|
'HeckAI',
|
|
84
90
|
'AllenAI',
|
|
@@ -89,7 +95,7 @@ __all__ = [
|
|
|
89
95
|
'IBMGranite',
|
|
90
96
|
'QwenLM',
|
|
91
97
|
'ChatGPTGratis',
|
|
92
|
-
|
|
98
|
+
|
|
93
99
|
'TextPollinationsAI',
|
|
94
100
|
'GliderAI',
|
|
95
101
|
'Cohere',
|
|
@@ -114,7 +120,6 @@ __all__ = [
|
|
|
114
120
|
'KOALA',
|
|
115
121
|
'Meta',
|
|
116
122
|
'AskMyAI',
|
|
117
|
-
'DiscordRocks',
|
|
118
123
|
'PiAI',
|
|
119
124
|
'Julius',
|
|
120
125
|
'YouChat',
|
|
@@ -132,14 +137,12 @@ __all__ = [
|
|
|
132
137
|
'Cleeai',
|
|
133
138
|
'Elmo',
|
|
134
139
|
'Free2GPT',
|
|
135
|
-
'Bing',
|
|
136
140
|
'GPTWeb',
|
|
137
141
|
'Netwrck',
|
|
138
142
|
'LlamaTutor',
|
|
139
143
|
'PromptRefine',
|
|
140
144
|
'TutorAI',
|
|
141
145
|
'ChatGPTES',
|
|
142
|
-
'AmigoChat',
|
|
143
146
|
'Bagoodex',
|
|
144
147
|
'AIMathGPT',
|
|
145
148
|
'GaurishCerebras',
|
|
@@ -155,4 +158,6 @@ __all__ = [
|
|
|
155
158
|
'ChatGLM',
|
|
156
159
|
'NousHermes',
|
|
157
160
|
'FreeAIChat',
|
|
161
|
+
'ElectronHub',
|
|
162
|
+
'GithubChat',
|
|
158
163
|
]
|
webscout/Provider/akashgpt.py
CHANGED
|
@@ -32,11 +32,13 @@ class AkashGPT(Provider):
|
|
|
32
32
|
"Meta-Llama-3-3-70B-Instruct",
|
|
33
33
|
"DeepSeek-R1",
|
|
34
34
|
"Meta-Llama-3-1-405B-Instruct-FP8",
|
|
35
|
-
"Meta-Llama-3-2-3B-Instruct",
|
|
36
|
-
"Meta-Llama-3-1-8B-Instruct-FP8",
|
|
37
|
-
"mistral",
|
|
38
|
-
"nous-hermes2-mixtral",
|
|
39
|
-
"dolphin-mixtral"
|
|
35
|
+
# "Meta-Llama-3-2-3B-Instruct",
|
|
36
|
+
# "Meta-Llama-3-1-8B-Instruct-FP8",
|
|
37
|
+
# "mistral",
|
|
38
|
+
# "nous-hermes2-mixtral",
|
|
39
|
+
# "dolphin-mixtral",
|
|
40
|
+
"Qwen-QwQ-32B"
|
|
41
|
+
|
|
40
42
|
]
|
|
41
43
|
|
|
42
44
|
def __init__(
|
|
@@ -186,6 +188,7 @@ class AkashGPT(Provider):
|
|
|
186
188
|
],
|
|
187
189
|
"model": self.model,
|
|
188
190
|
"temperature": self.temperature,
|
|
191
|
+
"system": self.system_prompt,
|
|
189
192
|
"topP": self.top_p
|
|
190
193
|
}
|
|
191
194
|
|
|
@@ -305,8 +308,23 @@ class AkashGPT(Provider):
|
|
|
305
308
|
return response.get("text", "")
|
|
306
309
|
|
|
307
310
|
if __name__ == "__main__":
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
311
|
+
print("-" * 80)
|
|
312
|
+
print(f"{'Model':<50} {'Status':<10} {'Response'}")
|
|
313
|
+
print("-" * 80)
|
|
314
|
+
|
|
315
|
+
for model in AkashGPT.AVAILABLE_MODELS:
|
|
316
|
+
try:
|
|
317
|
+
test_ai = AkashGPT(model=model, timeout=60)
|
|
318
|
+
response = test_ai.chat("Say 'Hello' in one word")
|
|
319
|
+
response_text = response
|
|
320
|
+
|
|
321
|
+
if response_text and len(response_text.strip()) > 0:
|
|
322
|
+
status = "✓"
|
|
323
|
+
# Truncate response if too long
|
|
324
|
+
display_text = response_text.strip()[:50] + "..." if len(response_text.strip()) > 50 else response_text.strip()
|
|
325
|
+
else:
|
|
326
|
+
status = "✗"
|
|
327
|
+
display_text = "Empty or invalid response"
|
|
328
|
+
print(f"{model:<50} {status:<10} {display_text}")
|
|
329
|
+
except Exception as e:
|
|
330
|
+
print(f"{model:<50} {'✗':<10} {str(e)}")
|
|
@@ -0,0 +1,416 @@
|
|
|
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 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
|
+
AVAILABLE_MODELS = ["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
|
+
|
|
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({
|
|
230
|
+
"event": "send",
|
|
231
|
+
"conversationId": conversation_id,
|
|
232
|
+
"content": [*uploaded_images, {
|
|
233
|
+
"type": "text",
|
|
234
|
+
"text": conversation_prompt,
|
|
235
|
+
}],
|
|
236
|
+
"mode": "chat"
|
|
237
|
+
}).encode(), CurlWsFlag.TEXT)
|
|
238
|
+
|
|
239
|
+
# Process response
|
|
240
|
+
is_started = False
|
|
241
|
+
msg = None
|
|
242
|
+
image_prompt: str = None
|
|
243
|
+
last_msg = None
|
|
244
|
+
streaming_text = ""
|
|
245
|
+
|
|
246
|
+
try:
|
|
247
|
+
while True:
|
|
248
|
+
try:
|
|
249
|
+
msg = wss.recv()[0]
|
|
250
|
+
msg = json.loads(msg)
|
|
251
|
+
except:
|
|
252
|
+
break
|
|
253
|
+
last_msg = msg
|
|
254
|
+
if msg.get("event") == "appendText":
|
|
255
|
+
is_started = True
|
|
256
|
+
content = msg.get("text")
|
|
257
|
+
streaming_text += content
|
|
258
|
+
resp = {"text": content}
|
|
259
|
+
yield resp if raw else resp
|
|
260
|
+
elif msg.get("event") == "generatingImage":
|
|
261
|
+
image_prompt = msg.get("prompt")
|
|
262
|
+
elif msg.get("event") == "imageGenerated":
|
|
263
|
+
yield {"type": "image", "url": msg.get("url"), "prompt": image_prompt, "preview": msg.get("thumbnailUrl")}
|
|
264
|
+
elif msg.get("event") == "done":
|
|
265
|
+
break
|
|
266
|
+
elif msg.get("event") == "replaceText":
|
|
267
|
+
content = msg.get("text")
|
|
268
|
+
streaming_text += content
|
|
269
|
+
resp = {"text": content}
|
|
270
|
+
yield resp if raw else resp
|
|
271
|
+
elif msg.get("event") == "error":
|
|
272
|
+
raise exceptions.FailedToGenerateResponseError(f"Error: {msg}")
|
|
273
|
+
|
|
274
|
+
if not is_started:
|
|
275
|
+
raise exceptions.FailedToGenerateResponseError(f"Invalid response: {last_msg}")
|
|
276
|
+
|
|
277
|
+
# Update conversation history
|
|
278
|
+
self.conversation.update_chat_history(prompt, streaming_text)
|
|
279
|
+
self.last_response = {"text": streaming_text}
|
|
280
|
+
|
|
281
|
+
finally:
|
|
282
|
+
wss.close()
|
|
283
|
+
|
|
284
|
+
except requests.RequestException as e:
|
|
285
|
+
raise exceptions.FailedToGenerateResponseError(f"Request failed: {str(e)}")
|
|
286
|
+
except Exception as e:
|
|
287
|
+
raise exceptions.FailedToGenerateResponseError(f"Error: {str(e)}")
|
|
288
|
+
|
|
289
|
+
def for_non_stream():
|
|
290
|
+
streaming_text = ""
|
|
291
|
+
for response in for_stream():
|
|
292
|
+
if isinstance(response, dict) and "text" in response:
|
|
293
|
+
streaming_text += response["text"]
|
|
294
|
+
self.last_response = {"text": streaming_text}
|
|
295
|
+
return self.last_response
|
|
296
|
+
|
|
297
|
+
return for_stream() if stream else for_non_stream()
|
|
298
|
+
|
|
299
|
+
def chat(
|
|
300
|
+
self,
|
|
301
|
+
prompt: str,
|
|
302
|
+
stream: bool = True,
|
|
303
|
+
optimizer: str = None,
|
|
304
|
+
conversationally: bool = False,
|
|
305
|
+
images = None,
|
|
306
|
+
api_key: str = None,
|
|
307
|
+
**kwargs
|
|
308
|
+
) -> Union[str, Generator]:
|
|
309
|
+
def for_stream():
|
|
310
|
+
for response in self.ask(prompt, True, optimizer=optimizer,
|
|
311
|
+
conversationally=conversationally,
|
|
312
|
+
images=images, api_key=api_key, **kwargs):
|
|
313
|
+
if isinstance(response, dict) and "text" in response:
|
|
314
|
+
yield response["text"]
|
|
315
|
+
elif isinstance(response, dict) and "type" in response and response["type"] == "image":
|
|
316
|
+
yield f"\n\n"
|
|
317
|
+
|
|
318
|
+
def for_non_stream():
|
|
319
|
+
response = self.ask(prompt, False, optimizer=optimizer,
|
|
320
|
+
conversationally=conversationally,
|
|
321
|
+
images=images, api_key=api_key, **kwargs)
|
|
322
|
+
return self.get_message(response)
|
|
323
|
+
|
|
324
|
+
return for_stream() if stream else for_non_stream()
|
|
325
|
+
|
|
326
|
+
def get_message(self, response: dict) -> str:
|
|
327
|
+
assert isinstance(response, dict), "Response should be of dict data-type only"
|
|
328
|
+
return response.get("text", "")
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
async def get_access_token_and_cookies(url: str, proxy: str = None, target: str = "ChatAI"):
|
|
332
|
+
browser, stop_browser = await get_nodriver(proxy=proxy, user_data_dir="copilot")
|
|
333
|
+
try:
|
|
334
|
+
page = await browser.get(url)
|
|
335
|
+
access_token = None
|
|
336
|
+
while access_token is None:
|
|
337
|
+
access_token = await page.evaluate("""
|
|
338
|
+
(() => {
|
|
339
|
+
for (var i = 0; i < localStorage.length; i++) {
|
|
340
|
+
try {
|
|
341
|
+
item = JSON.parse(localStorage.getItem(localStorage.key(i)));
|
|
342
|
+
if (item.credentialType == "AccessToken"
|
|
343
|
+
&& item.expiresOn > Math.floor(Date.now() / 1000)
|
|
344
|
+
&& item.target.includes("target")) {
|
|
345
|
+
return item.secret;
|
|
346
|
+
}
|
|
347
|
+
} catch(e) {}
|
|
348
|
+
}
|
|
349
|
+
})()
|
|
350
|
+
""".replace('"target"', json.dumps(target)))
|
|
351
|
+
if access_token is None:
|
|
352
|
+
await asyncio.sleep(1)
|
|
353
|
+
cookies = {}
|
|
354
|
+
for c in await page.send(nodriver.cdp.network.get_cookies([url])):
|
|
355
|
+
cookies[c.name] = c.value
|
|
356
|
+
await page.close()
|
|
357
|
+
return access_token, cookies
|
|
358
|
+
finally:
|
|
359
|
+
stop_browser()
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def readHAR(url: str):
|
|
363
|
+
api_key = None
|
|
364
|
+
cookies = None
|
|
365
|
+
har_files = []
|
|
366
|
+
# Look for HAR files in common locations
|
|
367
|
+
har_paths = [
|
|
368
|
+
os.path.join(os.path.expanduser("~"), "Downloads"),
|
|
369
|
+
os.path.join(os.path.expanduser("~"), "Desktop")
|
|
370
|
+
]
|
|
371
|
+
for path in har_paths:
|
|
372
|
+
if os.path.exists(path):
|
|
373
|
+
for file in os.listdir(path):
|
|
374
|
+
if file.endswith(".har"):
|
|
375
|
+
har_files.append(os.path.join(path, file))
|
|
376
|
+
|
|
377
|
+
for path in har_files:
|
|
378
|
+
with open(path, 'rb') as file:
|
|
379
|
+
try:
|
|
380
|
+
harFile = json.loads(file.read())
|
|
381
|
+
except json.JSONDecodeError:
|
|
382
|
+
# Error: not a HAR file!
|
|
383
|
+
continue
|
|
384
|
+
for v in harFile['log']['entries']:
|
|
385
|
+
if v['request']['url'].startswith(url):
|
|
386
|
+
v_headers = {h['name'].lower(): h['value'] for h in v['request']['headers']}
|
|
387
|
+
if "authorization" in v_headers:
|
|
388
|
+
api_key = v_headers["authorization"].split(maxsplit=1).pop()
|
|
389
|
+
if v['request']['cookies']:
|
|
390
|
+
cookies = {c['name']: c['value'] for c in v['request']['cookies']}
|
|
391
|
+
if api_key is None:
|
|
392
|
+
raise NoValidHarFileError("No access token found in .har files")
|
|
393
|
+
|
|
394
|
+
return api_key, cookies
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
# def get_clarity() -> bytes:
|
|
398
|
+
# body = base64.b64decode("H4sIAAAAAAAAA23RwU7DMAwG4HfJ2aqS2E5ibjxH1cMOnQYqYZvUTQPx7vyJRGGAemj01XWcP+9udg+j80MetDhSyrEISc5GrqrtZnmaTydHbrdUnSsWYT2u+8Obo0Ce/IQvaDBmjkwhUlKKIRNHmQgosqEArWPRDQMx90rxeUMPzB1j+UJvwNIxhTvsPcXyX1T+rizE4juK3mEEhpAUg/JvzW1/+U/tB1LATmhqotoiweMea50PLy2vui4LOY3XfD1dwnkor5fn/e18XBFgm6fHjSzZmCyV7d3aRByAEYextaTHEH3i5pgKGVP/s+DScE5PuLKIpW6FnCi1gY3Rbpqmj0/DI/+L7QEAAA==")
|
|
399
|
+
# return body
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
async def get_nodriver(proxy=None, user_data_dir=None):
|
|
403
|
+
browser = await nodriver.Browser(
|
|
404
|
+
headless=True,
|
|
405
|
+
proxy=proxy,
|
|
406
|
+
user_data_dir=user_data_dir
|
|
407
|
+
)
|
|
408
|
+
return browser, lambda: browser.close()
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
if __name__ == "__main__":
|
|
412
|
+
from rich import print
|
|
413
|
+
ai = Copilot(timeout=900)
|
|
414
|
+
response = ai.chat(input("> "), stream=True)
|
|
415
|
+
for chunk in response:
|
|
416
|
+
print(chunk, end="", flush=True)
|