import gradio as gr import os import tempfile import re from pydub import AudioSegment # Library to combine audio files from openai import OpenAI # Max character limit per API request MAX_CHAR_LIMIT = 4096 def clean_text(text): # Replace newlines with spaces and multiple spaces with a single space cleaned_text = re.sub(r'\s+', ' ', text.strip()) # Replace multiple spaces and newlines with a single space return cleaned_text def split_text(text, limit=MAX_CHAR_LIMIT): # Split text into chunks of <= MAX_CHAR_LIMIT characters words = text.split(' ') chunks = [] current_chunk = "" for word in words: # Add words to the current chunk without exceeding the character limit if len(current_chunk) + len(word) + 1 <= limit: # +1 for space current_chunk += word + " " else: chunks.append(current_chunk.strip()) # Append the current chunk current_chunk = word + " " # Start a new chunk if current_chunk: chunks.append(current_chunk.strip()) # Add the last chunk return chunks def tts(text, model, voice, speed, api_key, base_url): if api_key == '': raise gr.Error('Please enter your Key') cleaned_text = clean_text(text) chunks = split_text(cleaned_text) audio_segments = [] try: client = OpenAI(api_key=api_key, base_url=base_url+'/v1') # Use selected base_url # Process each chunk of text for chunk in chunks: response = client.audio.speech.create( model=model, # "tts-1", "tts-1-hd" voice=voice, # 'alloy', 'echo', 'fable', 'onyx', 'nova', 'shimmer' input=chunk, speed=speed ) # Create a temp file to save the audio for each chunk with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) temp_file_path = temp_file.name audio_segments.append(AudioSegment.from_mp3(temp_file_path)) except Exception as error: raise gr.Error("An error occurred while generating speech. Please check your API key and try again.") # Concatenate all audio chunks into one final audio file final_audio = sum(audio_segments) # Save the concatenated audio to a final file with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as final_temp_file: final_audio.export(final_temp_file.name, format="mp3") final_audio_path = final_temp_file.name return final_audio_path with gr.Blocks() as demo: gr.Markdown("#