webscout 5.8__py3-none-any.whl → 5.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.

@@ -0,0 +1,265 @@
1
+ import requests
2
+ import json
3
+ import uuid
4
+ import os
5
+ from typing import Any, Dict, Optional, Generator
6
+
7
+ from webscout.AIutel import Optimizers
8
+ from webscout.AIutel import Conversation
9
+ from webscout.AIutel import AwesomePrompts, sanitize_stream
10
+ from webscout.AIbase import Provider, AsyncProvider
11
+ from webscout import exceptions
12
+
13
+ class AmigoChat(Provider):
14
+ """
15
+ A class to interact with the AmigoChat.io API.
16
+ """
17
+
18
+ AVAILABLE_MODELS = [
19
+ "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo", # Llama 3
20
+ "o1-mini", # OpenAI O1 Mini
21
+ "claude-3-sonnet-20240229", # Claude Sonnet
22
+ "gemini-1.5-pro", # Gemini Pro
23
+ "gemini-1-5-flash", # Gemini Flash
24
+ "o1-preview", # OpenAI O1 Preview
25
+ ]
26
+
27
+ def __init__(
28
+ self,
29
+ is_conversation: bool = True,
30
+ max_tokens: int = 600,
31
+ timeout: int = 30,
32
+ intro: str = None,
33
+ filepath: str = None,
34
+ update_file: bool = True,
35
+ proxies: dict = {},
36
+ history_offset: int = 10250,
37
+ act: str = None,
38
+ model: str = "o1-preview", # Default model
39
+ ):
40
+ """
41
+ Initializes the AmigoChat.io API with given parameters.
42
+
43
+ Args:
44
+ is_conversation (bool, optional): Flag for chatting conversationally. Defaults to True.
45
+ max_tokens (int, optional): Maximum number of tokens to be generated upon completion. Defaults to 600.
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
+ model (str, optional): The AI model to use for text generation. Defaults to "o1-preview".
54
+ Options: "llama-three-point-one", "openai-o-one-mini", "claude",
55
+ "gemini-1.5-pro", "gemini-1.5-flash", "openai-o-one".
56
+ """
57
+ if model not in self.AVAILABLE_MODELS:
58
+ raise ValueError(f"Invalid model: {model}. Choose from: {self.AVAILABLE_MODELS}")
59
+
60
+ self.session = requests.Session()
61
+ self.is_conversation = is_conversation
62
+ self.max_tokens_to_sample = max_tokens
63
+ self.api_endpoint = "https://api.amigochat.io/v1/chat/completions"
64
+ self.stream_chunk_size = 64
65
+ self.timeout = timeout
66
+ self.last_response = {}
67
+ self.model = model
68
+ self.headers = {
69
+ "Accept": "*/*",
70
+ "Accept-Encoding": "gzip, deflate, br, zstd",
71
+ "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
72
+ "Authorization": "Bearer ", # empty
73
+ "Content-Type": "application/json",
74
+ "DNT": "1",
75
+ "Origin": "https://amigochat.io",
76
+ "Priority": "u=1, i",
77
+ "Referer": "https://amigochat.io/",
78
+ "Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
79
+ "Sec-CH-UA-Mobile": "?0",
80
+ "Sec-CH-UA-Platform": '"Windows"',
81
+ "Sec-Fetch-Dest": "empty",
82
+ "Sec-Fetch-Mode": "cors",
83
+ "Sec-Fetch-Site": "same-site",
84
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
85
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
86
+ "Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
87
+ "X-Device-Language": "en-US",
88
+ "X-Device-Platform": "web",
89
+ "X-Device-UUID": str(uuid.uuid4()),
90
+ "X-Device-Version": "1.0.22"
91
+ }
92
+
93
+ self.__available_optimizers = (
94
+ method
95
+ for method in dir(Optimizers)
96
+ if callable(getattr(Optimizers, method)) and not method.startswith("__")
97
+ )
98
+ self.session.headers.update(self.headers)
99
+ Conversation.intro = (
100
+ AwesomePrompts().get_act(
101
+ act, raise_not_found=True, default=None, case_insensitive=True
102
+ )
103
+ if act
104
+ else intro or Conversation.intro
105
+ )
106
+ self.conversation = Conversation(
107
+ is_conversation, self.max_tokens_to_sample, filepath, update_file
108
+ )
109
+ self.conversation.history_offset = history_offset
110
+ self.session.proxies = proxies
111
+
112
+ def ask(
113
+ self,
114
+ prompt: str,
115
+ stream: bool = False,
116
+ raw: bool = False,
117
+ optimizer: str = None,
118
+ conversationally: bool = False,
119
+ ) -> Dict[str, Any]:
120
+ """Chat with AI
121
+
122
+ Args:
123
+ prompt (str): Prompt to be send.
124
+ stream (bool, optional): Flag for streaming response. Defaults to False.
125
+ raw (bool, optional): Stream back raw response as received. Defaults to False.
126
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
127
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
128
+ Returns:
129
+ dict : {}
130
+ ```json
131
+ {
132
+ "text" : "How may I assist you today?"
133
+ }
134
+ ```
135
+ """
136
+ conversation_prompt = self.conversation.gen_complete_prompt(prompt)
137
+ if optimizer:
138
+ if optimizer in self.__available_optimizers:
139
+ conversation_prompt = getattr(Optimizers, optimizer)(
140
+ conversation_prompt if conversationally else prompt
141
+ )
142
+ else:
143
+ raise Exception(
144
+ f"Optimizer is not one of {self.__available_optimizers}"
145
+ )
146
+
147
+ # Define the payload
148
+ payload = {
149
+ "messages": [
150
+ {"role": "system", "content": "Mai hu ba khabr"},
151
+ {"role": "user", "content": conversation_prompt}
152
+ ],
153
+ "model": self.model,
154
+ "frequency_penalty": 0,
155
+ "max_tokens": 4000,
156
+ "presence_penalty": 0,
157
+ "stream": stream, # Enable streaming
158
+ "temperature": 0.5,
159
+ "top_p": 0.95
160
+ }
161
+
162
+ def for_stream():
163
+ try:
164
+ # Make the POST request with streaming enabled
165
+ with requests.post(self.api_endpoint, headers=self.headers, json=payload, stream=True) as response:
166
+ # Check if the request was successful
167
+ if response.status_code == 201:
168
+ # Iterate over the streamed response line by line
169
+ for line in response.iter_lines():
170
+ if line:
171
+ # Decode the line from bytes to string
172
+ decoded_line = line.decode('utf-8').strip()
173
+ if decoded_line.startswith("data: "):
174
+ data_str = decoded_line[6:]
175
+ if data_str == "[DONE]":
176
+ break
177
+ try:
178
+ # Load the JSON data
179
+ data_json = json.loads(data_str)
180
+
181
+ # Extract the content from the response
182
+ choices = data_json.get("choices", [])
183
+ if choices:
184
+ delta = choices[0].get("delta", {})
185
+ content = delta.get("content", "")
186
+ if content:
187
+ yield content if raw else dict(text=content)
188
+ except json.JSONDecodeError:
189
+ print(f"Received non-JSON data: {data_str}")
190
+ else:
191
+ print(f"Request failed with status code {response.status_code}")
192
+ print("Response:", response.text)
193
+
194
+ except requests.exceptions.RequestException as e:
195
+ print("An error occurred while making the request:", e)
196
+
197
+ def for_non_stream():
198
+ # Accumulate the streaming response
199
+ full_response = ""
200
+ for chunk in for_stream():
201
+ if not raw: # If not raw, chunk is a dictionary
202
+ full_response += chunk["text"]
203
+
204
+ # Update self.last_response with the full text
205
+ self.last_response.update(dict(text=full_response))
206
+ self.conversation.update_chat_history(
207
+ prompt, self.get_message(self.last_response)
208
+ )
209
+ return self.last_response
210
+
211
+ return for_stream() if stream else for_non_stream()
212
+
213
+ def chat(
214
+ self,
215
+ prompt: str,
216
+ stream: bool = False,
217
+ optimizer: str = None,
218
+ conversationally: bool = False,
219
+ ) -> str:
220
+ """Generate response `str`
221
+ Args:
222
+ prompt (str): Prompt to be send.
223
+ stream (bool, optional): Flag for streaming response. Defaults to False.
224
+ optimizer (str, optional): Prompt optimizer name - `[code, shell_command]`. Defaults to None.
225
+ conversationally (bool, optional): Chat conversationally when using optimizer. Defaults to False.
226
+ Returns:
227
+ str: Response generated
228
+ """
229
+
230
+ def for_stream():
231
+ for response in self.ask(
232
+ prompt, True, optimizer=optimizer, conversationally=conversationally
233
+ ):
234
+ yield self.get_message(response)
235
+
236
+ def for_non_stream():
237
+ return self.get_message(
238
+ self.ask(
239
+ prompt,
240
+ False,
241
+ optimizer=optimizer,
242
+ conversationally=conversationally,
243
+ )
244
+ )
245
+
246
+ return for_stream() if stream else for_non_stream()
247
+
248
+ def get_message(self, response: dict) -> str:
249
+ """Retrieves message only from response
250
+
251
+ Args:
252
+ response (dict): Response generated by `self.ask`
253
+
254
+ Returns:
255
+ str: Message extracted
256
+ """
257
+ assert isinstance(response, dict), "Response should be of dict data-type only"
258
+ return response["text"]
259
+
260
+ if __name__ == '__main__':
261
+ from rich import print
262
+ ai = AmigoChat(model="o1-preview")
263
+ response = ai.chat(input(">>> "))
264
+ for chunk in response:
265
+ print(chunk, end="", flush=True)
@@ -0,0 +1,142 @@
1
+ import requests
2
+ import os
3
+ from typing import List
4
+
5
+ from webscout.AIbase import ImageProvider
6
+
7
+ class WebSimAI(ImageProvider):
8
+ """
9
+ Image provider for WebSim.ai.
10
+ """
11
+
12
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
13
+ """Initializes the WebSimAI class.
14
+
15
+ Args:
16
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
17
+ proxies (dict, optional): HTTP request proxies (socks). Defaults to {}.
18
+ """
19
+ self.url = "https://websim.ai/api/image_gen"
20
+ self.headers = {
21
+ "Accept": "*/*",
22
+ "Accept-Encoding": "gzip, deflate, br, zstd",
23
+ "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
24
+ "Content-Type": "application/json",
25
+ "User-Agent": (
26
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
27
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
28
+ "Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
29
+ ),
30
+ "Origin": "https://websim.ai",
31
+ "Referer": "https://websim.ai/p/a5yvwmtj8qz6ayx4tlg1"
32
+ }
33
+ self.session = requests.Session()
34
+ self.session.headers.update(self.headers)
35
+ self.session.proxies.update(proxies)
36
+ self.timeout = timeout
37
+ self.prompt: str = "AI-generated image - Webscout"
38
+ self.image_extension: str = "png"
39
+
40
+ def generate(
41
+ self,
42
+ prompt: str,
43
+ amount: int = 1,
44
+ width: int = 1024,
45
+ height: int = 756
46
+ ) -> List[bytes]:
47
+ """Generate image from prompt
48
+
49
+ Args:
50
+ prompt (str): Image description.
51
+ amount (int, optional): Total images to be generated. Defaults to 1.
52
+ width (int, optional): Width of the generated image. Defaults to 1024.
53
+ height (int, optional): Height of the generated image. Defaults to 756.
54
+
55
+ Returns:
56
+ List[bytes]: List of generated images as bytes.
57
+ """
58
+ assert bool(prompt), "Prompt cannot be null"
59
+ assert isinstance(amount, int), f"Amount should be an integer only, not {type(amount)}"
60
+ assert amount > 0, "Amount should be greater than 0"
61
+
62
+ self.prompt = prompt
63
+ response = []
64
+
65
+ for _ in range(amount):
66
+ payload = {
67
+ "prompt": prompt,
68
+ "width": width,
69
+ "height": height,
70
+ "site_id": "KcWvHOHNBP2PmWUYZ",
71
+ }
72
+
73
+ try:
74
+ resp = self.session.post(self.url, headers=self.headers, json=payload, timeout=self.timeout)
75
+ resp.raise_for_status() # Raises HTTPError for bad responses
76
+
77
+ response_data = resp.json()
78
+ image_url = response_data.get("url")
79
+ if not image_url:
80
+ print("No image URL found in the response.")
81
+ continue
82
+
83
+ image_response = requests.get(image_url)
84
+ image_response.raise_for_status()
85
+ response.append(image_response.content)
86
+
87
+ except requests.exceptions.HTTPError as http_err:
88
+ print(f"HTTP error occurred: {http_err} - {response.text}")
89
+ return [] # Return an empty list on error
90
+ except requests.exceptions.RequestException as req_err:
91
+ print(f"Request error occurred: {req_err}")
92
+ return [] # Return an empty list on error
93
+
94
+ return response
95
+
96
+ def save(
97
+ self,
98
+ response: List[bytes],
99
+ name: str = None,
100
+ dir: str = os.getcwd(),
101
+ filenames_prefix: str = "",
102
+ ) -> List[str]:
103
+ """Save generated images
104
+
105
+ Args:
106
+ response (List[bytes]): List of generated images as bytes.
107
+ name (str): Filename for the images. Defaults to the last prompt.
108
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
109
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
110
+
111
+ Returns:
112
+ List[str]: List of saved filenames.
113
+ """
114
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
115
+ name = self.prompt if name is None else name
116
+
117
+ filenames = []
118
+ count = 0
119
+ for image in response:
120
+ def complete_path():
121
+ count_value = "" if count == 0 else f"_{count}"
122
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
123
+
124
+ while os.path.isfile(complete_path()):
125
+ count += 1
126
+
127
+ absolute_path_to_file = complete_path()
128
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
129
+
130
+ with open(absolute_path_to_file, "wb") as fh:
131
+ fh.write(image)
132
+
133
+ return filenames
134
+
135
+
136
+ if __name__ == "__main__":
137
+ bot = WebSimAI()
138
+ try:
139
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
140
+ print(bot.save(resp))
141
+ except Exception as e:
142
+ print(f"An error occurred: {e}")
@@ -4,4 +4,6 @@ from .aiforce import *
4
4
  from .blackboximage import *
5
5
  from .Nexra import *
6
6
  from .huggingface import *
7
- from .artbit import *
7
+ from .artbit import *
8
+ from .amigo import *
9
+ from .WebSimAI import *
@@ -0,0 +1,148 @@
1
+ import requests
2
+ import json
3
+ import uuid
4
+ import os
5
+ from typing import List
6
+
7
+ from webscout.AIbase import ImageProvider
8
+
9
+ class AmigoImager(ImageProvider):
10
+ """
11
+ Image provider for AmigoChat.io.
12
+ """
13
+ AVAILABLE_MODELS = ["dalle-e-3", "flux-pro", "flux-realism"]
14
+ def __init__(self, timeout: int = 60, proxies: dict = {}):
15
+ """Initializes the AmigoImager class.
16
+
17
+ Args:
18
+ timeout (int, optional): HTTP request timeout in seconds. Defaults to 60.
19
+ proxies (dict, optional): HTTP request proxies. Defaults to {}.
20
+ """
21
+ self.url = "https://api.amigochat.io/v1/images/generations"
22
+ self.headers = {
23
+ "Accept": "*/*",
24
+ "Accept-Encoding": "gzip, deflate, br, zstd",
25
+ "Accept-Language": "en-US,en;q=0.9,en-IN;q=0.8",
26
+ "Authorization": "Bearer ", # Empty
27
+ "Content-Type": "application/json; charset=utf-8",
28
+ "DNT": "1",
29
+ "Origin": "https://amigochat.io",
30
+ "Referer": "https://amigochat.io/",
31
+ "Sec-CH-UA": '"Microsoft Edge";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
32
+ "Sec-CH-UA-Mobile": "?0",
33
+ "Sec-CH-UA-Platform": '"Windows"',
34
+ "Sec-Fetch-Dest": "empty",
35
+ "Sec-Fetch-Mode": "cors",
36
+ "Sec-Fetch-Site": "same-site",
37
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
38
+ "X-Device-Language": "en-US",
39
+ "X-Device-Platform": "web",
40
+ "X-Device-UUID": str(uuid.uuid4()),
41
+ "X-Device-Version": "1.0.22"
42
+ }
43
+ self.session = requests.Session()
44
+ self.session.headers.update(self.headers)
45
+ self.session.proxies.update(proxies)
46
+ self.timeout = timeout
47
+ self.prompt: str = "AI-generated image - webscout"
48
+ self.image_extension: str = "png"
49
+
50
+ def generate(self, prompt: str, amount: int = 1, model: str = "flux-pro") -> List[str]:
51
+ """Generate image from prompt
52
+
53
+ Args:
54
+ prompt (str): Image description.
55
+ amount (int, optional): Total images to be generated. Defaults to 1.
56
+ model (str, optional): Model to use for generating images. Defaults to "flux-pro".
57
+
58
+ Returns:
59
+ List[str]: List of generated image URLs.
60
+ """
61
+ assert bool(prompt), "Prompt cannot be null"
62
+ assert isinstance(amount, int), f"Amount should be an integer only not {type(amount)}"
63
+ assert amount > 0, "Amount should be greater than 0"
64
+ assert model in self.AVAILABLE_MODELS, f"Model should be one of {self.AVAILABLE_MODELS}"
65
+
66
+ self.prompt = prompt
67
+ response = []
68
+
69
+ for _ in range(amount):
70
+ # JSON payload for the request
71
+ payload = {
72
+ "prompt": prompt,
73
+ "model": model,
74
+ "personaId": "image-generator"
75
+ }
76
+
77
+ try:
78
+ # Sending the POST request
79
+ resp = requests.post(self.url, headers=self.headers, data=json.dumps(payload), timeout=self.timeout)
80
+ resp.raise_for_status()
81
+
82
+ # Process the response
83
+ response_data = resp.json()
84
+ image_url = response_data['data'][0]['url']
85
+ response.append(image_url)
86
+
87
+ except requests.exceptions.RequestException as e:
88
+ print(f"An error occurred: {e}")
89
+ raise
90
+
91
+ return response
92
+
93
+ def save(
94
+ self,
95
+ response: List[str], # List of image URLs
96
+ name: str = None,
97
+ dir: str = os.getcwd(),
98
+ filenames_prefix: str = "",
99
+ ) -> List[str]:
100
+ """Save generated images
101
+
102
+ Args:
103
+ response (List[str]): List of generated image URLs.
104
+ name (str): Filename for the images. Defaults to the last prompt.
105
+ dir (str, optional): Directory for saving images. Defaults to os.getcwd().
106
+ filenames_prefix (str, optional): String to be prefixed at each filename to be returned.
107
+
108
+ Returns:
109
+ List[str]: List of saved filenames.
110
+ """
111
+ assert isinstance(response, list), f"Response should be of {list} not {type(response)}"
112
+ name = self.prompt if name is None else name
113
+
114
+ filenames = []
115
+ count = 0
116
+ for img_url in response:
117
+ def complete_path():
118
+ count_value = "" if count == 0 else f"_{count}"
119
+ return os.path.join(dir, name + count_value + "." + self.image_extension)
120
+
121
+ while os.path.isfile(complete_path()):
122
+ count += 1
123
+
124
+ absolute_path_to_file = complete_path()
125
+ filenames.append(filenames_prefix + os.path.split(absolute_path_to_file)[1])
126
+
127
+ # Download and save the image
128
+ try:
129
+ img_response = requests.get(img_url, stream=True, timeout=self.timeout)
130
+ img_response.raise_for_status()
131
+
132
+ with open(absolute_path_to_file, "wb") as fh:
133
+ for chunk in img_response.iter_content(chunk_size=8192):
134
+ fh.write(chunk)
135
+ except requests.exceptions.RequestException as e:
136
+ print(f"An error occurred while downloading image from {img_url}: {e}")
137
+ raise
138
+
139
+ return filenames
140
+
141
+ # Example usage
142
+ if __name__ == "__main__":
143
+ bot = AmigoImager()
144
+ try:
145
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
146
+ print(bot.save(resp))
147
+ except Exception as e:
148
+ print(f"An error occurred: {e}")
@@ -1,2 +1,3 @@
1
1
  from .streamElements import *
2
- from .voicepod import *
2
+ from .voicepod import *
3
+ from .parler import *
@@ -0,0 +1,108 @@
1
+ import time
2
+ from pathlib import Path
3
+ from typing import Generator
4
+ from playsound import playsound
5
+ from webscout import exceptions
6
+ from webscout.AIbase import TTSProvider
7
+
8
+ from gradio_client import Client
9
+ import os
10
+
11
+
12
+ class ParlerTTS(TTSProvider):
13
+ """
14
+ A class to interact with the Parler TTS API through Gradio Client.
15
+ """
16
+
17
+ def __init__(self, timeout: int = 20, proxies: dict = None):
18
+ """Initializes the Parler TTS client."""
19
+ self.api_endpoint = "/gen_tts"
20
+ self.client = Client("parler-tts/parler_tts") # Initialize the Gradio client
21
+ self.timeout = timeout
22
+ self.audio_cache_dir = Path("./audio_cache")
23
+
24
+ def tts(self, text: str, description: str = "", use_large: bool = False) -> str:
25
+ """
26
+ Converts text to speech using the Parler TTS API.
27
+
28
+ Args:
29
+ text (str): The text to be converted to speech.
30
+ description (str, optional): Description of the desired voice characteristics. Defaults to "".
31
+ use_large (bool, optional): Whether to use the large model variant. Defaults to False.
32
+
33
+ Returns:
34
+ str: The filename of the saved audio file.
35
+
36
+ Raises:
37
+ exceptions.FailedToGenerateResponseError: If there is an error generating or saving the audio.
38
+ """
39
+ filename = self.audio_cache_dir / f"{int(time.time())}.wav"
40
+
41
+ try:
42
+ result = self.client.predict(
43
+ text=text,
44
+ description=description,
45
+ use_large=use_large,
46
+ api_name=self.api_endpoint,
47
+ )
48
+
49
+ if isinstance(result, bytes):
50
+ audio_bytes = result
51
+ elif isinstance(result, str) and os.path.isfile(result):
52
+ with open(result, "rb") as f:
53
+ audio_bytes = f.read()
54
+ else:
55
+ raise ValueError(f"Unexpected response from API: {result}")
56
+
57
+ self._save_audio(audio_bytes, filename)
58
+ return filename.as_posix()
59
+
60
+ except Exception as e:
61
+ raise exceptions.FailedToGenerateResponseError(
62
+ f"Error generating audio after multiple retries: {e}"
63
+ ) from e
64
+
65
+ def _save_audio(self, audio_data: bytes, filename: Path):
66
+ """Saves the audio data to a WAV file in the audio cache directory."""
67
+ try:
68
+ self.audio_cache_dir.mkdir(parents=True, exist_ok=True)
69
+ with open(filename, "wb") as f:
70
+ f.write(audio_data)
71
+
72
+ except Exception as e:
73
+ raise exceptions.FailedToGenerateResponseError(f"Error saving audio: {e}")
74
+
75
+ def play_audio(self, filename: str):
76
+ """
77
+ Plays an audio file using playsound.
78
+
79
+ Args:
80
+ filename (str): The path to the audio file.
81
+
82
+ Raises:
83
+ RuntimeError: If there is an error playing the audio.
84
+ """
85
+ try:
86
+ playsound(filename)
87
+ except Exception as e:
88
+ raise RuntimeError(f"Error playing audio: {e}")
89
+
90
+
91
+ # Example usage
92
+ if __name__ == "__main__":
93
+ parlertts = ParlerTTS()
94
+ text = (
95
+ "All of the data, pre-processing, training code, and weights are released "
96
+ "publicly under a permissive license, enabling the community to build on our work "
97
+ "and develop their own powerful models."
98
+ )
99
+ voice_description = (
100
+ "Laura's voice is monotone yet slightly fast in delivery, with a very close "
101
+ "recording that almost has no background noise."
102
+ )
103
+
104
+ print("Generating audio...")
105
+ audio_file = parlertts.tts(text, description=voice_description, use_large=False)
106
+
107
+ print("Playing audio...")
108
+ parlertts.play_audio(audio_file)