webscout 6.8__py3-none-any.whl → 6.9__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.

@@ -1,227 +0,0 @@
1
- import requests
2
- import json
3
- from typing import Any, AsyncGenerator, Dict
4
-
5
- from webscout.AIutel import Optimizers
6
- from webscout.AIutel import Conversation
7
- from webscout.AIutel import AwesomePrompts, sanitize_stream
8
- from webscout.AIbase import Provider, AsyncProvider
9
- from webscout import exceptions
10
-
11
- class DeepSeek(Provider):
12
- """
13
- A class to interact with the Deepseek API.
14
- """
15
-
16
- AVAILABLE_MODELS = [
17
- "deepseek_chat",
18
- "deepseek_code"
19
- ]
20
-
21
- def __init__(
22
- self,
23
- api_key,
24
- model: str = "deepseek_chat",
25
- temperature: float = 0,
26
- is_conversation: bool = True,
27
- timeout: int = 30,
28
- max_tokens: int = 4000,
29
- intro: str = None,
30
- filepath: str = None,
31
- update_file: bool = True,
32
- proxies: dict = {},
33
- history_offset: int = 10250,
34
- act: str = None,
35
- ) -> None:
36
- """
37
- Initializes the Deepseek API with given parameters.
38
-
39
- Args:
40
- api_key (str): The API token for authentication.
41
- model (str, optional): The AI model to use for text generation.
42
- Defaults to "deepseek_chat".
43
- Options: "deepseek_chat", "deepseek_code".
44
- temperature (float): The temperature parameter for the model.
45
- is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
46
- timeout (int, optional): Http request timeout. Defaults to 30.
47
- intro (str, optional): Conversation introductory prompt. Defaults to None.
48
- filepath (str, optional): Path to file containing conversation history. Defaults to None.
49
- update_file (bool, optional): Add new prompts and responses to the file. Defaults to True.
50
- proxies (dict, optional): Http request proxies. Defaults to {}.
51
- history_offset (int, optional): Limit conversation history to this number of last texts. Defaults to 10250.
52
- act (str|int, optional): Awesome prompt key or index. (Used as intro). Defaults to None.
53
- """
54
- if model not in self.AVAILABLE_MODELS:
55
- raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
56
-
57
- self.api_token = api_key
58
- self.api_endpoint = "https://chat.deepseek.com/api/v0/chat/completions"
59
- self.model = model
60
- self.temperature = temperature
61
- self.session = requests.Session()
62
- self.is_conversation = is_conversation
63
- self.max_tokens_to_sample = max_tokens
64
- self.timeout = timeout
65
- self.last_response = {}
66
- self.headers = {
67
- "accept": "*/*",
68
- "accept-encoding": "gzip, deflate, br, zstd",
69
- "accept-language": "en-US,en;q=0.9,en-IN;q=0.8",
70
- "authorization": f"Bearer {self.api_token}",
71
- "content-length": "128",
72
- "content-type": "application/json",
73
- "dnt": "1",
74
- "origin": "https://chat.deepseek.com",
75
- "priority": "u=1, i",
76
- "referer": "https://chat.deepseek.com/",
77
- "sec-ch-ua": '"Chromium";v="130", "Microsoft Edge";v="130", "Not?A_Brand";v="99"',
78
- "sec-ch-ua-mobile": "?0",
79
- "sec-ch-ua-platform": '"Windows"',
80
- "sec-fetch-dest": "empty",
81
- "sec-fetch-mode": "cors",
82
- "sec-fetch-site": "same-origin",
83
- "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
84
- "x-app-version": "20241018.0"
85
- }
86
- self.__available_optimizers = (
87
- method
88
- for method in dir(Optimizers)
89
- if callable(getattr(Optimizers, method)) and not method.startswith("__")
90
- )
91
- self.session.headers.update(self.headers)
92
- Conversation.intro = (
93
- AwesomePrompts().get_act(
94
- act, raise_not_found=True, default=None, case_insensitive=True
95
- )
96
- if act
97
- else intro or Conversation.intro
98
- )
99
- self.conversation = Conversation(
100
- is_conversation, self.max_tokens_to_sample, filepath, update_file
101
- )
102
- self.conversation.history_offset = history_offset
103
- self.session.proxies = proxies
104
-
105
- def ask(
106
- self,
107
- prompt: str,
108
- stream: bool = False,
109
- raw: bool = False,
110
- optimizer: str = None,
111
- conversationally: bool = False,
112
- ) -> Dict[str, Any]:
113
- """
114
- Sends a prompt to the Deepseek AI API and returns the response.
115
-
116
- Args:
117
- prompt: The text prompt to generate text from.
118
- stream (bool, optional): Whether to stream the response. Defaults to False.
119
- raw (bool, optional): Whether to return the raw response. Defaults to False.
120
- optimizer (str, optional): The name of the optimizer to use. Defaults to None.
121
- conversationally (bool, optional): Whether to chat conversationally. Defaults to False.
122
-
123
- Returns:
124
- The response from the API.
125
- """
126
- conversation_prompt = self.conversation.gen_complete_prompt(prompt)
127
- if optimizer:
128
- if optimizer in self.__available_optimizers:
129
- conversation_prompt = getattr(Optimizers, optimizer)(
130
- conversation_prompt if conversationally else prompt
131
- )
132
- else:
133
- raise Exception(
134
- f"Optimizer is not one of {self.__available_optimizers}"
135
- )
136
-
137
- payload = {
138
- "message": conversation_prompt,
139
- "stream": True,
140
- "model_preference": None,
141
- "model_class": self.model,
142
- "temperature": self.temperature
143
- }
144
-
145
- def for_stream():
146
- response = self.session.post(
147
- self.api_endpoint, json=payload, headers=self.headers, stream=True, timeout=self.timeout
148
- )
149
-
150
- if not response.ok:
151
- raise exceptions.FailedToGenerateResponseError(
152
- f"Failed to generate response - ({response.status_code}, {response.reason})"
153
- )
154
- streaming_response = ""
155
- for line in response.iter_lines():
156
- if line:
157
- json_line = json.loads(line.decode('utf-8').split('data: ')[1])
158
- if 'choices' in json_line and len(json_line['choices']) > 0:
159
- delta_content = json_line['choices'][0].get('delta', {}).get('content')
160
- if delta_content:
161
- streaming_response += delta_content
162
- yield delta_content if raw else dict(text=delta_content)
163
- self.last_response.update(dict(text=streaming_response))
164
- self.conversation.update_chat_history(
165
- prompt, self.get_message(self.last_response)
166
- )
167
-
168
- def for_non_stream():
169
- for _ in for_stream():
170
- pass
171
- return self.last_response
172
-
173
- return for_stream() if stream else for_non_stream()
174
-
175
- def chat(
176
- self,
177
- prompt: str,
178
- stream: bool = False,
179
- optimizer: str = None,
180
- conversationally: bool = False,
181
- ) -> str:
182
- """Generate response `str`
183
- Args:
184
- prompt (str): Prompt to be send.
185
- stream (bool, optional): Flag for streaming response. Defaults to False.
186
- optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
187
- conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
188
- Returns:
189
- str: Response generated
190
- """
191
-
192
- def for_stream():
193
- for response in self.ask(
194
- prompt, True, optimizer=optimizer, conversationally=conversationally
195
- ):
196
- yield self.get_message(response)
197
-
198
- def for_non_stream():
199
- return self.get_message(
200
- self.ask(
201
- prompt,
202
- False,
203
- optimizer=optimizer,
204
- conversationally=conversationally,
205
- )
206
- )
207
-
208
- return for_stream() if stream else for_non_stream()
209
-
210
- def get_message(self, response: dict) -> str:
211
- """Retrieves message only from response
212
-
213
- Args:
214
- response (dict): Response generated by `self.ask`
215
-
216
- Returns:
217
- str: Message extracted
218
- """
219
- assert isinstance(response, dict), "Response should be of dict data-type only"
220
- return response["text"]
221
-
222
- if __name__ == '__main__':
223
- from rich import print
224
- ai = DeepSeek(api_key="", timeout=5000)
225
- response = ai.chat("write a poem about AI", stream=True)
226
- for chunk in response:
227
- print(chunk, end="", flush=True)
@@ -1,225 +0,0 @@
1
- """
2
- ZeroDir: A zero-dependency app directories management library
3
-
4
- Provides cross-platform directory management for application data,
5
- configuration, and cache without external dependencies.
6
- """
7
-
8
- import os
9
- import sys
10
- import json
11
- import platform
12
- import tempfile
13
- import shutil
14
- import hashlib
15
- import time
16
- import datetime
17
-
18
- class ZeroDirs:
19
- def __init__(self, app_name, app_author=None):
20
- """
21
- Initialize ZeroDirs with application details
22
-
23
- :param app_name: Name of the application
24
- :param app_author: Author/Company name (optional)
25
- """
26
- self.app_name = app_name
27
- self.app_author = app_author or os.getlogin()
28
- self._init_dirs()
29
-
30
- def _init_dirs(self):
31
- """Initialize application directories"""
32
- self.user_data_dir = self._get_user_data_dir()
33
- self.user_config_dir = self._get_user_config_dir()
34
- self.user_cache_dir = self._get_user_cache_dir()
35
- self.user_log_dir = self._get_user_log_dir()
36
- self.temp_dir = self._get_temp_dir()
37
-
38
- # Create directories if they don't exist
39
- for directory in [
40
- self.user_data_dir,
41
- self.user_config_dir,
42
- self.user_cache_dir,
43
- self.user_log_dir,
44
- self.temp_dir
45
- ]:
46
- os.makedirs(directory, exist_ok=True)
47
-
48
- def _get_user_data_dir(self):
49
- """Get user data directory"""
50
- system = platform.system().lower()
51
- if system == 'windows':
52
- base = os.path.expandvars('%LOCALAPPDATA%')
53
- return os.path.join(base, self.app_author, self.app_name)
54
- elif system == 'darwin': # macOS
55
- return os.path.expanduser(f'~/Library/Application Support/{self.app_name}')
56
- else: # Linux and other Unix-like
57
- xdg_data_home = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
58
- return os.path.join(xdg_data_home, self.app_name)
59
-
60
- def _get_user_config_dir(self):
61
- """Get user configuration directory"""
62
- system = platform.system().lower()
63
- if system == 'windows':
64
- base = os.path.expandvars('%APPDATA%')
65
- return os.path.join(base, self.app_author, self.app_name)
66
- elif system == 'darwin': # macOS
67
- return os.path.expanduser(f'~/Library/Preferences/{self.app_name}')
68
- else: # Linux and other Unix-like
69
- xdg_config_home = os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')
70
- return os.path.join(xdg_config_home, self.app_name)
71
-
72
- def _get_user_cache_dir(self):
73
- """Get user cache directory"""
74
- system = platform.system().lower()
75
- if system == 'windows':
76
- base = os.path.expandvars('%LOCALAPPDATA%')
77
- return os.path.join(base, self.app_author, self.app_name, 'Cache')
78
- elif system == 'darwin': # macOS
79
- return os.path.expanduser(f'~/Library/Caches/{self.app_name}')
80
- else: # Linux and other Unix-like
81
- xdg_cache_home = os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache')
82
- return os.path.join(xdg_cache_home, self.app_name)
83
-
84
- def _get_user_log_dir(self):
85
- """Get user log directory"""
86
- system = platform.system().lower()
87
- if system == 'windows':
88
- base = os.path.expandvars('%LOCALAPPDATA%')
89
- return os.path.join(base, self.app_author, self.app_name, 'Logs')
90
- elif system == 'darwin': # macOS
91
- return os.path.expanduser(f'~/Library/Logs/{self.app_name}')
92
- else: # Linux and other Unix-like
93
- xdg_data_home = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
94
- return os.path.join(xdg_data_home, self.app_name, 'logs')
95
-
96
- def _get_temp_dir(self):
97
- """Get temporary directory for the application"""
98
- return os.path.join(tempfile.gettempdir(), f'{self.app_name}_temp')
99
-
100
- def save_config(self, config_data, filename='config.json'):
101
- """
102
- Save configuration data to config directory
103
-
104
- :param config_data: Dictionary of configuration data
105
- :param filename: Name of the config file (default: config.json)
106
- :return: Path to saved config file
107
- """
108
- config_path = os.path.join(self.user_config_dir, filename)
109
- with open(config_path, 'w') as f:
110
- json.dump(config_data, f, indent=4)
111
- return config_path
112
-
113
- def load_config(self, filename='config.json'):
114
- """
115
- Load configuration data from config directory
116
-
117
- :param filename: Name of the config file (default: config.json)
118
- :return: Dictionary of configuration data or None if file doesn't exist
119
- """
120
- config_path = os.path.join(self.user_config_dir, filename)
121
- if os.path.exists(config_path):
122
- with open(config_path, 'r') as f:
123
- return json.load(f)
124
- return None
125
-
126
- def cache_file(self, content, filename=None, extension=None):
127
- """
128
- Cache a file with optional naming and extension
129
-
130
- :param content: File content or bytes
131
- :param filename: Optional custom filename
132
- :param extension: Optional file extension
133
- :return: Path to cached file
134
- """
135
- if not filename:
136
- # Generate a hash-based filename if not provided
137
- content_hash = hashlib.md5(str(content).encode()).hexdigest()
138
- filename = f'{content_hash}{extension or ""}'
139
-
140
- cache_path = os.path.join(self.user_cache_dir, filename)
141
-
142
- # Write content to file
143
- with open(cache_path, 'wb' if isinstance(content, bytes) else 'w') as f:
144
- f.write(content)
145
-
146
- return cache_path
147
-
148
- def clear_cache(self, max_age_days=30):
149
- """
150
- Clear cache directory, optionally removing files older than max_age_days
151
-
152
- :param max_age_days: Maximum age of files to keep (default: 30 days)
153
- :return: Number of files deleted
154
- """
155
- current_time = time.time()
156
-
157
- deleted_count = 0
158
- for filename in os.listdir(self.user_cache_dir):
159
- filepath = os.path.join(self.user_cache_dir, filename)
160
-
161
- # Check file age
162
- file_age_days = (current_time - os.path.getctime(filepath)) / (24 * 3600)
163
-
164
- if file_age_days > max_age_days:
165
- try:
166
- os.remove(filepath)
167
- deleted_count += 1
168
- except Exception:
169
- pass
170
-
171
- return deleted_count
172
-
173
- def log(self, message, filename='app.log', level='INFO'):
174
- """
175
- Log a message to the log directory
176
-
177
- :param message: Log message
178
- :param filename: Log filename (default: app.log)
179
- :param level: Log level (default: INFO)
180
- """
181
- log_path = os.path.join(self.user_log_dir, filename)
182
-
183
- with open(log_path, 'a') as log_file:
184
- timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
185
- log_file.write(f'[{level}] {timestamp}: {message}\n')
186
-
187
- def user_data_dir(app_name, app_author=None):
188
- """
189
- Quick function to get user data directory
190
-
191
- :param app_name: Name of the application
192
- :param app_author: Author/Company name (optional)
193
- :return: Path to user data directory
194
- """
195
- return ZeroDirs(app_name, app_author).user_data_dir
196
-
197
- def user_config_dir(app_name, app_author=None):
198
- """
199
- Quick function to get user config directory
200
-
201
- :param app_name: Name of the application
202
- :param app_author: Author/Company name (optional)
203
- :return: Path to user config directory
204
- """
205
- return ZeroDirs(app_name, app_author).user_config_dir
206
-
207
- def user_cache_dir(app_name, app_author=None):
208
- """
209
- Quick function to get user cache directory
210
-
211
- :param app_name: Name of the application
212
- :param app_author: Author/Company name (optional)
213
- :return: Path to user cache directory
214
- """
215
- return ZeroDirs(app_name, app_author).user_cache_dir
216
-
217
- def user_log_dir(app_name, app_author=None):
218
- """
219
- Quick function to get user log directory
220
-
221
- :param app_name: Name of the application
222
- :param app_author: Author/Company name (optional)
223
- :return: Path to user log directory
224
- """
225
- return ZeroDirs(app_name, app_author).user_log_dir
File without changes