|
| 1 | +# Python standard modules |
| 2 | +import os |
| 3 | +import requests |
| 4 | +import base64 |
| 5 | +import re |
| 6 | +from json import load |
| 7 | +from threading import Thread |
| 8 | +from typing import Dict, List, Optional |
| 9 | + |
| 10 | +# Downloaded modules |
| 11 | +from playsound import playsound |
| 12 | + |
| 13 | +# Local files |
| 14 | +from .voice import Voice |
| 15 | + |
| 16 | +def tts( |
| 17 | + text: str, |
| 18 | + voice: Voice, |
| 19 | + output_file_path: str = "output.mp3", |
| 20 | + play_sound: bool = False |
| 21 | +): |
| 22 | + """Main function to convert text to speech and save to a file.""" |
| 23 | + |
| 24 | + # Validate input arguments |
| 25 | + _validate_args(text, voice) |
| 26 | + |
| 27 | + # Load endpoint data from the endpoints.json file |
| 28 | + endpoint_data: List[Dict[str, str]] = _load_endpoints() |
| 29 | + |
| 30 | + |
| 31 | + # Iterate over endpoints to find a working one |
| 32 | + for endpoint in endpoint_data: |
| 33 | + # Generate audio bytes from the current endpoint |
| 34 | + audio_bytes: bytes = _fetch_audio_bytes(endpoint, text, voice) |
| 35 | + |
| 36 | + if audio_bytes: |
| 37 | + # Save the generated audio to a file |
| 38 | + _save_audio_file(output_file_path, audio_bytes) |
| 39 | + |
| 40 | + # Optionally play the audio file |
| 41 | + if play_sound: |
| 42 | + playsound(output_file_path) |
| 43 | + |
| 44 | + # Stop after processing a valid endpoint |
| 45 | + break |
| 46 | + |
| 47 | +def _save_audio_file(output_file_path: str, audio_bytes: bytes): |
| 48 | + """Write the audio bytes to a file.""" |
| 49 | + if os.path.exists(output_file_path): |
| 50 | + os.remove(output_file_path) |
| 51 | + |
| 52 | + with open(output_file_path, "wb") as file: |
| 53 | + file.write(audio_bytes) |
| 54 | + |
| 55 | +def _fetch_audio_bytes( |
| 56 | + endpoint: Dict[str, str], |
| 57 | + text: str, |
| 58 | + voice: Voice |
| 59 | +) -> Optional[bytes]: |
| 60 | + """Fetch audio data from an endpoint and decode it.""" |
| 61 | + |
| 62 | + # Initialize variables for endpoint validity and audio data |
| 63 | + text_chunks: List[str] = _split_text(text) |
| 64 | + audio_chunks: List[str] = ["" for _ in range(len(text_chunks))] |
| 65 | + |
| 66 | + # Function to generate audio for each text chunk |
| 67 | + def generate_audio_chunk(index: int, text_chunk: str): |
| 68 | + try: |
| 69 | + response = requests.post(endpoint["url"], json={"text": text_chunk, "voice": voice.value}) |
| 70 | + response.raise_for_status() |
| 71 | + audio_chunks[index] = response.json()[endpoint["response"]] |
| 72 | + except (requests.RequestException, KeyError): |
| 73 | + return |
| 74 | + |
| 75 | + # Start threads for generating audio for each chunk |
| 76 | + threads = [Thread(target=generate_audio_chunk, args=(i, chunk)) for i, chunk in enumerate(text_chunks)] |
| 77 | + for thread in threads: |
| 78 | + thread.start() |
| 79 | + |
| 80 | + for thread in threads: |
| 81 | + thread.join() |
| 82 | + |
| 83 | + if any(not chunk for chunk in audio_chunks): |
| 84 | + return None |
| 85 | + |
| 86 | + # Concatenate and decode audio data from all chunks |
| 87 | + return base64.b64decode("".join(audio_chunks)) |
| 88 | + |
| 89 | +def _load_endpoints() -> List[Dict[str, str]]: |
| 90 | + """Load endpoint configurations from a JSON file.""" |
| 91 | + script_dir = os.path.dirname(__file__) |
| 92 | + json_file_path = os.path.join(script_dir, '../data', 'config.json') |
| 93 | + with open(json_file_path, 'r') as file: |
| 94 | + return load(file) |
| 95 | + |
| 96 | +def _validate_args(text: str, voice: Voice): |
| 97 | + """Validate the input arguments.""" |
| 98 | + |
| 99 | + # Check if the voice is of the correct type |
| 100 | + if not isinstance(voice, Voice): |
| 101 | + raise TypeError("'voice' must be of type Voice") |
| 102 | + |
| 103 | + # Check if the text is not empty |
| 104 | + if not text: |
| 105 | + raise ValueError("text must not be empty") |
| 106 | + |
| 107 | +def _split_text(text: str) -> List[str]: |
| 108 | + """Split text into chunks of 300 characters or less.""" |
| 109 | + |
| 110 | + # Split text into chunks based on punctuation marks |
| 111 | + merged_chunks: List[str] = [] |
| 112 | + separated_chunks: List[str] = re.findall(r'.*?[.,!?:;-]|.+', text) |
| 113 | + |
| 114 | + # Further split any chunks longer than 300 characters |
| 115 | + for i, chunk in enumerate(separated_chunks): |
| 116 | + if len(chunk) > 300: |
| 117 | + separated_chunks[i:i+1] = re.findall(r'.*?[ ]|.+', chunk) |
| 118 | + |
| 119 | + # Combine chunks into segments of 300 characters or less |
| 120 | + current_chunk: str = "" |
| 121 | + for separated_chunk in separated_chunks: |
| 122 | + if len(current_chunk) + len(separated_chunk) <= 300: |
| 123 | + current_chunk += separated_chunk |
| 124 | + else: |
| 125 | + merged_chunks.append(current_chunk) |
| 126 | + current_chunk = separated_chunk |
| 127 | + |
| 128 | + # Append the last chunk |
| 129 | + merged_chunks.append(current_chunk) |
| 130 | + return merged_chunks |
0 commit comments