webscout 8.3.5__py3-none-any.whl → 8.3.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/Bard.py +12 -6
- webscout/DWEBS.py +66 -57
- webscout/Provider/{UNFINISHED → AISEARCH}/PERPLEXED_search.py +34 -74
- webscout/Provider/AISEARCH/__init__.py +1 -1
- webscout/Provider/Deepinfra.py +6 -0
- webscout/Provider/Flowith.py +6 -1
- webscout/Provider/GithubChat.py +1 -0
- webscout/Provider/GptOss.py +207 -0
- webscout/Provider/Kimi.py +445 -0
- webscout/Provider/Netwrck.py +3 -6
- webscout/Provider/OPENAI/README.md +2 -1
- webscout/Provider/OPENAI/TogetherAI.py +50 -55
- webscout/Provider/OPENAI/__init__.py +4 -2
- webscout/Provider/OPENAI/copilot.py +20 -4
- webscout/Provider/OPENAI/deepinfra.py +6 -0
- webscout/Provider/OPENAI/e2b.py +60 -8
- webscout/Provider/OPENAI/flowith.py +4 -3
- webscout/Provider/OPENAI/generate_api_key.py +48 -0
- webscout/Provider/OPENAI/gptoss.py +288 -0
- webscout/Provider/OPENAI/kimi.py +469 -0
- webscout/Provider/OPENAI/netwrck.py +8 -12
- webscout/Provider/OPENAI/refact.py +274 -0
- webscout/Provider/OPENAI/textpollinations.py +3 -6
- webscout/Provider/OPENAI/toolbaz.py +1 -0
- webscout/Provider/TTI/bing.py +14 -2
- webscout/Provider/TTI/together.py +10 -9
- webscout/Provider/TTS/README.md +0 -1
- webscout/Provider/TTS/__init__.py +0 -1
- webscout/Provider/TTS/base.py +479 -159
- webscout/Provider/TTS/deepgram.py +409 -156
- webscout/Provider/TTS/elevenlabs.py +425 -111
- webscout/Provider/TTS/freetts.py +317 -140
- webscout/Provider/TTS/gesserit.py +192 -128
- webscout/Provider/TTS/murfai.py +248 -113
- webscout/Provider/TTS/openai_fm.py +347 -129
- webscout/Provider/TTS/speechma.py +620 -586
- webscout/Provider/TextPollinationsAI.py +3 -6
- webscout/Provider/TogetherAI.py +50 -55
- webscout/Provider/UNFINISHED/VercelAIGateway.py +339 -0
- webscout/Provider/__init__.py +2 -90
- webscout/Provider/cerebras.py +83 -33
- webscout/Provider/copilot.py +42 -23
- webscout/Provider/toolbaz.py +1 -0
- webscout/conversation.py +22 -20
- webscout/sanitize.py +14 -10
- webscout/scout/README.md +20 -23
- webscout/scout/core/crawler.py +125 -38
- webscout/scout/core/scout.py +26 -5
- webscout/version.py +1 -1
- webscout/webscout_search.py +13 -6
- webscout/webscout_search_async.py +10 -8
- webscout/yep_search.py +13 -5
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/METADATA +2 -1
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/RECORD +59 -56
- webscout/Provider/Glider.py +0 -225
- webscout/Provider/OPENAI/c4ai.py +0 -394
- webscout/Provider/OPENAI/glider.py +0 -330
- webscout/Provider/TTS/sthir.py +0 -94
- /webscout/Provider/{samurai.py → UNFINISHED/samurai.py} +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/WHEEL +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/entry_points.txt +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/licenses/LICENSE.md +0 -0
- {webscout-8.3.5.dist-info → webscout-8.3.6.dist-info}/top_level.txt +0 -0
|
@@ -1,330 +0,0 @@
|
|
|
1
|
-
import requests
|
|
2
|
-
import json
|
|
3
|
-
import time
|
|
4
|
-
import uuid
|
|
5
|
-
from typing import List, Dict, Optional, Union, Generator, Any
|
|
6
|
-
|
|
7
|
-
# Import base classes and utility structures
|
|
8
|
-
from .base import OpenAICompatibleProvider, BaseChat, BaseCompletions
|
|
9
|
-
from .utils import (
|
|
10
|
-
ChatCompletionChunk, ChatCompletion, Choice, ChoiceDelta,
|
|
11
|
-
ChatCompletionMessage, CompletionUsage
|
|
12
|
-
)
|
|
13
|
-
|
|
14
|
-
# Attempt to import LitAgent, fallback if not available
|
|
15
|
-
try:
|
|
16
|
-
from webscout.litagent import LitAgent
|
|
17
|
-
except ImportError:
|
|
18
|
-
# Define a dummy LitAgent if webscout is not installed or accessible
|
|
19
|
-
class LitAgent:
|
|
20
|
-
def generate_fingerprint(self, browser: str = "chrome") -> Dict[str, Any]:
|
|
21
|
-
# Return minimal default headers if LitAgent is unavailable
|
|
22
|
-
print("Warning: LitAgent not found. Using default minimal headers.")
|
|
23
|
-
return {
|
|
24
|
-
"accept": "*/*",
|
|
25
|
-
"accept_language": "en-US,en;q=0.9",
|
|
26
|
-
"platform": "Windows",
|
|
27
|
-
"sec_ch_ua": '"Not/A)Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
|
|
28
|
-
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
|
|
29
|
-
"browser_type": browser,
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
# --- Glider Client ---
|
|
33
|
-
|
|
34
|
-
class Completions(BaseCompletions):
|
|
35
|
-
def __init__(self, client: 'Glider'):
|
|
36
|
-
self._client = client
|
|
37
|
-
|
|
38
|
-
def create(
|
|
39
|
-
self,
|
|
40
|
-
*,
|
|
41
|
-
model: str,
|
|
42
|
-
messages: List[Dict[str, str]],
|
|
43
|
-
max_tokens: Optional[int] = 2049,
|
|
44
|
-
stream: bool = False,
|
|
45
|
-
temperature: Optional[float] = None,
|
|
46
|
-
top_p: Optional[float] = None,
|
|
47
|
-
timeout: Optional[int] = None,
|
|
48
|
-
proxies: Optional[Dict[str, str]] = None,
|
|
49
|
-
**kwargs: Any
|
|
50
|
-
) -> Union[ChatCompletion, Generator[ChatCompletionChunk, None, None]]:
|
|
51
|
-
"""
|
|
52
|
-
Creates a model response for the given chat conversation.
|
|
53
|
-
Mimics openai.chat.completions.create
|
|
54
|
-
"""
|
|
55
|
-
# Prepare the payload for Glider API
|
|
56
|
-
payload = {
|
|
57
|
-
"messages": messages,
|
|
58
|
-
"model": self._client.convert_model_name(model),
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
# Add optional parameters if provided
|
|
62
|
-
if max_tokens is not None and max_tokens > 0:
|
|
63
|
-
payload["max_tokens"] = max_tokens
|
|
64
|
-
|
|
65
|
-
if temperature is not None:
|
|
66
|
-
payload["temperature"] = temperature
|
|
67
|
-
|
|
68
|
-
if top_p is not None:
|
|
69
|
-
payload["top_p"] = top_p
|
|
70
|
-
|
|
71
|
-
# Add any additional parameters
|
|
72
|
-
payload.update(kwargs)
|
|
73
|
-
|
|
74
|
-
request_id = f"chatcmpl-{uuid.uuid4()}"
|
|
75
|
-
created_time = int(time.time())
|
|
76
|
-
|
|
77
|
-
if stream:
|
|
78
|
-
return self._create_stream(request_id, created_time, model, payload, timeout, proxies)
|
|
79
|
-
else:
|
|
80
|
-
return self._create_non_stream(request_id, created_time, model, payload, timeout, proxies)
|
|
81
|
-
|
|
82
|
-
def _create_stream(
|
|
83
|
-
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
|
|
84
|
-
) -> Generator[ChatCompletionChunk, None, None]:
|
|
85
|
-
try:
|
|
86
|
-
response = self._client.session.post(
|
|
87
|
-
self._client.api_endpoint,
|
|
88
|
-
headers=self._client.headers,
|
|
89
|
-
json=payload,
|
|
90
|
-
stream=True,
|
|
91
|
-
timeout=timeout or self._client.timeout,
|
|
92
|
-
proxies=proxies or getattr(self._client, "proxies", None)
|
|
93
|
-
)
|
|
94
|
-
response.raise_for_status()
|
|
95
|
-
|
|
96
|
-
# Track token usage across chunks
|
|
97
|
-
prompt_tokens = 0
|
|
98
|
-
completion_tokens = 0
|
|
99
|
-
total_tokens = 0
|
|
100
|
-
|
|
101
|
-
for line in response.iter_lines():
|
|
102
|
-
if line:
|
|
103
|
-
decoded_line = line.decode('utf-8').strip()
|
|
104
|
-
|
|
105
|
-
if decoded_line.startswith("data: "):
|
|
106
|
-
json_str = decoded_line[6:]
|
|
107
|
-
if json_str == "[DONE]":
|
|
108
|
-
# Format the final [DONE] marker in OpenAI format
|
|
109
|
-
# print("data: [DONE]")
|
|
110
|
-
break
|
|
111
|
-
|
|
112
|
-
try:
|
|
113
|
-
data = json.loads(json_str)
|
|
114
|
-
choice_data = data.get('choices', [{}])[0]
|
|
115
|
-
delta_data = choice_data.get('delta', {})
|
|
116
|
-
finish_reason = choice_data.get('finish_reason')
|
|
117
|
-
|
|
118
|
-
# Update token counts if available
|
|
119
|
-
usage_data = data.get('usage', {})
|
|
120
|
-
if usage_data:
|
|
121
|
-
prompt_tokens = usage_data.get('prompt_tokens', prompt_tokens)
|
|
122
|
-
completion_tokens = usage_data.get('completion_tokens', completion_tokens)
|
|
123
|
-
total_tokens = usage_data.get('total_tokens', total_tokens)
|
|
124
|
-
|
|
125
|
-
# Create the delta object
|
|
126
|
-
delta = ChoiceDelta(
|
|
127
|
-
content=delta_data.get('content'),
|
|
128
|
-
role=delta_data.get('role'),
|
|
129
|
-
tool_calls=delta_data.get('tool_calls')
|
|
130
|
-
)
|
|
131
|
-
|
|
132
|
-
# Create the choice object
|
|
133
|
-
choice = Choice(
|
|
134
|
-
index=choice_data.get('index', 0),
|
|
135
|
-
delta=delta,
|
|
136
|
-
finish_reason=finish_reason,
|
|
137
|
-
logprobs=choice_data.get('logprobs')
|
|
138
|
-
)
|
|
139
|
-
|
|
140
|
-
# Create the chunk object
|
|
141
|
-
chunk = ChatCompletionChunk(
|
|
142
|
-
id=request_id,
|
|
143
|
-
choices=[choice],
|
|
144
|
-
created=created_time,
|
|
145
|
-
model=model,
|
|
146
|
-
system_fingerprint=data.get('system_fingerprint')
|
|
147
|
-
)
|
|
148
|
-
|
|
149
|
-
# Convert chunk to dict using Pydantic's API
|
|
150
|
-
if hasattr(chunk, "model_dump"):
|
|
151
|
-
chunk_dict = chunk.model_dump(exclude_none=True)
|
|
152
|
-
else:
|
|
153
|
-
chunk_dict = chunk.dict(exclude_none=True)
|
|
154
|
-
|
|
155
|
-
# Add usage information to match OpenAI format
|
|
156
|
-
# Even if we don't have real token counts, include estimated usage
|
|
157
|
-
# This matches the format in the examples
|
|
158
|
-
usage_dict = {
|
|
159
|
-
"prompt_tokens": prompt_tokens or 10,
|
|
160
|
-
"completion_tokens": completion_tokens or (len(delta_data.get('content', '')) if delta_data.get('content') else 0),
|
|
161
|
-
"total_tokens": total_tokens or (10 + (len(delta_data.get('content', '')) if delta_data.get('content') else 0)),
|
|
162
|
-
"estimated_cost": None
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
# Update completion_tokens and total_tokens as we receive more content
|
|
166
|
-
if delta_data.get('content'):
|
|
167
|
-
completion_tokens += 1
|
|
168
|
-
total_tokens = prompt_tokens + completion_tokens
|
|
169
|
-
usage_dict["completion_tokens"] = completion_tokens
|
|
170
|
-
usage_dict["total_tokens"] = total_tokens
|
|
171
|
-
|
|
172
|
-
chunk_dict["usage"] = usage_dict
|
|
173
|
-
|
|
174
|
-
# Format the response in OpenAI format exactly as requested
|
|
175
|
-
# We need to print the raw string and also yield the chunk object
|
|
176
|
-
# This ensures both the console output and the returned object are correct
|
|
177
|
-
# print(f"data: {json.dumps(chunk_dict)}")
|
|
178
|
-
|
|
179
|
-
# Return the chunk object for internal processing
|
|
180
|
-
yield chunk
|
|
181
|
-
except json.JSONDecodeError:
|
|
182
|
-
print(f"Warning: Could not decode JSON line: {json_str}")
|
|
183
|
-
continue
|
|
184
|
-
except requests.exceptions.RequestException as e:
|
|
185
|
-
print(f"Error during Glider stream request: {e}")
|
|
186
|
-
raise IOError(f"Glider request failed: {e}") from e
|
|
187
|
-
except Exception as e:
|
|
188
|
-
print(f"Error processing Glider stream: {e}")
|
|
189
|
-
raise
|
|
190
|
-
|
|
191
|
-
def _create_non_stream(
|
|
192
|
-
self, request_id: str, created_time: int, model: str, payload: Dict[str, Any], timeout: Optional[int] = None, proxies: Optional[Dict[str, str]] = None
|
|
193
|
-
) -> ChatCompletion:
|
|
194
|
-
try:
|
|
195
|
-
response = self._client.session.post(
|
|
196
|
-
self._client.api_endpoint,
|
|
197
|
-
headers=self._client.headers,
|
|
198
|
-
json=payload,
|
|
199
|
-
timeout=timeout or self._client.timeout,
|
|
200
|
-
proxies=proxies or getattr(self._client, "proxies", None)
|
|
201
|
-
)
|
|
202
|
-
response.raise_for_status()
|
|
203
|
-
data = response.json()
|
|
204
|
-
|
|
205
|
-
choices_data = data.get('choices', [])
|
|
206
|
-
usage_data = data.get('usage', {})
|
|
207
|
-
|
|
208
|
-
choices = []
|
|
209
|
-
for choice_d in choices_data:
|
|
210
|
-
message_d = choice_d.get('message', {})
|
|
211
|
-
message = ChatCompletionMessage(
|
|
212
|
-
role=message_d.get('role', 'assistant'),
|
|
213
|
-
content=message_d.get('content', '')
|
|
214
|
-
)
|
|
215
|
-
choice = Choice(
|
|
216
|
-
index=choice_d.get('index', 0),
|
|
217
|
-
message=message,
|
|
218
|
-
finish_reason=choice_d.get('finish_reason', 'stop')
|
|
219
|
-
)
|
|
220
|
-
choices.append(choice)
|
|
221
|
-
|
|
222
|
-
usage = CompletionUsage(
|
|
223
|
-
prompt_tokens=usage_data.get('prompt_tokens', 0),
|
|
224
|
-
completion_tokens=usage_data.get('completion_tokens', 0),
|
|
225
|
-
total_tokens=usage_data.get('total_tokens', 0)
|
|
226
|
-
)
|
|
227
|
-
|
|
228
|
-
completion = ChatCompletion(
|
|
229
|
-
id=request_id,
|
|
230
|
-
choices=choices,
|
|
231
|
-
created=created_time,
|
|
232
|
-
model=data.get('model', model),
|
|
233
|
-
usage=usage,
|
|
234
|
-
)
|
|
235
|
-
return completion
|
|
236
|
-
|
|
237
|
-
except requests.exceptions.RequestException as e:
|
|
238
|
-
print(f"Error during Glider non-stream request: {e}")
|
|
239
|
-
raise IOError(f"Glider request failed: {e}") from e
|
|
240
|
-
except Exception as e:
|
|
241
|
-
print(f"Error processing Glider response: {e}")
|
|
242
|
-
raise
|
|
243
|
-
|
|
244
|
-
class Chat(BaseChat):
|
|
245
|
-
def __init__(self, client: 'Glider'):
|
|
246
|
-
self.completions = Completions(client)
|
|
247
|
-
|
|
248
|
-
class Glider(OpenAICompatibleProvider):
|
|
249
|
-
"""
|
|
250
|
-
OpenAI-compatible client for Glider.so API.
|
|
251
|
-
|
|
252
|
-
Usage:
|
|
253
|
-
client = Glider()
|
|
254
|
-
response = client.chat.completions.create(
|
|
255
|
-
model="chat-llama-3-1-70b",
|
|
256
|
-
messages=[{"role": "user", "content": "Hello!"}]
|
|
257
|
-
)
|
|
258
|
-
"""
|
|
259
|
-
|
|
260
|
-
AVAILABLE_MODELS = [
|
|
261
|
-
"chat-llama-3-1-8b",
|
|
262
|
-
"chat-llama-3-2-3b",
|
|
263
|
-
"chat-deepseek-r1-qwen-32b",
|
|
264
|
-
"chat-qwen-2-5-7b",
|
|
265
|
-
"chat-qwen-qwq-32b",
|
|
266
|
-
"deepseek-ai/DeepSeek-R1",
|
|
267
|
-
]
|
|
268
|
-
|
|
269
|
-
# No model mapping needed as we use the model names directly
|
|
270
|
-
|
|
271
|
-
def __init__(self, timeout: Optional[int] = None, browser: str = "chrome"):
|
|
272
|
-
"""
|
|
273
|
-
Initialize the Glider client.
|
|
274
|
-
|
|
275
|
-
Args:
|
|
276
|
-
timeout: Request timeout in seconds (None for no timeout)
|
|
277
|
-
browser: Browser to emulate in user agent
|
|
278
|
-
"""
|
|
279
|
-
self.timeout = timeout
|
|
280
|
-
self.api_endpoint = "https://glider.so/api/chat"
|
|
281
|
-
self.session = requests.Session()
|
|
282
|
-
|
|
283
|
-
agent = LitAgent()
|
|
284
|
-
fingerprint = agent.generate_fingerprint(browser)
|
|
285
|
-
|
|
286
|
-
self.headers = {
|
|
287
|
-
"Accept": fingerprint["accept"],
|
|
288
|
-
"Accept-Encoding": "gzip, deflate, br, zstd",
|
|
289
|
-
"Accept-Language": fingerprint["accept_language"],
|
|
290
|
-
"Content-Type": "application/json",
|
|
291
|
-
"Cache-Control": "no-cache",
|
|
292
|
-
"Connection": "keep-alive",
|
|
293
|
-
"Origin": "https://glider.so",
|
|
294
|
-
"Pragma": "no-cache",
|
|
295
|
-
"Referer": "https://glider.so/",
|
|
296
|
-
"Sec-Fetch-Dest": "empty",
|
|
297
|
-
"Sec-Fetch-Mode": "cors",
|
|
298
|
-
"Sec-Fetch-Site": "same-site",
|
|
299
|
-
"Sec-CH-UA": fingerprint["sec_ch_ua"] or '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
|
|
300
|
-
"Sec-CH-UA-Mobile": "?0",
|
|
301
|
-
"Sec-CH-UA-Platform": f'"{fingerprint["platform"]}"',
|
|
302
|
-
"User-Agent": fingerprint["user_agent"],
|
|
303
|
-
}
|
|
304
|
-
self.session.headers.update(self.headers)
|
|
305
|
-
self.chat = Chat(self)
|
|
306
|
-
|
|
307
|
-
def convert_model_name(self, model: str) -> str:
|
|
308
|
-
"""
|
|
309
|
-
Convert model names to ones supported by Glider.
|
|
310
|
-
|
|
311
|
-
Args:
|
|
312
|
-
model: Model name to convert
|
|
313
|
-
|
|
314
|
-
Returns:
|
|
315
|
-
Glider model name
|
|
316
|
-
"""
|
|
317
|
-
# If the model is already a valid Glider model, return it
|
|
318
|
-
if model in self.AVAILABLE_MODELS:
|
|
319
|
-
return model
|
|
320
|
-
|
|
321
|
-
# Default to the most capable model
|
|
322
|
-
print(f"Warning: Unknown model '{model}'. Using 'chat-llama-3-1-70b' instead.")
|
|
323
|
-
return "chat-llama-3-1-70b"
|
|
324
|
-
|
|
325
|
-
@property
|
|
326
|
-
def models(self):
|
|
327
|
-
class _ModelList:
|
|
328
|
-
def list(inner_self):
|
|
329
|
-
return type(self).AVAILABLE_MODELS
|
|
330
|
-
return _ModelList()
|
webscout/Provider/TTS/sthir.py
DELETED
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import time
|
|
2
|
-
import requests
|
|
3
|
-
import pathlib
|
|
4
|
-
import tempfile
|
|
5
|
-
from io import BytesIO
|
|
6
|
-
from webscout import exceptions
|
|
7
|
-
from webscout.litagent import LitAgent
|
|
8
|
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
9
|
-
from webscout.Provider.TTS import utils
|
|
10
|
-
from webscout.Provider.TTS.base import BaseTTSProvider
|
|
11
|
-
|
|
12
|
-
class SthirTTS(BaseTTSProvider):
|
|
13
|
-
"""
|
|
14
|
-
Text-to-speech provider using the Sthir.org TTS API.
|
|
15
|
-
"""
|
|
16
|
-
headers = {
|
|
17
|
-
"Content-Type": "application/json",
|
|
18
|
-
"User-Agent": LitAgent().random(),
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
all_voices = {
|
|
22
|
-
"aura-luna-en": "Sophie (American, Feminine)",
|
|
23
|
-
"aura-stella-en": "Isabella (American, Feminine)",
|
|
24
|
-
"aura-athena-en": "Emma (British, Feminine)",
|
|
25
|
-
"aura-hera-en": "Victoria (American, Feminine)",
|
|
26
|
-
"aura-asteria-en": "Maria (American, Feminine)",
|
|
27
|
-
"aura-arcas-en": "Alex (American, Masculine)",
|
|
28
|
-
"aura-zeus-en": "Thomas (American, Masculine)",
|
|
29
|
-
"aura-perseus-en": "Michael (American, Masculine)",
|
|
30
|
-
"aura-angus-en": "Connor (Irish, Masculine)",
|
|
31
|
-
"aura-orpheus-en": "James (American, Masculine)",
|
|
32
|
-
"aura-helios-en": "William (British, Masculine)",
|
|
33
|
-
"aura-orion-en": "Daniel (American, Masculine)",
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
def __init__(self, timeout: int = 20, proxies: dict = None):
|
|
37
|
-
"""Initializes the SthirTTS client."""
|
|
38
|
-
super().__init__()
|
|
39
|
-
self.api_url = "https://sthir.org/com.api/tts-api.php"
|
|
40
|
-
self.session = requests.Session()
|
|
41
|
-
self.session.headers.update(self.headers)
|
|
42
|
-
if proxies:
|
|
43
|
-
self.session.proxies.update(proxies)
|
|
44
|
-
self.timeout = timeout
|
|
45
|
-
|
|
46
|
-
def tts(self, text: str, voice: str = "aura-luna-en") -> str:
|
|
47
|
-
"""
|
|
48
|
-
Converts text to speech using the Sthir.org API and saves it to a file.
|
|
49
|
-
|
|
50
|
-
Args:
|
|
51
|
-
text (str): The text to convert to speech
|
|
52
|
-
voice (str): The voice to use for TTS (default: "aura-luna-en")
|
|
53
|
-
|
|
54
|
-
Returns:
|
|
55
|
-
str: Path to the generated audio file
|
|
56
|
-
|
|
57
|
-
Raises:
|
|
58
|
-
exceptions.FailedToGenerateResponseError: If there is an error generating or saving the audio.
|
|
59
|
-
"""
|
|
60
|
-
assert (
|
|
61
|
-
voice in self.all_voices
|
|
62
|
-
), f"Voice '{voice}' not one of [{', '.join(self.all_voices.keys())}]"
|
|
63
|
-
|
|
64
|
-
filename = pathlib.Path(tempfile.mktemp(suffix=".mp3", dir=self.temp_dir))
|
|
65
|
-
payload = {"text": text, "voice": voice}
|
|
66
|
-
|
|
67
|
-
try:
|
|
68
|
-
response = self.session.post(
|
|
69
|
-
self.api_url,
|
|
70
|
-
headers=self.headers,
|
|
71
|
-
json=payload,
|
|
72
|
-
timeout=self.timeout
|
|
73
|
-
)
|
|
74
|
-
if response.status_code == 200 and len(response.content) > 0:
|
|
75
|
-
with open(filename, "wb") as f:
|
|
76
|
-
f.write(response.content)
|
|
77
|
-
return filename.as_posix()
|
|
78
|
-
else:
|
|
79
|
-
try:
|
|
80
|
-
error_data = response.json()
|
|
81
|
-
if "error" in error_data:
|
|
82
|
-
raise exceptions.FailedToGenerateResponseError(f"API error: {error_data['error']}")
|
|
83
|
-
except Exception:
|
|
84
|
-
pass
|
|
85
|
-
raise exceptions.FailedToGenerateResponseError(f"Sthir API error: {response.text}")
|
|
86
|
-
except Exception as e:
|
|
87
|
-
raise exceptions.FailedToGenerateResponseError(f"Failed to perform the operation: {e}")
|
|
88
|
-
|
|
89
|
-
# Example usage
|
|
90
|
-
if __name__ == "__main__":
|
|
91
|
-
sthir = SthirTTS()
|
|
92
|
-
text = "This is a test of the Sthir.org text-to-speech API. It supports multiple voices."
|
|
93
|
-
audio_file = sthir.tts(text, voice="aura-luna-en")
|
|
94
|
-
print(f"Audio saved to: {audio_file}")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|