Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- !pip install openai pydub
- !apt-get install ffmpeg
- """
- If you're interested in efficient, cost-effective TTS solutions, feel free to check out the code and share your thoughts! To use just copy your OpenAI key to Google Drive, drop the code into Google Colab, modify the paths and output text and execute. It really is that easy.
- """
- import openai
- from openai import OpenAI
- from google.colab import drive
- import hashlib
- import os
- from pydub import AudioSegment
- # Mount Google Drive
- drive.mount('/content/drive')
- # Load the OpenAI API key from Google Drive
- keypath = '/content/drive/My Drive/libproc/keys/openai_api_key.txt' # Update this path to your key's location
- with open(keypath, 'r') as f:
- key_text = f.read().strip()
- print(f"Key loaded, length={len(key_text)}")
- openai.api_key = key_text
- client = OpenAI(api_key=key_text)
- def openai_tts(text, output_path, voice='nova'):
- global client
- # Call the TTS API to create the speech synthesis
- response = client.audio.speech.create(
- model="tts-1",
- voice=voice,
- input=text
- )
- with open(output_path, 'wb') as f:
- f.write(response.content)
- def split_text_on_boundary(text, limit=4096):
- """
- Splits the text on carriage return boundaries if it exceeds the character limit.
- Attempts to split the text on newlines, preserving the original newlines and ensuring
- that no chunk exceeds the character limit.
- Args:
- text (str): The text to split.
- limit (int): The character limit for each part.
- Returns:
- list of str: A list of text chunks that respect the character limit.
- Raises:
- Exception: If any chunk exceeds the character limit.
- """
- # Base case: If the text is already under the limit, return it as a single chunk
- if len(text) <= limit:
- return [text]
- # Split the text by newlines
- lines = text.split('\n')
- # Initialize variables for building chunks
- chunks = []
- current_chunk = ""
- for line in lines:
- # Check if adding this line to the current chunk would exceed the limit
- if len(current_chunk) + len(line) + 1 > limit: # +1 accounts for the newline character
- # If the current chunk exceeds the limit, save it and start a new one
- if len(current_chunk) > 0:
- chunks.append(current_chunk)
- current_chunk = ""
- # If the single line itself exceeds the limit, raise an exception
- if len(line) > limit:
- raise Exception(f"Cannot split text: single line exceeds the character limit of {limit} characters. Line: {line[:100]}")
- # Add the line to the current chunk
- if current_chunk:
- current_chunk += '\n' + line # Re-include the newline character
- else:
- current_chunk = line
- # Append the last chunk if it's non-empty
- if current_chunk:
- chunks.append(current_chunk)
- # Assert that rejoining the chunks results in the original text
- reconstructed_text = "\n".join(chunks)
- assert text == reconstructed_text, "The split text chunks cannot reconstruct the original text."
- return chunks
- def concatenate_audio_files(file_list, output_path):
- """
- Concatenates multiple audio files into a single audio file.
- Args:
- file_list (list of str): List of audio file paths to concatenate.
- output_path (str): Path to save the concatenated audio file.
- """
- combined = AudioSegment.empty()
- for file in file_list:
- audio = AudioSegment.from_file(file)
- combined += audio
- combined.export(output_path, format="mp3")
- print(f"Final audio saved as {output_path}")
- def generate_tts_audio(text, final_output_path, voice='nova', temp_dir='/content/drive/My Drive/partial_files', limit=4096):
- """
- Generates TTS audio from text, possibly splitting it into chunks if necessary.
- Uses a cache mechanism to avoid regenerating audio for text chunks that have already been processed.
- Args:
- text (str): The input text to be converted to audio.
- final_output_path (str): The path to save the final concatenated audio file.
- voice (str): The TTS voice to use.
- temp_dir (str): Directory to store partial audio files.
- limit (int): Maximum character limit per chunk.
- Raises:
- Exception: If a text chunk cannot be split on a carriage return boundary.
- """
- # Ensure the temp directory exists
- if not os.path.exists(temp_dir):
- os.makedirs(temp_dir)
- # Split the text into chunks that respect the character limit
- if len(text) > limit:
- parts = split_text_on_boundary(text, limit)
- else:
- parts = [text]
- partial_files = []
- for part in parts:
- # Create a unique hash for the text and voice
- hash_input = f"{part}|{voice}".encode('utf-8')
- sha256_hash = hashlib.sha256(hash_input).hexdigest()
- # Filename for the partial audio file
- partial_filename = os.path.join(temp_dir, f"{sha256_hash}.mp3")
- if not os.path.exists(partial_filename):
- # If the partial file does not exist, generate it
- print(f"Generating audio for chunk: {sha256_hash}")
- openai_tts(part, partial_filename, voice=voice)
- else:
- print(f"Using cached audio for chunk: {sha256_hash}")
- partial_files.append(partial_filename)
- # Concatenate partial audio files into final output
- concatenate_audio_files(partial_files, final_output_path)
- story = r"""
- This is the text that will be converted to audio.
- """.strip().replace('\r', '\n')
- # Path to save the final audio file on Google Drive
- final_output_path = '/content/drive/My Drive/tts_output.mp3' # Update this path as needed
- generate_tts_audio(
- text=story,
- final_output_path=final_output_path,
- voice='nova',
- temp_dir='/content/drive/My Drive/partial_files',
- limit=4096
- )
Advertisement
Add Comment
Please, Sign In to add comment