webscout 6.3__py3-none-any.whl → 6.5__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 (131) hide show
  1. webscout/AIauto.py +191 -176
  2. webscout/AIbase.py +0 -197
  3. webscout/AIutel.py +441 -1130
  4. webscout/DWEBS.py +189 -35
  5. webscout/{YTdownloader.py → Extra/YTToolkit/YTdownloader.py} +990 -1103
  6. webscout/Extra/YTToolkit/__init__.py +3 -0
  7. webscout/{transcriber.py → Extra/YTToolkit/transcriber.py} +479 -551
  8. webscout/Extra/YTToolkit/ytapi/__init__.py +6 -0
  9. webscout/Extra/YTToolkit/ytapi/channel.py +307 -0
  10. webscout/Extra/YTToolkit/ytapi/errors.py +13 -0
  11. webscout/Extra/YTToolkit/ytapi/extras.py +45 -0
  12. webscout/Extra/YTToolkit/ytapi/https.py +88 -0
  13. webscout/Extra/YTToolkit/ytapi/patterns.py +61 -0
  14. webscout/Extra/YTToolkit/ytapi/playlist.py +59 -0
  15. webscout/Extra/YTToolkit/ytapi/pool.py +8 -0
  16. webscout/Extra/YTToolkit/ytapi/query.py +37 -0
  17. webscout/Extra/YTToolkit/ytapi/stream.py +60 -0
  18. webscout/Extra/YTToolkit/ytapi/utils.py +62 -0
  19. webscout/Extra/YTToolkit/ytapi/video.py +102 -0
  20. webscout/Extra/__init__.py +3 -1
  21. webscout/Extra/autocoder/__init__.py +9 -0
  22. webscout/Extra/autocoder/autocoder_utiles.py +121 -0
  23. webscout/Extra/autocoder/rawdog.py +680 -0
  24. webscout/Extra/autollama.py +246 -195
  25. webscout/Extra/gguf.py +81 -56
  26. webscout/Extra/markdownlite/__init__.py +862 -0
  27. webscout/Extra/weather_ascii.py +2 -2
  28. webscout/LLM.py +206 -43
  29. webscout/Litlogger/__init__.py +681 -0
  30. webscout/Provider/DARKAI.py +1 -1
  31. webscout/Provider/EDITEE.py +1 -1
  32. webscout/Provider/NinjaChat.py +1 -1
  33. webscout/Provider/PI.py +120 -35
  34. webscout/Provider/Perplexity.py +590 -598
  35. webscout/Provider/Reka.py +0 -1
  36. webscout/Provider/RoboCoders.py +206 -0
  37. webscout/Provider/TTI/AiForce/__init__.py +22 -0
  38. webscout/Provider/TTI/AiForce/async_aiforce.py +257 -0
  39. webscout/Provider/TTI/AiForce/sync_aiforce.py +242 -0
  40. webscout/Provider/TTI/Nexra/__init__.py +22 -0
  41. webscout/Provider/TTI/Nexra/async_nexra.py +286 -0
  42. webscout/Provider/TTI/Nexra/sync_nexra.py +258 -0
  43. webscout/Provider/TTI/PollinationsAI/__init__.py +23 -0
  44. webscout/Provider/TTI/PollinationsAI/async_pollinations.py +330 -0
  45. webscout/Provider/TTI/PollinationsAI/sync_pollinations.py +285 -0
  46. webscout/Provider/TTI/__init__.py +2 -4
  47. webscout/Provider/TTI/artbit/__init__.py +22 -0
  48. webscout/Provider/TTI/artbit/async_artbit.py +184 -0
  49. webscout/Provider/TTI/artbit/sync_artbit.py +176 -0
  50. webscout/Provider/TTI/blackbox/__init__.py +4 -0
  51. webscout/Provider/TTI/blackbox/async_blackbox.py +212 -0
  52. webscout/Provider/TTI/{blackboximage.py → blackbox/sync_blackbox.py} +199 -153
  53. webscout/Provider/TTI/deepinfra/__init__.py +4 -0
  54. webscout/Provider/TTI/deepinfra/async_deepinfra.py +227 -0
  55. webscout/Provider/TTI/deepinfra/sync_deepinfra.py +199 -0
  56. webscout/Provider/TTI/huggingface/__init__.py +22 -0
  57. webscout/Provider/TTI/huggingface/async_huggingface.py +199 -0
  58. webscout/Provider/TTI/huggingface/sync_huggingface.py +195 -0
  59. webscout/Provider/TTI/imgninza/__init__.py +4 -0
  60. webscout/Provider/TTI/imgninza/async_ninza.py +214 -0
  61. webscout/Provider/TTI/{imgninza.py → imgninza/sync_ninza.py} +209 -136
  62. webscout/Provider/TTI/talkai/__init__.py +4 -0
  63. webscout/Provider/TTI/talkai/async_talkai.py +229 -0
  64. webscout/Provider/TTI/talkai/sync_talkai.py +207 -0
  65. webscout/Provider/TTS/__init__.py +5 -1
  66. webscout/Provider/TTS/deepgram.py +183 -0
  67. webscout/Provider/TTS/elevenlabs.py +137 -0
  68. webscout/Provider/TTS/gesserit.py +151 -0
  69. webscout/Provider/TTS/murfai.py +139 -0
  70. webscout/Provider/TTS/parler.py +134 -107
  71. webscout/Provider/TTS/streamElements.py +360 -275
  72. webscout/Provider/TTS/utils.py +280 -0
  73. webscout/Provider/TTS/voicepod.py +116 -116
  74. webscout/Provider/__init__.py +8 -1
  75. webscout/Provider/askmyai.py +2 -2
  76. webscout/Provider/cerebras.py +227 -219
  77. webscout/Provider/llama3mitril.py +0 -1
  78. webscout/Provider/meta.py +794 -779
  79. webscout/Provider/mhystical.py +176 -0
  80. webscout/Provider/perplexitylabs.py +265 -0
  81. webscout/Provider/twitterclone.py +251 -245
  82. webscout/Provider/typegpt.py +358 -0
  83. webscout/__init__.py +9 -8
  84. webscout/__main__.py +5 -5
  85. webscout/cli.py +252 -280
  86. webscout/conversation.py +227 -0
  87. webscout/exceptions.py +161 -29
  88. webscout/litagent/__init__.py +172 -0
  89. webscout/litprinter/__init__.py +832 -0
  90. webscout/optimizers.py +270 -0
  91. webscout/prompt_manager.py +279 -0
  92. webscout/scout/__init__.py +11 -0
  93. webscout/scout/core.py +884 -0
  94. webscout/scout/element.py +459 -0
  95. webscout/scout/parsers/__init__.py +69 -0
  96. webscout/scout/parsers/html5lib_parser.py +172 -0
  97. webscout/scout/parsers/html_parser.py +236 -0
  98. webscout/scout/parsers/lxml_parser.py +178 -0
  99. webscout/scout/utils.py +38 -0
  100. webscout/swiftcli/__init__.py +810 -0
  101. webscout/update_checker.py +125 -0
  102. webscout/version.py +1 -1
  103. webscout/zeroart/__init__.py +55 -0
  104. webscout/zeroart/base.py +61 -0
  105. webscout/zeroart/effects.py +99 -0
  106. webscout/zeroart/fonts.py +816 -0
  107. webscout/zerodir/__init__.py +225 -0
  108. {webscout-6.3.dist-info → webscout-6.5.dist-info}/METADATA +37 -112
  109. webscout-6.5.dist-info/RECORD +179 -0
  110. webscout/Agents/Onlinesearcher.py +0 -182
  111. webscout/Agents/__init__.py +0 -2
  112. webscout/Agents/functioncall.py +0 -248
  113. webscout/Bing_search.py +0 -154
  114. webscout/Provider/TTI/AIuncensoredimage.py +0 -103
  115. webscout/Provider/TTI/Nexra.py +0 -120
  116. webscout/Provider/TTI/PollinationsAI.py +0 -138
  117. webscout/Provider/TTI/WebSimAI.py +0 -142
  118. webscout/Provider/TTI/aiforce.py +0 -160
  119. webscout/Provider/TTI/artbit.py +0 -141
  120. webscout/Provider/TTI/deepinfra.py +0 -148
  121. webscout/Provider/TTI/huggingface.py +0 -155
  122. webscout/Provider/TTI/talkai.py +0 -116
  123. webscout/g4f.py +0 -666
  124. webscout/models.py +0 -23
  125. webscout/requestsHTMLfix.py +0 -775
  126. webscout/webai.py +0 -2590
  127. webscout-6.3.dist-info/RECORD +0 -124
  128. {webscout-6.3.dist-info → webscout-6.5.dist-info}/LICENSE.md +0 -0
  129. {webscout-6.3.dist-info → webscout-6.5.dist-info}/WHEEL +0 -0
  130. {webscout-6.3.dist-info → webscout-6.5.dist-info}/entry_points.txt +0 -0
  131. {webscout-6.3.dist-info → webscout-6.5.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,207 @@
1
+ import uuid
2
+ import requests
3
+ import json
4
+ import os
5
+ from typing import Any, Dict, List, Optional
6
+
7
+ from webscout.AIbase import ImageProvider
8
+ from webscout import exceptions
9
+ from webscout.litagent import agent # Import our fire user agent generator 🔥
10
+ from webscout.Litlogger import LitLogger # For that cyberpunk logging swag ⚡
11
+
12
+ # Initialize our fire logger 🚀
13
+ logger = LitLogger("TalkaiImager")
14
+
15
+ class TalkaiImager(ImageProvider):
16
+ """
17
+ TalkAI Image Provider - Your go-to for fire AI art! 🎨
18
+
19
+ >>> # Generate some fire art! 🔥
20
+ >>> imager = TalkaiImager(logging=True)
21
+ >>> images = imager.generate("Epic dragon breathing fire", amount=2)
22
+ >>> paths = imager.save(images)
23
+ >>> print(paths)
24
+ ['epic_dragon_0.png', 'epic_dragon_1.png']
25
+
26
+ >>> # Turn off logging for stealth mode 🥷
27
+ >>> quiet_imager = TalkaiImager(logging=False)
28
+ >>> images = quiet_imager.generate("Cyberpunk city at night")
29
+ >>> paths = quiet_imager.save(images)
30
+ """
31
+
32
+ def __init__(self, timeout: int = 60, proxies: dict = {}, logging: bool = True):
33
+ """Initialize your TalkAI provider with custom settings! ⚙️
34
+
35
+ Args:
36
+ timeout (int): Request timeout in seconds (default: 60)
37
+ proxies (dict): Proxy settings for requests (default: {})
38
+ logging (bool): Enable fire logging (default: True)
39
+ """
40
+ self.api_endpoint = "https://talkai.info/chat/send/"
41
+ self.headers = {
42
+ 'accept': 'application/json',
43
+ 'accept-language': 'en-US,en;q=0.9',
44
+ 'content-type': 'application/json',
45
+ 'origin': 'https://talkai.info',
46
+ 'referer': 'https://talkai.info/image/',
47
+ 'user-agent': agent.random(), # Using our fire random agent! 🔥
48
+ }
49
+ self.session = requests.Session()
50
+ self.session.headers.update(self.headers)
51
+ self.session.proxies.update(proxies)
52
+ self.timeout = timeout
53
+ self.prompt: str = "AI-generated image - webscout"
54
+ self.image_extension: str = "png"
55
+ self.logging = logging
56
+ if self.logging:
57
+ logger.info("TalkaiImager initialized! Ready to create some fire art! 🚀")
58
+
59
+ def generate(
60
+ self, prompt: str, amount: int = 1,
61
+ max_retries: int = 3, retry_delay: int = 5
62
+ ) -> List[str]:
63
+ """Generate some fire images from your prompt! 🎨
64
+
65
+ Args:
66
+ prompt (str): Your creative prompt
67
+ amount (int): How many images to generate
68
+ max_retries (int): Max retry attempts if generation fails
69
+ retry_delay (int): Seconds to wait between retries
70
+
71
+ Returns:
72
+ List[str]: List of image URLs
73
+ """
74
+ assert bool(prompt), "Prompt cannot be empty."
75
+ assert isinstance(amount, int) and amount > 0, "Amount must be a positive integer."
76
+
77
+ self.prompt = prompt
78
+ image_urls = []
79
+
80
+ if self.logging:
81
+ logger.info(f"Generating {amount} images... 🎨")
82
+
83
+ for _ in range(amount):
84
+ for attempt in range(max_retries):
85
+ try:
86
+ with self.session.post(
87
+ self.api_endpoint,
88
+ json=self._create_payload(prompt),
89
+ timeout=self.timeout
90
+ ) as response:
91
+ response.raise_for_status()
92
+ data = response.json()
93
+
94
+ if 'data' in data and len(data['data']) > 0 and 'url' in data['data'][0]:
95
+ image_urls.append(data['data'][0]['url'])
96
+ if self.logging:
97
+ logger.success(f"Generated image {len(image_urls)}/{amount}! 🎨")
98
+ break
99
+ else:
100
+ raise exceptions.InvalidResponseError("No image URL found in API response.")
101
+
102
+ except requests.exceptions.RequestException as e:
103
+ if attempt == max_retries - 1:
104
+ if self.logging:
105
+ logger.error(f"Error making API request: {e} 😢")
106
+ raise exceptions.APIConnectionError(f"Error making API request: {e}") from e
107
+ else:
108
+ if self.logging:
109
+ logger.warning(f"Attempt {attempt + 1} failed. Retrying in {retry_delay} seconds... 🔄")
110
+ import time
111
+ time.sleep(retry_delay)
112
+ except json.JSONDecodeError as e:
113
+ if self.logging:
114
+ logger.error(f"Invalid JSON response: {e} 😢")
115
+ raise exceptions.InvalidResponseError(f"Invalid JSON response: {e}") from e
116
+ except Exception as e:
117
+ if self.logging:
118
+ logger.error(f"An unexpected error occurred: {e} 😢")
119
+ raise exceptions.FailedToGenerateResponseError(f"An unexpected error occurred: {e}") from e
120
+
121
+ if self.logging:
122
+ logger.success("All images generated successfully! 🎉")
123
+ return image_urls
124
+
125
+ def _create_payload(self, prompt: str) -> Dict[str, Any]:
126
+ """Create the API request payload 📦
127
+
128
+ Args:
129
+ prompt (str): The image generation prompt
130
+
131
+ Returns:
132
+ Dict[str, Any]: API request payload
133
+ """
134
+ return {
135
+ "type": "image",
136
+ "messagesHistory": [
137
+ {
138
+ "id": str(uuid.uuid4()),
139
+ "from": "you",
140
+ "content": prompt
141
+ }
142
+ ],
143
+ "settings": {
144
+ "model": "gpt-4o-mini" # Or another suitable model if available
145
+ }
146
+ }
147
+
148
+ def save(
149
+ self,
150
+ response: List[str],
151
+ name: str = None,
152
+ dir: str = os.getcwd(),
153
+ filenames_prefix: str = "",
154
+ ) -> List[str]:
155
+ """Save your fire images! 💾
156
+
157
+ Args:
158
+ response (List[str]): List of image URLs
159
+ name (str, optional): Base name for saved files
160
+ dir (str, optional): Where to save the images
161
+ filenames_prefix (str, optional): Prefix for filenames
162
+
163
+ Returns:
164
+ List[str]: List of saved filenames
165
+ """
166
+ assert isinstance(response, list), f"Response should be a list, not {type(response)}"
167
+ name = self.prompt if name is None else name
168
+
169
+ if not os.path.exists(dir):
170
+ os.makedirs(dir)
171
+ if self.logging:
172
+ logger.info(f"Created directory: {dir} 📁")
173
+
174
+ if self.logging:
175
+ logger.info(f"Saving {len(response)} images... 💾")
176
+
177
+ filenames = []
178
+ for i, url in enumerate(response):
179
+ try:
180
+ with self.session.get(url, stream=True, timeout=self.timeout) as r:
181
+ r.raise_for_status()
182
+ filename = f"{filenames_prefix}{name}_{i}.{self.image_extension}"
183
+ filepath = os.path.join(dir, filename)
184
+ with open(filepath, 'wb') as f:
185
+ for chunk in r.iter_content(chunk_size=8192):
186
+ f.write(chunk)
187
+ filenames.append(filename)
188
+ if self.logging:
189
+ logger.success(f"Saved image to: {filepath} 💾")
190
+ except requests.exceptions.RequestException as e:
191
+ if self.logging:
192
+ logger.error(f"Error downloading image from {url}: {e} 😢")
193
+ filenames.append(None) # Indicate failure to download
194
+
195
+ if self.logging:
196
+ logger.success(f"All images saved successfully! Check {dir} 🎉")
197
+ return filenames
198
+
199
+
200
+ if __name__ == "__main__":
201
+ bot = TalkaiImager()
202
+ try:
203
+ resp = bot.generate("A shiny red sports car speeding down a scenic mountain road", 1)
204
+ print(bot.save(resp))
205
+ except Exception as e:
206
+ if bot.logging:
207
+ logger.error(f"An error occurred: {e} 😢")
@@ -1,3 +1,7 @@
1
1
  from .streamElements import *
2
2
  from .voicepod import *
3
- from .parler import *
3
+ from .parler import *
4
+ from .deepgram import *
5
+ from .elevenlabs import *
6
+ from .murfai import *
7
+ from .gesserit import *
@@ -0,0 +1,183 @@
1
+ import time
2
+ import requests
3
+ import pathlib
4
+ import base64
5
+ from io import BytesIO
6
+ from playsound import playsound
7
+ from webscout import exceptions
8
+ from webscout.AIbase import TTSProvider
9
+ from concurrent.futures import ThreadPoolExecutor, as_completed
10
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
11
+ from webscout.litagent import LitAgent
12
+ from . import utils
13
+
14
+ class DeepgramTTS(TTSProvider):
15
+ """
16
+ Text-to-speech provider using the DeepgramTTS API.
17
+ """
18
+ # Request headers
19
+ headers: dict[str, str] = {
20
+ "User-Agent": LitAgent().random()
21
+ }
22
+ cache_dir = pathlib.Path("./audio_cache")
23
+ all_voices: dict[str, str] = {
24
+ "Asteria": "aura-asteria-en", "Arcas": "aura-arcas-en", "Luna": "aura-luna-en",
25
+ "Zeus": "aura-zeus-en", "Orpheus": "aura-orpheus-en", "Angus": "aura-angus-en",
26
+ "Athena": "aura-athena-en", "Helios": "aura-helios-en", "Hera": "aura-hera-en",
27
+ "Orion": "aura-orion-en", "Perseus": "aura-perseus-en", "Stella": "aura-stella-en"
28
+ }
29
+
30
+ def __init__(self, timeout: int = 20, proxies: dict = None):
31
+ """Initializes the DeepgramTTS TTS client."""
32
+ self.session = requests.Session()
33
+ self.session.headers.update(self.headers)
34
+ if proxies:
35
+ self.session.proxies.update(proxies)
36
+ self.timeout = timeout
37
+ self.logger = LitLogger(
38
+ name="DeepgramTTS",
39
+ format=LogFormat.MODERN_EMOJI,
40
+ color_scheme=ColorScheme.AURORA
41
+ )
42
+
43
+ def tts(self, text: str, voice: str = "Brian", verbose: bool = True) -> str:
44
+ """
45
+ Converts text to speech using the DeepgramTTS API and saves it to a file.
46
+
47
+ Args:
48
+ text (str): The text to convert to speech
49
+ voice (str): The voice to use for TTS (default: "Brian")
50
+ verbose (bool): Whether to print progress messages (default: True)
51
+
52
+ Returns:
53
+ str: Path to the generated audio file
54
+
55
+ Raises:
56
+ AssertionError: If the specified voice is not available
57
+ requests.RequestException: If there's an error communicating with the API
58
+ RuntimeError: If there's an error processing 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
+ url = "https://deepgram.com/api/ttsAudioGeneration"
65
+ filename = self.cache_dir / f"{int(time.time())}.mp3"
66
+
67
+ # Split text into sentences using the utils module
68
+ sentences = utils.split_sentences(text)
69
+ if verbose:
70
+ for index, sen in enumerate(sentences):
71
+ self.logger.debug(f"Sentence {index}: {sen}")
72
+
73
+ def generate_audio_for_chunk(part_text: str, part_number: int):
74
+ """
75
+ Generate audio for a single chunk of text.
76
+
77
+ Args:
78
+ part_text (str): The text chunk to convert
79
+ part_number (int): The chunk number for ordering
80
+
81
+ Returns:
82
+ tuple: (part_number, audio_data)
83
+
84
+ Raises:
85
+ requests.RequestException: If there's an API error
86
+ """
87
+ max_retries = 3
88
+ retry_count = 0
89
+
90
+ while retry_count < max_retries:
91
+ try:
92
+ payload = {"text": part_text, "model": self.all_voices[voice]}
93
+ response = self.session.post(
94
+ url=url,
95
+ headers=self.headers,
96
+ json=payload,
97
+ stream=True,
98
+ timeout=self.timeout
99
+ )
100
+ response.raise_for_status()
101
+
102
+ response_data = response.json().get('data')
103
+ if response_data:
104
+ audio_data = base64.b64decode(response_data)
105
+ if verbose:
106
+ self.logger.success(f"Chunk {part_number} processed successfully 🎉")
107
+ return part_number, audio_data
108
+
109
+ if verbose:
110
+ self.logger.warning(f"No data received for chunk {part_number}. Attempt {retry_count + 1}/{max_retries} ⚠️")
111
+
112
+ except requests.RequestException as e:
113
+ if verbose:
114
+ self.logger.error(f"Error processing chunk {part_number}: {str(e)}. Attempt {retry_count + 1}/{max_retries} 🚨")
115
+ if retry_count == max_retries - 1:
116
+ raise
117
+
118
+ retry_count += 1
119
+ time.sleep(1)
120
+
121
+ raise RuntimeError(f"Failed to generate audio for chunk {part_number} after {max_retries} attempts")
122
+
123
+ try:
124
+ # Create the audio_cache directory if it doesn't exist
125
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
126
+
127
+ # Using ThreadPoolExecutor to handle requests concurrently
128
+ with ThreadPoolExecutor() as executor:
129
+ futures = {
130
+ executor.submit(generate_audio_for_chunk, sentence.strip(), chunk_num): chunk_num
131
+ for chunk_num, sentence in enumerate(sentences, start=1)
132
+ }
133
+
134
+ # Dictionary to store results with order preserved
135
+ audio_chunks = {}
136
+
137
+ for future in as_completed(futures):
138
+ chunk_num = futures[future]
139
+ try:
140
+ part_number, audio_data = future.result()
141
+ audio_chunks[part_number] = audio_data
142
+ except Exception as e:
143
+ raise RuntimeError(f"Failed to generate audio for chunk {chunk_num}: {str(e)}")
144
+
145
+ # Combine all audio chunks in order
146
+ with open(filename, 'wb') as f:
147
+ for chunk_num in sorted(audio_chunks.keys()):
148
+ f.write(audio_chunks[chunk_num])
149
+
150
+ if verbose:
151
+ self.logger.success(f"Audio saved to {filename} 🎉")
152
+ return str(filename)
153
+
154
+ except Exception as e:
155
+ self.logger.critical(f"Failed to generate audio: {str(e)} 🚨")
156
+ raise RuntimeError(f"Failed to generate audio: {str(e)}")
157
+
158
+ def play_audio(self, filename: str):
159
+ """
160
+ Plays an audio file using playsound.
161
+
162
+ Args:
163
+ filename (str): The path to the audio file.
164
+
165
+ Raises:
166
+ RuntimeError: If there is an error playing the audio.
167
+ """
168
+ try:
169
+ playsound(filename)
170
+ except Exception as e:
171
+ self.logger.error(f"Failed to play audio: {str(e)} 🚨")
172
+ raise RuntimeError(f"Failed to play audio: {str(e)}")
173
+
174
+ # Example usage
175
+ if __name__ == "__main__":
176
+ deepgram = DeepgramTTS()
177
+ text = "This is a test of the DeepgramTTS text-to-speech API. It supports multiple sentences. Let's see how it works!"
178
+
179
+ deepgram.logger.info("Generating audio...")
180
+ audio_file = deepgram.tts(text, voice="Brian")
181
+
182
+ deepgram.logger.info("Playing audio...")
183
+ deepgram.play_audio(audio_file)
@@ -0,0 +1,137 @@
1
+ import time
2
+ import requests
3
+ import pathlib
4
+ from io import BytesIO
5
+ from playsound import playsound
6
+ from webscout import exceptions
7
+ from webscout.AIbase import TTSProvider
8
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
9
+ from webscout.litagent import LitAgent
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ from . import utils
12
+
13
+ class ElevenlabsTTS(TTSProvider):
14
+ """
15
+ Text-to-speech provider using the ElevenlabsTTS API.
16
+ """
17
+ # Request headers
18
+ headers: dict[str, str] = {
19
+ "User-Agent": LitAgent().random()
20
+ }
21
+ cache_dir = pathlib.Path("./audio_cache")
22
+ all_voices: dict[str, str] = {"Brian": "nPczCjzI2devNBz1zQrb", "Alice":"Xb7hH8MSUJpSbSDYk0k2", "Bill":"pqHfZKP75CvOlQylNhV4", "Callum":"N2lVS1w4EtoT3dr4eOWO", "Charlie":"IKne3meq5aSn9XLyUdCD", "Charlotte":"XB0fDUnXU5powFXDhCwa", "Chris":"iP95p4xoKVk53GoZ742B", "Daniel":"onwK4e9ZLuTAKqWW03F9", "Eric":"cjVigY5qzO86Huf0OWal", "George":"JBFqnCBsd6RMkjVDRZzb", "Jessica":"cgSgspJ2msm6clMCkdW9", "Laura":"FGY2WhTYpPnrIDTdsKH5", "Liam":"TX3LPaxmHKxFdv7VOQHJ", "Lily":"pFZP5JQG7iQjIQuC4Bku", "Matilda":"XrExE9yKIg1WjnnlVkGX", "Sarah":"EXAVITQu4vr4xnSDxMaL", "Will":"bIHbv24MWmeRgasZH58o"}
23
+
24
+ def __init__(self, timeout: int = 20, proxies: dict = None):
25
+ """Initializes the ElevenlabsTTS TTS client."""
26
+ self.session = requests.Session()
27
+ self.session.headers.update(self.headers)
28
+ if proxies:
29
+ self.session.proxies.update(proxies)
30
+ self.timeout = timeout
31
+ self.params = {'allow_unauthenticated': '1'}
32
+ self.logger = LitLogger(
33
+ name="ElevenlabsTTS",
34
+ format=LogFormat.MODERN_EMOJI,
35
+ color_scheme=ColorScheme.AURORA
36
+ )
37
+
38
+ def tts(self, text: str, voice: str = "Brian", verbose:bool = True) -> str:
39
+ """
40
+ Converts text to speech using the ElevenlabsTTS API and saves it to a file.
41
+ """
42
+ assert (
43
+ voice in self.all_voices
44
+ ), f"Voice '{voice}' not one of [{', '.join(self.all_voices.keys())}]"
45
+
46
+ filename = self.cache_dir / f"{int(time.time())}.mp3"
47
+
48
+ # Split text into sentences
49
+ sentences = utils.split_sentences(text)
50
+
51
+ # Function to request audio for each chunk
52
+ def generate_audio_for_chunk(part_text: str, part_number: int):
53
+ while True:
54
+ try:
55
+ json_data = {'text': part_text, 'model_id': 'eleven_multilingual_v2'}
56
+ response = self.session.post(f'https://api.elevenlabs.io/v1/text-to-speech/{self.all_voices[voice]}',params=self.params, headers=self.headers, json=json_data, timeout=self.timeout)
57
+ response.raise_for_status()
58
+
59
+ # Create the audio_cache directory if it doesn't exist
60
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
61
+
62
+ # Check if the request was successful
63
+ if response.ok and response.status_code == 200:
64
+ if verbose:
65
+ self.logger.success(f"Chunk {part_number} processed successfully 🎉")
66
+ return part_number, response.content
67
+ else:
68
+ if verbose:
69
+ self.logger.warning(f"No data received for chunk {part_number}. Retrying...")
70
+ except requests.RequestException as e:
71
+ if verbose:
72
+ self.logger.error(f"Error for chunk {part_number}: {e}. Retrying... 🔄")
73
+ time.sleep(1)
74
+ try:
75
+ # Using ThreadPoolExecutor to handle requests concurrently
76
+ with ThreadPoolExecutor() as executor:
77
+ futures = {executor.submit(generate_audio_for_chunk, sentence.strip(), chunk_num): chunk_num
78
+ for chunk_num, sentence in enumerate(sentences, start=1)}
79
+
80
+ # Dictionary to store results with order preserved
81
+ audio_chunks = {}
82
+
83
+ for future in as_completed(futures):
84
+ chunk_num = futures[future]
85
+ try:
86
+ part_number, audio_data = future.result()
87
+ audio_chunks[part_number] = audio_data # Store the audio data in correct sequence
88
+ except Exception as e:
89
+ if verbose:
90
+ self.logger.error(f"Failed to generate audio for chunk {chunk_num}: {e} 🚨")
91
+
92
+ # Combine audio chunks in the correct sequence
93
+ combined_audio = BytesIO()
94
+ for part_number in sorted(audio_chunks.keys()):
95
+ combined_audio.write(audio_chunks[part_number])
96
+ if verbose:
97
+ self.logger.debug(f"Added chunk {part_number} to the combined file.")
98
+
99
+ # Save the combined audio data to a single file
100
+ with open(filename, 'wb') as f:
101
+ f.write(combined_audio.getvalue())
102
+ if verbose:
103
+ self.logger.info(f"Final Audio Saved as {filename} 🔊")
104
+ return filename.as_posix()
105
+
106
+ except requests.exceptions.RequestException as e:
107
+ self.logger.critical(f"Failed to perform the operation: {e} 🚨")
108
+ raise exceptions.FailedToGenerateResponseError(
109
+ f"Failed to perform the operation: {e}"
110
+ )
111
+
112
+ def play_audio(self, filename: str):
113
+ """
114
+ Plays an audio file using playsound.
115
+
116
+ Args:
117
+ filename (str): The path to the audio file.
118
+
119
+ Raises:
120
+ RuntimeError: If there is an error playing the audio.
121
+ """
122
+ try:
123
+ playsound(filename)
124
+ except Exception as e:
125
+ self.logger.error(f"Error playing audio: {e} 🔇")
126
+ raise RuntimeError(f"Error playing audio: {e}")
127
+
128
+ # Example usage
129
+ if __name__ == "__main__":
130
+ elevenlabs = ElevenlabsTTS()
131
+ text = "This is a test of the ElevenlabsTTS text-to-speech API. It supports multiple sentences and advanced logging."
132
+
133
+ elevenlabs.logger.info("Generating audio...")
134
+ audio_file = elevenlabs.tts(text, voice="Brian")
135
+
136
+ elevenlabs.logger.info("Playing audio...")
137
+ elevenlabs.play_audio(audio_file)
@@ -0,0 +1,151 @@
1
+ import time
2
+ import requests
3
+ import pathlib
4
+ import base64
5
+ from io import BytesIO
6
+ from playsound import playsound
7
+ from webscout import exceptions
8
+ from webscout.AIbase import TTSProvider
9
+ from webscout.Litlogger import LitLogger, LogFormat, ColorScheme
10
+ from webscout.litagent import LitAgent
11
+ from concurrent.futures import ThreadPoolExecutor, as_completed
12
+ from . import utils
13
+
14
+ class GesseritTTS(TTSProvider):
15
+ """Text-to-speech provider using the GesseritTTS API."""
16
+ # Request headers
17
+ headers: dict[str, str] = {
18
+ "User-Agent": LitAgent().random()
19
+ }
20
+ cache_dir = pathlib.Path("./audio_cache")
21
+ all_voices: dict[str, str] = {
22
+ "Emma": "en_us_001", # Female Voice
23
+ "Liam": "en_us_006", # Male Voice
24
+ "Noah": "en_us_007", # Male Voice
25
+ "Oliver": "en_us_009", # Male Voice
26
+ "Elijah": "en_us_010", # Male Voice
27
+ "James": "en_male_narration", # Male Voice
28
+ "Charlie": "en_male_funny", # Male Voice
29
+ "Sophia": "en_female_emotional", # Female Voice
30
+ "Cody": "en_male_cody", # Male Voice
31
+ }
32
+
33
+ def __init__(self, timeout: int = 20, proxies: dict = None):
34
+ """Initializes the GesseritTTS TTS client."""
35
+ self.session = requests.Session()
36
+ self.session.headers.update(self.headers)
37
+ if proxies:
38
+ self.session.proxies.update(proxies)
39
+ self.timeout = timeout
40
+ self.logger = LitLogger(
41
+ name="GesseritTTS",
42
+ format=LogFormat.MODERN_EMOJI,
43
+ color_scheme=ColorScheme.AURORA
44
+ )
45
+
46
+ def tts(self, text: str, voice: str = "Oliver", verbose:bool = True) -> str:
47
+ """Converts text to speech using the GesseritTTS API and saves it to a file."""
48
+ assert (
49
+ voice in self.all_voices
50
+ ), f"Voice '{voice}' not one of [{', '.join(self.all_voices.keys())}]"
51
+
52
+ filename = self.cache_dir / f"{int(time.time())}.mp3"
53
+
54
+ voice_id = self.all_voices[voice]
55
+
56
+ # Split text into sentences
57
+ sentences = utils.split_sentences(text)
58
+
59
+ # Function to request audio for each chunk
60
+ def generate_audio_for_chunk(part_text: str, part_number: int):
61
+ while True:
62
+ try:
63
+ payload = {
64
+ "text": part_text,
65
+ "voice": voice_id
66
+ }
67
+ response = self.session.post('https://gesserit.co/api/tiktok-tts', headers=self.headers, json=payload, timeout=self.timeout)
68
+ response.raise_for_status()
69
+
70
+ # Create the audio_cache directory if it doesn't exist
71
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
72
+
73
+ # Check if the request was successful
74
+ if response.ok and response.status_code == 200:
75
+ data = response.json()
76
+ audio_base64 = data["audioUrl"].split(",")[1]
77
+ audio_data = base64.b64decode(audio_base64)
78
+ if verbose:
79
+ self.logger.success(f"Chunk {part_number} processed successfully 🎉")
80
+ return part_number, audio_data
81
+ else:
82
+ if verbose:
83
+ self.logger.warning(f"No data received for chunk {part_number}. Retrying...")
84
+ except requests.RequestException as e:
85
+ if verbose:
86
+ self.logger.error(f"Error for chunk {part_number}: {e}. Retrying... 🔄")
87
+ time.sleep(1)
88
+ try:
89
+ # Using ThreadPoolExecutor to handle requests concurrently
90
+ with ThreadPoolExecutor() as executor:
91
+ futures = {executor.submit(generate_audio_for_chunk, sentence.strip(), chunk_num): chunk_num
92
+ for chunk_num, sentence in enumerate(sentences, start=1)}
93
+
94
+ # Dictionary to store results with order preserved
95
+ audio_chunks = {}
96
+
97
+ for future in as_completed(futures):
98
+ chunk_num = futures[future]
99
+ try:
100
+ part_number, audio_data = future.result()
101
+ audio_chunks[part_number] = audio_data # Store the audio data in correct sequence
102
+ except Exception as e:
103
+ if verbose:
104
+ self.logger.error(f"Failed to generate audio for chunk {chunk_num}: {e} 🚨")
105
+
106
+ # Combine audio chunks in the correct sequence
107
+ combined_audio = BytesIO()
108
+ for part_number in sorted(audio_chunks.keys()):
109
+ combined_audio.write(audio_chunks[part_number])
110
+ if verbose:
111
+ self.logger.debug(f"Added chunk {part_number} to the combined file.")
112
+
113
+ # Save the combined audio data to a single file
114
+ with open(filename, 'wb') as f:
115
+ f.write(combined_audio.getvalue())
116
+ if verbose:
117
+ self.logger.info(f"Final Audio Saved as {filename} 🔊")
118
+ return filename.as_posix()
119
+
120
+ except requests.exceptions.RequestException as e:
121
+ self.logger.critical(f"Failed to perform the operation: {e} 🚨")
122
+ raise exceptions.FailedToGenerateResponseError(
123
+ f"Failed to perform the operation: {e}"
124
+ )
125
+
126
+ def play_audio(self, filename: str):
127
+ """
128
+ Plays an audio file using playsound.
129
+
130
+ Args:
131
+ filename (str): The path to the audio file.
132
+
133
+ Raises:
134
+ RuntimeError: If there is an error playing the audio.
135
+ """
136
+ try:
137
+ playsound(filename)
138
+ except Exception as e:
139
+ self.logger.error(f"Error playing audio: {e} 🔇")
140
+ raise RuntimeError(f"Error playing audio: {e}")
141
+
142
+ # Example usage
143
+ if __name__ == "__main__":
144
+ gesserit = GesseritTTS()
145
+ text = "This is a test of the GesseritTTS text-to-speech API. It supports multiple sentences and advanced logging."
146
+
147
+ gesserit.logger.info("Generating audio...")
148
+ audio_file = gesserit.tts(text, voice="Oliver")
149
+
150
+ gesserit.logger.info("Playing audio...")
151
+ gesserit.play_audio(audio_file)