webscout 6.4__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 (69) hide show
  1. webscout/AIutel.py +7 -54
  2. webscout/DWEBS.py +48 -26
  3. webscout/{YTdownloader.py → Extra/YTToolkit/YTdownloader.py} +990 -1103
  4. webscout/Extra/YTToolkit/__init__.py +3 -0
  5. webscout/{transcriber.py → Extra/YTToolkit/transcriber.py} +1 -1
  6. webscout/Extra/YTToolkit/ytapi/__init__.py +6 -0
  7. webscout/Extra/YTToolkit/ytapi/channel.py +307 -0
  8. webscout/Extra/YTToolkit/ytapi/errors.py +13 -0
  9. webscout/Extra/YTToolkit/ytapi/extras.py +45 -0
  10. webscout/Extra/YTToolkit/ytapi/https.py +88 -0
  11. webscout/Extra/YTToolkit/ytapi/patterns.py +61 -0
  12. webscout/Extra/YTToolkit/ytapi/playlist.py +59 -0
  13. webscout/Extra/YTToolkit/ytapi/pool.py +8 -0
  14. webscout/Extra/YTToolkit/ytapi/query.py +37 -0
  15. webscout/Extra/YTToolkit/ytapi/stream.py +60 -0
  16. webscout/Extra/YTToolkit/ytapi/utils.py +62 -0
  17. webscout/Extra/YTToolkit/ytapi/video.py +102 -0
  18. webscout/Extra/__init__.py +2 -1
  19. webscout/Extra/autocoder/rawdog.py +679 -680
  20. webscout/Extra/gguf.py +441 -441
  21. webscout/Extra/markdownlite/__init__.py +862 -0
  22. webscout/Extra/weather_ascii.py +2 -2
  23. webscout/Provider/PI.py +292 -221
  24. webscout/Provider/Perplexity.py +6 -14
  25. webscout/Provider/Reka.py +0 -1
  26. webscout/Provider/TTS/__init__.py +5 -1
  27. webscout/Provider/TTS/deepgram.py +183 -0
  28. webscout/Provider/TTS/elevenlabs.py +137 -0
  29. webscout/Provider/TTS/gesserit.py +151 -0
  30. webscout/Provider/TTS/murfai.py +139 -0
  31. webscout/Provider/TTS/parler.py +134 -107
  32. webscout/Provider/TTS/streamElements.py +360 -275
  33. webscout/Provider/TTS/utils.py +280 -0
  34. webscout/Provider/TTS/voicepod.py +116 -116
  35. webscout/Provider/__init__.py +146 -146
  36. webscout/Provider/meta.py +794 -779
  37. webscout/Provider/typegpt.py +1 -2
  38. webscout/__init__.py +24 -28
  39. webscout/litprinter/__init__.py +831 -830
  40. webscout/optimizers.py +269 -269
  41. webscout/prompt_manager.py +279 -279
  42. webscout/scout/__init__.py +11 -0
  43. webscout/scout/core.py +884 -0
  44. webscout/scout/element.py +459 -0
  45. webscout/scout/parsers/__init__.py +69 -0
  46. webscout/scout/parsers/html5lib_parser.py +172 -0
  47. webscout/scout/parsers/html_parser.py +236 -0
  48. webscout/scout/parsers/lxml_parser.py +178 -0
  49. webscout/scout/utils.py +38 -0
  50. webscout/update_checker.py +125 -125
  51. webscout/version.py +1 -1
  52. webscout/zeroart/__init__.py +55 -0
  53. webscout/zeroart/base.py +61 -0
  54. webscout/zeroart/effects.py +99 -0
  55. webscout/zeroart/fonts.py +816 -0
  56. webscout/zerodir/__init__.py +225 -0
  57. {webscout-6.4.dist-info → webscout-6.5.dist-info}/METADATA +12 -68
  58. {webscout-6.4.dist-info → webscout-6.5.dist-info}/RECORD +62 -37
  59. webscout/Agents/Onlinesearcher.py +0 -182
  60. webscout/Agents/__init__.py +0 -2
  61. webscout/Agents/functioncall.py +0 -248
  62. webscout/Bing_search.py +0 -251
  63. webscout/gpt4free.py +0 -666
  64. webscout/requestsHTMLfix.py +0 -775
  65. webscout/webai.py +0 -2590
  66. {webscout-6.4.dist-info → webscout-6.5.dist-info}/LICENSE.md +0 -0
  67. {webscout-6.4.dist-info → webscout-6.5.dist-info}/WHEEL +0 -0
  68. {webscout-6.4.dist-info → webscout-6.5.dist-info}/entry_points.txt +0 -0
  69. {webscout-6.4.dist-info → webscout-6.5.dist-info}/top_level.txt +0 -0
@@ -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)
@@ -0,0 +1,139 @@
1
+ import time
2
+ import requests
3
+ import pathlib
4
+ from io import BytesIO
5
+ from urllib.parse import urlencode
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 MurfAITTS(TTSProvider):
15
+ """Text-to-speech provider using the MurfAITTS 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] = {"Hazel": "en-UK-hazel"}
22
+
23
+ def __init__(self, timeout: int = 20, proxies: dict = None):
24
+ """Initializes the MurfAITTS TTS client."""
25
+ self.session = requests.Session()
26
+ self.session.headers.update(self.headers)
27
+ if proxies:
28
+ self.session.proxies.update(proxies)
29
+ self.timeout = timeout
30
+ self.logger = LitLogger(
31
+ name="MurfAITTS",
32
+ format=LogFormat.MODERN_EMOJI,
33
+ color_scheme=ColorScheme.AURORA
34
+ )
35
+
36
+ def tts(self, text: str, voice: str = "Hazel", verbose:bool = True) -> str:
37
+ """Converts text to speech using the MurfAITTS API and saves it to a file."""
38
+ assert (
39
+ voice in self.all_voices
40
+ ), f"Voice '{voice}' not one of [{', '.join(self.all_voices.keys())}]"
41
+
42
+ filename = self.cache_dir / f"{int(time.time())}.mp3"
43
+
44
+ voice_id = self.all_voices[voice]
45
+
46
+ # Split text into sentences
47
+ sentences = utils.split_sentences(text)
48
+
49
+ # Function to request audio for each chunk
50
+ def generate_audio_for_chunk(part_text: str, part_number: int):
51
+ while True:
52
+ try:
53
+ params: dict[str, str] = {
54
+ "name": voice_id,
55
+ "text": part_text
56
+ }
57
+ encode_param: str = urlencode(params)
58
+ response = self.session.get(f"https://murf.ai/Prod/anonymous-tts/audio?{encode_param}", headers=self.headers, timeout=self.timeout)
59
+ response.raise_for_status()
60
+
61
+ # Create the audio_cache directory if it doesn't exist
62
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
63
+
64
+ # Check if the request was successful
65
+ if response.ok and response.status_code == 200:
66
+ if verbose:
67
+ self.logger.success(f"Chunk {part_number} processed successfully 🎉")
68
+ return part_number, response.content
69
+ else:
70
+ if verbose:
71
+ self.logger.warning(f"No data received for chunk {part_number}. Retrying...")
72
+ except requests.RequestException as e:
73
+ if verbose:
74
+ self.logger.error(f"Error for chunk {part_number}: {e}. Retrying... 🔄")
75
+ time.sleep(1)
76
+ try:
77
+ # Using ThreadPoolExecutor to handle requests concurrently
78
+ with ThreadPoolExecutor() as executor:
79
+ futures = {executor.submit(generate_audio_for_chunk, sentence.strip(), chunk_num): chunk_num
80
+ for chunk_num, sentence in enumerate(sentences, start=1)}
81
+
82
+ # Dictionary to store results with order preserved
83
+ audio_chunks = {}
84
+
85
+ for future in as_completed(futures):
86
+ chunk_num = futures[future]
87
+ try:
88
+ part_number, audio_data = future.result()
89
+ audio_chunks[part_number] = audio_data # Store the audio data in correct sequence
90
+ except Exception as e:
91
+ if verbose:
92
+ self.logger.error(f"Failed to generate audio for chunk {chunk_num}: {e} 🚨")
93
+
94
+ # Combine audio chunks in the correct sequence
95
+ combined_audio = BytesIO()
96
+ for part_number in sorted(audio_chunks.keys()):
97
+ combined_audio.write(audio_chunks[part_number])
98
+ if verbose:
99
+ self.logger.debug(f"Added chunk {part_number} to the combined file.")
100
+
101
+ # Save the combined audio data to a single file
102
+ with open(filename, 'wb') as f:
103
+ f.write(combined_audio.getvalue())
104
+ if verbose:
105
+ self.logger.info(f"Final Audio Saved as {filename} 🔊")
106
+ return filename.as_posix()
107
+
108
+ except requests.exceptions.RequestException as e:
109
+ self.logger.critical(f"Failed to perform the operation: {e} 🚨")
110
+ raise exceptions.FailedToGenerateResponseError(
111
+ f"Failed to perform the operation: {e}"
112
+ )
113
+
114
+ def play_audio(self, filename: str):
115
+ """
116
+ Plays an audio file using playsound.
117
+
118
+ Args:
119
+ filename (str): The path to the audio file.
120
+
121
+ Raises:
122
+ RuntimeError: If there is an error playing the audio.
123
+ """
124
+ try:
125
+ playsound(filename)
126
+ except Exception as e:
127
+ self.logger.error(f"Error playing audio: {e} 🔇")
128
+ raise RuntimeError(f"Error playing audio: {e}")
129
+
130
+ # Example usage
131
+ if __name__ == "__main__":
132
+ murfai = MurfAITTS()
133
+ text = "This is a test of the MurfAITTS text-to-speech API. It supports multiple sentences and advanced logging."
134
+
135
+ murfai.logger.info("Generating audio...")
136
+ audio_file = murfai.tts(text, voice="Hazel")
137
+
138
+ murfai.logger.info("Playing audio...")
139
+ murfai.play_audio(audio_file)