lucgumshoe

OpenAI TTS Google Colab Code

Sep 15th, 2024
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.99 KB | None | 0 0
  1. !pip install openai pydub
  2. !apt-get install ffmpeg
  3.  
  4. """
  5.  
  6. 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.
  7.  
  8. """
  9.  
  10.  
  11. import openai
  12. from openai import OpenAI
  13. from google.colab import drive
  14. import hashlib
  15. import os
  16. from pydub import AudioSegment
  17.  
  18. # Mount Google Drive
  19. drive.mount('/content/drive')
  20.  
  21. # Load the OpenAI API key from Google Drive
  22. keypath = '/content/drive/My Drive/libproc/keys/openai_api_key.txt'  # Update this path to your key's location
  23. with open(keypath, 'r') as f:
  24.     key_text = f.read().strip()
  25. print(f"Key loaded, length={len(key_text)}")
  26. openai.api_key = key_text
  27. client = OpenAI(api_key=key_text)
  28.  
  29. def openai_tts(text, output_path, voice='nova'):
  30.     global client
  31.  
  32.     # Call the TTS API to create the speech synthesis
  33.     response = client.audio.speech.create(
  34.         model="tts-1",
  35.         voice=voice,
  36.         input=text
  37.     )
  38.  
  39.     with open(output_path, 'wb') as f:
  40.         f.write(response.content)
  41.  
  42. def split_text_on_boundary(text, limit=4096):
  43.     """
  44.    Splits the text on carriage return boundaries if it exceeds the character limit.
  45.    Attempts to split the text on newlines, preserving the original newlines and ensuring
  46.    that no chunk exceeds the character limit.
  47.  
  48.    Args:
  49.        text (str): The text to split.
  50.        limit (int): The character limit for each part.
  51.  
  52.    Returns:
  53.        list of str: A list of text chunks that respect the character limit.
  54.  
  55.    Raises:
  56.        Exception: If any chunk exceeds the character limit.
  57.    """
  58.  
  59.     # Base case: If the text is already under the limit, return it as a single chunk
  60.     if len(text) <= limit:
  61.         return [text]
  62.  
  63.     # Split the text by newlines
  64.     lines = text.split('\n')
  65.  
  66.     # Initialize variables for building chunks
  67.     chunks = []
  68.     current_chunk = ""
  69.  
  70.     for line in lines:
  71.         # Check if adding this line to the current chunk would exceed the limit
  72.         if len(current_chunk) + len(line) + 1 > limit:  # +1 accounts for the newline character
  73.             # If the current chunk exceeds the limit, save it and start a new one
  74.             if len(current_chunk) > 0:
  75.                 chunks.append(current_chunk)
  76.                 current_chunk = ""
  77.  
  78.             # If the single line itself exceeds the limit, raise an exception
  79.             if len(line) > limit:
  80.                 raise Exception(f"Cannot split text: single line exceeds the character limit of {limit} characters. Line: {line[:100]}")
  81.  
  82.         # Add the line to the current chunk
  83.         if current_chunk:
  84.             current_chunk += '\n' + line  # Re-include the newline character
  85.         else:
  86.             current_chunk = line
  87.  
  88.     # Append the last chunk if it's non-empty
  89.     if current_chunk:
  90.         chunks.append(current_chunk)
  91.  
  92.     # Assert that rejoining the chunks results in the original text
  93.     reconstructed_text = "\n".join(chunks)
  94.     assert text == reconstructed_text, "The split text chunks cannot reconstruct the original text."
  95.  
  96.     return chunks
  97.  
  98.  
  99. def concatenate_audio_files(file_list, output_path):
  100.     """
  101.    Concatenates multiple audio files into a single audio file.
  102.  
  103.    Args:
  104.        file_list (list of str): List of audio file paths to concatenate.
  105.        output_path (str): Path to save the concatenated audio file.
  106.    """
  107.     combined = AudioSegment.empty()
  108.  
  109.     for file in file_list:
  110.         audio = AudioSegment.from_file(file)
  111.         combined += audio
  112.  
  113.     combined.export(output_path, format="mp3")
  114.     print(f"Final audio saved as {output_path}")
  115.  
  116. def generate_tts_audio(text, final_output_path, voice='nova', temp_dir='/content/drive/My Drive/partial_files', limit=4096):
  117.     """
  118.    Generates TTS audio from text, possibly splitting it into chunks if necessary.
  119.    Uses a cache mechanism to avoid regenerating audio for text chunks that have already been processed.
  120.  
  121.    Args:
  122.        text (str): The input text to be converted to audio.
  123.        final_output_path (str): The path to save the final concatenated audio file.
  124.        voice (str): The TTS voice to use.
  125.        temp_dir (str): Directory to store partial audio files.
  126.        limit (int): Maximum character limit per chunk.
  127.  
  128.    Raises:
  129.        Exception: If a text chunk cannot be split on a carriage return boundary.
  130.    """
  131.     # Ensure the temp directory exists
  132.     if not os.path.exists(temp_dir):
  133.         os.makedirs(temp_dir)
  134.  
  135.     # Split the text into chunks that respect the character limit
  136.     if len(text) > limit:
  137.         parts = split_text_on_boundary(text, limit)
  138.     else:
  139.         parts = [text]
  140.  
  141.     partial_files = []
  142.  
  143.     for part in parts:
  144.         # Create a unique hash for the text and voice
  145.         hash_input = f"{part}|{voice}".encode('utf-8')
  146.         sha256_hash = hashlib.sha256(hash_input).hexdigest()
  147.  
  148.         # Filename for the partial audio file
  149.         partial_filename = os.path.join(temp_dir, f"{sha256_hash}.mp3")
  150.  
  151.         if not os.path.exists(partial_filename):
  152.             # If the partial file does not exist, generate it
  153.             print(f"Generating audio for chunk: {sha256_hash}")
  154.             openai_tts(part, partial_filename, voice=voice)
  155.         else:
  156.             print(f"Using cached audio for chunk: {sha256_hash}")
  157.  
  158.         partial_files.append(partial_filename)
  159.  
  160.     # Concatenate partial audio files into final output
  161.     concatenate_audio_files(partial_files, final_output_path)
  162.  
  163.  
  164. story = r"""
  165.  
  166. This is the text that will be converted to audio.
  167.  
  168.  
  169. """.strip().replace('\r', '\n')
  170.  
  171. # Path to save the final audio file on Google Drive
  172. final_output_path = '/content/drive/My Drive/tts_output.mp3'  # Update this path as needed
  173.  
  174. generate_tts_audio(
  175.     text=story,
  176.     final_output_path=final_output_path,
  177.     voice='nova',
  178.     temp_dir='/content/drive/My Drive/partial_files',
  179.     limit=4096
  180. )
  181.  
Advertisement
Add Comment
Please, Sign In to add comment