diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..507675c --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,9 @@ +{ + "files.associations": { + "*.html": "jinja-html" + }, + "emmet.includeLanguages": { + "jinja-html": "html", + "jinja2": "html" + }, +} \ No newline at end of file diff --git a/README.md b/README.md index 61bf387..1eece6d 100644 --- a/README.md +++ b/README.md @@ -69,11 +69,13 @@ Once the extension is loaded, please find all documentation and settings on the **Where to find voices** https://aiartes.com/voiceai or https://commons.wikimedia.org/ or interviews on youtube etc. Instructions on how to cut down and prepare a voice sample are within the built in documentation. #### 🟩 The one thing I cant easily work around -Narrator function specific - With a RP chat with your AI, **on your character card** `parameters menu` > `character tab` > `greeting` make sure that anything in there that is the **narrator is in asterisks** and anything **spoken is in double quotes**, then hit the `save` (💾) button. Greeting paragraphs/sentences are handled differently from how the AI sends text and so its difficut to account for them both. +Messages intended for the Narrator should be enclosed in asterisks `*` and those for the character inside quotation marks `"`. However, AI systems often deviate from these rules, resulting in text that is neither in quotes nor asterisks. Sometimes, text may appear with only a single asterisk, and AI models may vary their formatting mid-conversation. For example, they might use asterisks initially and then switch to unmarked text. A properly formatted line should look like this: -I could force a delimeter in at this stage, but I know it would/may affect things further down the line in the chat and I need a good think about that before just making a change. This issue **only** affects the greeting card/start of conversation and the "example" card that comes with text-generation-webui suffers this issue (if you want to try it for yourself). So you would put double quotes around like this (from the example card): +`"`Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers.`"` `*`She walked across the room and picked up her cup of coffee`*` -`"`*Hey! I'm so excited to finally meet you. I've heard so many great things about you and I'm eager to pick your brain about computers. I'm sure you have a wealth of knowledge that I can learn from.*`"` +Most narrator/character systems switch voices upon encountering an asterisk or quotation marks, which is somewhat effective. AllTalk has undergone several revisions in its sentence splitting and identification methods. While some irregularities and AI deviations in message formatting are inevitable, any line beginning or ending with an asterisk should now be recognized as Narrator dialogue. Lines enclosed in double quotes are identified as Character dialogue. For any other text, you can choose how AllTalk handles it: whether it should be interpreted as Character or Narrator dialogue (most AI systems tend to lean more towards one format when generating text not enclosed in quotes or asterisks). + +With improvements to the splitter/processor, I'm confident it's functioning well. You can monitor what AllTalk identifies as Narrator lines on the command line and adjust its behavior if needed (Text Not Inside - Function). ## 🟪 Updating This is pretty much a repeat of the installation process. diff --git a/script.py b/script.py index 3e6d98e..d2a42dd 100644 --- a/script.py +++ b/script.py @@ -509,11 +509,53 @@ def voice_preview(string): return f"[{params['branding']}Server] Audio generation failed. Status: {generate_response.get('status')}" -#def replace_asterisk(match): -# return match.group(0) + '"<*' +def process_text(text): + # Normalize HTML encoded quotes + text = html.unescape(text) -def replace_asterisk(match): - return '"<*' + # Replace ellipsis with a single dot + text = re.sub(r'\.{3,}', '.', text) + + # Pattern to identify combined narrator and character speech + combined_pattern = r'(\*[^*"]+\*|"[^"*]+")' + + # List to hold parts of speech along with their type + ordered_parts = [] + + # Track the start of the next segment + start = 0 + + # Find all matches + for match in re.finditer(combined_pattern, text): + # Add the text before the match, if any, as ambiguous + if start < match.start(): + ambiguous_text = text[start:match.start()].strip() + if ambiguous_text: + ordered_parts.append(('ambiguous', ambiguous_text)) + + # Add the matched part as either narrator or character + matched_text = match.group(0) + if matched_text.startswith('*') and matched_text.endswith('*'): + ordered_parts.append(('narrator', matched_text.strip('*').strip())) + elif matched_text.startswith('"') and matched_text.endswith('"'): + ordered_parts.append(('character', matched_text.strip('"').strip())) + else: + # In case of mixed or improperly formatted parts + if '*' in matched_text: + ordered_parts.append(('narrator', matched_text.strip('*').strip('"'))) + else: + ordered_parts.append(('character', matched_text.strip('"').strip('*'))) + + # Update the start of the next segment + start = match.end() + + # Add any remaining text after the last match as ambiguous + if start < len(text): + ambiguous_text = text[start:].strip() + if ambiguous_text: + ordered_parts.append(('ambiguous', ambiguous_text)) + + return ordered_parts ################################# #### TTS STANDARD GENERATION #### @@ -534,86 +576,55 @@ def output_modifier(string, state): if process_lock.acquire(blocking=False): try: if params["narrator_enabled"]: - # Do Some basic stripping and remove any double CR's - processed_string = ( - original_string - .replace("***", "*") - .replace("**", "*") - .replace("\n\n", "\n") - .replace("\n", "") - ) - processed_string = re.sub(r'\.\*\n\*', '. ', processed_string) - processed_string = (processed_string .replace('"\n\n*', '"<*')) - processed_string = (processed_string .replace('"\n', '< ')) - processed_string = (processed_string .replace("'", "'")) - processed_string = (processed_string .replace("\n", " ")) - processed_string = (processed_string .replace('"', '"<')) - processed_string = (processed_string .replace('"', '"<')) - #pattern = re.compile(r'(?<=[a-zA-Z!])"<(?=[a-zA-Z])') - pattern = re.compile(r'(?<=[a-zA-Z!?\.])"<(?=[a-zA-Z])') - processed_string = pattern.sub('" ', processed_string) - pattern = re.compile(r'(?<=[a-zA-Z])\*(?=[a-zA-Z])') - processed_string = pattern.sub('*"', processed_string) - processed_string = processed_string.replace('"<. *', '"< *"') - processed_string = processed_string.replace('< *"', '< *') - processed_string = processed_string.replace('. *', '< *') - processed_string = processed_string.replace('! *', '"< *') - processed_string = processed_string.replace('? *', '< *') - processed_string = processed_string.replace('* ', '* "<') - processed_string = processed_string.replace('*. ', '* "<') - processed_string = re.sub(r'\*(?=[a-zA-Z])', replace_asterisk, processed_string) - #print("PROCESSED STRING IS:", processed_string) - # Set up a tracking of the individual wav files. + processed_parts = process_text(original_string) + audio_files_all_paragraphs = [] - # Split the line using " and ".* " (so end of sentences, leaving special characters added to the start of all OTHER sentences, bar possibly the first one if its starting with a * - parts = re.split(r'"|\.\*', processed_string) - audio_files_paragraph = [] - for i, part in enumerate(parts): + for part_type, part in processed_parts: # Skip parts that are too short if len(part.strip()) <= 3: continue - # Figure out which type of line it is, then replace characters as necessary to avoid TTS trying to pronunce them, htmlunescape after. - # Character will always be a < with a letter immediately after it - #print("PART IS:", part) - if '<' in part and '< *' not in part and '<*' not in part and '< *' not in part and '< ' not in part and '< ' not in part: - cleaned_part = html.unescape(part.replace('<', '')) - voice_to_use = params["voice"] - #Narrator will always be an * or < with an * a position or two after it. - elif '<*' in part or '< *' in part or '< *' in part or '*' in part: - cleaned_part = html.unescape(part.replace('<*', '').replace('< *', '').replace('< *', '').replace('*', '')) + + # Determine the voice to use based on the part type + if part_type == 'narrator': voice_to_use = params["narrator_voice"] - #If the other two dont capture it, aka, the AI gave no * or " on the line, use non_quoted_text_is aka user interface, user can choose Char or Narrator - elif non_quoted_text_is: - #print("HIT ELIF CHAR VOICE") - cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) + print(f"[{params['branding']}TTSGen] \033[92mNarrator\033[0m") # Green + elif part_type == 'character': voice_to_use = params["voice"] + print(f"[{params['branding']}TTSGen] \033[36mCharacter\033[0m") # Yellow else: - #print("HIT ELIF NARRATOR VOICE") - cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) - voice_to_use = params["narrator_voice"] - # Generate that TTS and output to a file + # Handle ambiguous parts based on user preference + voice_to_use = params["voice"] if non_quoted_text_is else params["narrator_voice"] + voice_description = "\033[36mCharacter (Text-not-inside)\033[0m" if non_quoted_text_is else "\033[92mNarrator (Text-not-inside)\033[0m" + print(f"[{params['branding']}TTSGen] {voice_description}") + + # Replace multiple exclamation marks, question marks, or other punctuation with a single instance + cleaned_part = re.sub(r'([!?.])\1+', r'\1', part) + # Further clean to remove any other unwanted characters + cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_part) + # Remove all newline characters (single or multiple) + cleaned_part = re.sub(r'\n+', ' ', cleaned_part) + + # Generate TTS and output to a file output_filename = get_output_filename(state) generate_response = send_generate_request( cleaned_part, voice_to_use, language_code, output_filename ) audio_path = generate_response.get("data", {}).get("audio_path") - audio_files_paragraph.append(audio_path) - # Accumulate audio files within the paragraph - audio_files_all_paragraphs.extend(audio_files_paragraph) + audio_files_all_paragraphs.append(audio_path) + # Combine audio files across paragraphs final_output_file = combine( audio_files_all_paragraphs, params["output_folder_wav"], state ) else: - processed_string = ( - original_string - .replace("***", "") - .replace("**", "") - .replace("*", "") - .replace("\n\n", "\n") - .replace("'", "'") - ) - cleaned_part = html.unescape(processed_string) + # Decode HTML entities first + cleaned_part = html.unescape(original_string) + # Replace multiple instances of certain punctuation marks with a single instance + cleaned_part = re.sub(r'([!?.])\1+', r'\1', cleaned_part) + # Further clean to remove any other unwanted characters + cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_part) + # Remove all newline characters (single or multiple) + cleaned_part = re.sub(r'\n+', ' ', cleaned_part) # Process the part and give it a non-character name if being used vai API or standalone. if "character_menu" in state: output_file = Path(f'{params["output_folder_wav"]}/{state["character_menu"]}_{int(time.time())}.wav') @@ -721,10 +732,6 @@ def input_modifier(string, state): shared.processing_message = "*Is recording a voice message...*" return string -def custom_css(): - path_to_css = Path(f"{this_dir}/style.css") - return open(path_to_css, "r").read() - def ui(): with gr.Accordion(params["branding"] + " TTS (XTTSv2)"): diff --git a/style.css b/style.css deleted file mode 100644 index 2330a74..0000000 --- a/style.css +++ /dev/null @@ -1,8 +0,0 @@ -.SDAP .hires_opts input[type="number"] { - width: 6em !important; -} - -/* silero_tts preview */ -.form:has(> #silero_preview_text) { - min-width: 75% -} diff --git a/templates/TTS_Input_Proof_of_concept.html b/templates/TTS_Input_Proof_of_concept.html new file mode 100644 index 0000000..0cb5333 --- /dev/null +++ b/templates/TTS_Input_Proof_of_concept.html @@ -0,0 +1,584 @@ + + + + + + + AllTalk TTS Generator + + + + +

AllTalk TTS Generator

+ +
+
+ + +
+ +
+ +
+ + +
+ +
+ + +
+ + +
+ + +
+ +
+ + +
+ +
+ + + 3 +
+ +
+ + + 0.8 +
+
+ + +
+ + + +
+ + +
+ + + + + + + + \ No newline at end of file diff --git a/templates/admin.html b/templates/admin.html index 1053047..bcb4f2b 100644 --- a/templates/admin.html +++ b/templates/admin.html @@ -410,6 +410,13 @@ // Get and clean the text input from the textarea let textInput = formData.get('text'); let cleanedText = textInput.replace(/ \- | \– /g, ' '); // Replace hyphens + + // Get and clean the text input from the textarea + let textInput = formData.get('text'); + let cleanedText = textInput.replace(/ \- | \– /g, ' '); // Replace hyphens + cleanedText = cleanedText.replace(/([!?.])\1+/g, '$1'); + cleanedText = cleanedText.replace(/[^a-zA-Z0-9\s\.,;:!?\-\'"]/g, ''); + cleanedText = cleanedText.replace(/\n+/g, ' '); cleanedText = cleanedText.replace(/\.\s'/g, ".'"); // Remove space between period and single quote cleanedText = cleanedText.replace(/'/g, ""); // Remove all single quotes diff --git a/tts_server.py b/tts_server.py index e9a6e5a..6153b47 100644 --- a/tts_server.py +++ b/tts_server.py @@ -6,6 +6,8 @@ import torch import torchaudio from TTS.tts.configs.xtts_config import XttsConfig from TTS.tts.models.xtts import Xtts +import io +import wave ########################## #### Webserver Imports#### @@ -16,11 +18,12 @@ from fastapi import ( Request, Response, Depends, + HTTPException, ) -from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse, FileResponse +from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse, FileResponse, StreamingResponse +from fastapi.middleware.cors import CORSMiddleware from fastapi.templating import Jinja2Templates from fastapi.staticfiles import StaticFiles -from jinja2 import Template from contextlib import asynccontextmanager ########################### @@ -86,10 +89,10 @@ try: from TTS.api import TTS from TTS.utils.synthesizer import Synthesizer except ModuleNotFoundError: - logger.error( - f"[{params['branding']}Startup] \033[91mWarning\033[0m Could not find the TTS module. Make sure to install the requirements for the alltalk_tts extension." - f"[{params['branding']}Startup] \033[91mWarning\033[0m Linux / Mac:\npip install -r extensions/alltalk_tts/requirements.txt\n" - f"[{params['branding']}Startup] \033[91mWarning\033[0m Windows:\npip install -r extensions\\alltalk_tts\\requirements.txt\n" + print( + f"[{params['branding']}Startup] \033[91mWarning\033[0m Could not find the TTS module. Make sure to install the requirements for the alltalk_tts extension.", + f"[{params['branding']}Startup] \033[91mWarning\033[0m Linux / Mac:\npip install -r extensions/alltalk_tts/requirements.txt\n", + f"[{params['branding']}Startup] \033[91mWarning\033[0m Windows:\npip install -r extensions\\alltalk_tts\\requirements.txt\n", f"[{params['branding']}Startup] \033[91mWarning\033[0m If you used the one-click installer, paste the command above in the terminal window launched after running the cmd_ script. On Windows, that's cmd_windows.bat." ) raise @@ -119,7 +122,14 @@ async def startup_shutdown(no_actual_value_it_demanded_something_be_here): # Create FastAPI app with lifespan app = FastAPI(lifespan=startup_shutdown) - +# Allow all origins, and set other CORS options +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # Set this to the specific origins you want to allow + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) ##################################### #### MODEL LOADING AND UNLOADING #### @@ -452,12 +462,23 @@ async def deepspeed(request: Request, new_deepspeed_value: bool): ######################## #### TTS GENERATION #### ######################## + # TTS VOICE GENERATION METHODS (called from voice_preview and output_modifer) -async def generate_audio(text, voice, language, output_file): +async def generate_audio(text, voice, language, output_file, streaming=False): + # Get the async generator from the internal function + response = generate_audio_internal(text, voice, language, output_file, streaming) + # If streaming, then return the generator as-is, otherwise just exhaust it and return + if streaming: + return response + async for _ in response: + pass + +async def generate_audio_internal(text, voice, language, output_file, streaming): global model if params["low_vram"] and device == "cpu": await switch_device() generate_start_time = time.time() # Record the start time of generating TTS + # XTTSv2 LOCAL & Xttsv2 FT Method if params["tts_method_xtts_local"] or tts_method_xtts_ft: print(f"[{params['branding']}TTSGen] {text}") @@ -467,21 +488,62 @@ async def generate_audio(text, voice, language, output_file): max_ref_length=model.config.max_ref_len, sound_norm_refs=model.config.sound_norm_refs, ) - out = model.inference( - text, - language, - gpt_cond_latent=gpt_cond_latent, - speaker_embedding=speaker_embedding, - temperature=float(params["local_temperature"]), - length_penalty=float(model.config.length_penalty), - repetition_penalty=float(params["local_repetition_penalty"]), - top_k=int(model.config.top_k), # Convert to int if necessary - top_p=float(model.config.top_p), - enable_text_splitting=True, - ) - torchaudio.save(output_file, torch.tensor(out["wav"]).unsqueeze(0), 24000) + + # Common arguments for both functions + common_args = { + "text": text, + "language": language, + "gpt_cond_latent": gpt_cond_latent, + "speaker_embedding": speaker_embedding, + "temperature": float(params["local_temperature"]), + "length_penalty": float(model.config.length_penalty), + "repetition_penalty": float(params["local_repetition_penalty"]), + "top_k": int(model.config.top_k), + "top_p": float(model.config.top_p), + "enable_text_splitting": True + } + + # Determine the correct inference function and add streaming specific argument if needed + inference_func = model.inference_stream if streaming else model.inference + if streaming: + common_args["stream_chunk_size"] = 20 + + # Call the appropriate function + output = inference_func(**common_args) + + # Process the output based on streaming or non-streaming + if streaming: + # Streaming-specific operations + file_chunks = [] + wav_buf = io.BytesIO() + with wave.open(wav_buf, "wb") as vfout: + vfout.setnchannels(1) + vfout.setsampwidth(2) + vfout.setframerate(24000) + vfout.writeframes(b"") + wav_buf.seek(0) + yield wav_buf.read() + + for i, chunk in enumerate(output): + file_chunks.append(chunk) + if isinstance(chunk, list): + chunk = torch.cat(chunk, dim=0) + chunk = chunk.clone().detach().cpu().numpy() + chunk = chunk[None, : int(chunk.shape[0])] + chunk = np.clip(chunk, -1, 1) + chunk = (chunk * 32767).astype(np.int16) + yield chunk.tobytes() + else: + # Non-streaming-specific operation + torchaudio.save(output_file, torch.tensor(output["wav"]).unsqueeze(0), 24000) + + # API LOCAL Methods elif params["tts_method_api_local"]: + # Streaming only allowed for XTTSv2 local + if streaming: + raise ValueError("Streaming is only supported in XTTSv2 local") + # Set the correct output path (different from the if statement) print(f"[{params['branding']}TTSGen] Using API Local") model.tts_to_file( @@ -495,8 +557,13 @@ async def generate_audio(text, voice, language, output_file): top_k=model.config.top_k, top_p=model.config.top_p, ) + # API TTS elif params["tts_method_api_tts"]: + # Streaming only allowed for XTTSv2 local + if streaming: + raise ValueError("Streaming is only supported in XTTSv2 local") + print(f"[{params['branding']}TTSGen] Using API TTS") model.tts_to_file( text=text, @@ -504,6 +571,7 @@ async def generate_audio(text, voice, language, output_file): speaker_wav=[f"{this_dir}/voices/{voice}"], language=language, ) + # Print Generation time and settings generate_end_time = time.time() # Record the end time to generate TTS generate_elapsed_time = generate_end_time - generate_start_time @@ -526,8 +594,11 @@ async def generate(request: Request): voice = data["voice"] language = data["language"] output_file = data["output_file"] + streaming = False # Generation logic - await generate_audio(text, voice, language, output_file) + response = await generate_audio(text, voice, language, output_file, streaming) + if streaming: + return StreamingResponse(response, media_type="audio/wav") return JSONResponse( content={"status": "generate-success", "data": {"audio_path": output_file}} ) @@ -637,14 +708,25 @@ async def update_settings( ################################## #### SETTINGS PAGE DEMO VOICE #### ################################## -# Submit demo post here + +@app.get("/tts-demo-request", response_class=StreamingResponse) +async def tts_demo_request_streaming(text: str, voice: str, language: str, output_file: str): + try: + output_file_path = this_dir / "outputs" / output_file + stream = await generate_audio(text, voice, language, output_file_path, streaming=True) + return StreamingResponse(stream, media_type="audio/wav") + except Exception as e: + print(f"An error occurred: {e}") + return JSONResponse(content={"error": "An error occurred"}, status_code=500) + @app.post("/tts-demo-request", response_class=JSONResponse) async def tts_demo_request(request: Request, text: str = Form(...), voice: str = Form(...), language: str = Form(...), output_file: str = Form(...)): try: output_file_path = this_dir / "outputs" / output_file - await generate_audio(text, voice, language, output_file_path) + await generate_audio(text, voice, language, output_file_path, streaming=False) return JSONResponse(content={"output_file_path": str(output_file)}, status_code=200) except Exception as e: + print(f"An error occurred: {e}") return JSONResponse(content={"error": "An error occurred"}, status_code=500) # Gives web access to the output files @@ -653,6 +735,22 @@ async def get_audio(filename: str): audio_path = this_dir / "outputs" / filename return FileResponse(audio_path) +@app.get("/audiocache/{filename}") +async def get_audio(filename: str): + audio_path = Path("outputs") / filename + if not audio_path.is_file(): + raise HTTPException(status_code=404, detail="File not found") + + response = FileResponse( + path=audio_path, + media_type='audio/wav', + filename=filename + ) + # Set caching headers + response.headers["Cache-Control"] = "public, max-age=604800" # Cache for one week + response.headers["ETag"] = str(audio_path.stat().st_mtime) # Use the file's last modified time as a simple ETag + + return response ######################### #### VOICES LIST API #### @@ -682,7 +780,7 @@ async def preview_voice(request: Request, voice: str = Form(...)): # Generate the audio output_file_path = this_dir / "outputs" / f"{output_file_name}.wav" - await generate_audio(text, voice, language, output_file_path) + await generate_audio(text, voice, language, output_file_path, streaming=False) # Generate the URL output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' @@ -766,6 +864,45 @@ class TTSGenerator: except ValidationError as e: return str(e) +def process_text(text): + # Normalize HTML encoded quotes + text = html.unescape(text) + # Replace ellipsis with a single dot + text = re.sub(r'\.{3,}', '.', text) + # Pattern to identify combined narrator and character speech + combined_pattern = r'(\*[^*"]+\*|"[^"*]+")' + # List to hold parts of speech along with their type + ordered_parts = [] + # Track the start of the next segment + start = 0 + # Find all matches + for match in re.finditer(combined_pattern, text): + # Add the text before the match, if any, as ambiguous + if start < match.start(): + ambiguous_text = text[start:match.start()].strip() + if ambiguous_text: + ordered_parts.append(('ambiguous', ambiguous_text)) + # Add the matched part as either narrator or character + matched_text = match.group(0) + if matched_text.startswith('*') and matched_text.endswith('*'): + ordered_parts.append(('narrator', matched_text.strip('*').strip())) + elif matched_text.startswith('"') and matched_text.endswith('"'): + ordered_parts.append(('character', matched_text.strip('"').strip())) + else: + # In case of mixed or improperly formatted parts + if '*' in matched_text: + ordered_parts.append(('narrator', matched_text.strip('*').strip('"'))) + else: + ordered_parts.append(('character', matched_text.strip('"').strip('*'))) + # Update the start of the next segment + start = match.end() + # Add any remaining text after the last match as ambiguous + if start < len(text): + ambiguous_text = text[start:].strip() + if ambiguous_text: + ordered_parts.append(('ambiguous', ambiguous_text)) + return ordered_parts + def standard_filtering(text_input): text_output = (text_input .replace("***", "") @@ -776,20 +913,6 @@ def standard_filtering(text_input): ) return text_output -def narrator_filtering(narrator_text_input): - processed_string = re.sub(r'\.\*\n\*', '. ', narrator_text_input) - processed_string = ( - processed_string - .replace("\n", " ") - .replace('"', '"<') - .replace('"', '"<') - ) - processed_string = processed_string.replace('"<. *', '"< *"') - processed_string = processed_string.replace('< *"', '< *') - processed_string = processed_string.replace('. *', '< *') - text_output = html.unescape(processed_string) - return text_output - def combine(output_file_timestamp, output_file_name, audio_files): audio = np.array([]) sample_rate = None @@ -810,9 +933,11 @@ def combine(output_file_timestamp, output_file_name, audio_files): timestamp = int(time.time()) output_file_path = os.path.join(this_dir / "outputs" / f'{output_file_name}_{timestamp}_combined.wav') output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_{timestamp}_combined.wav' + output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}_combined.wav' else: output_file_path = os.path.join(this_dir / "outputs" / f'{output_file_name}_combined.wav') output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' + output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}.wav' try: sf.write(output_file_path, audio, samplerate=sample_rate) # Clean up unnecessary files @@ -821,7 +946,7 @@ def combine(output_file_timestamp, output_file_name, audio_files): except Exception as e: # Handle exceptions (e.g., failed to write output file) return None, None - return output_file_path, output_file_url + return output_file_path, output_file_url, output_cache_url # Generation API (separate from text-generation-webui) @app.post("/api/tts-generate", response_class=JSONResponse) @@ -837,6 +962,7 @@ async def tts_generate( output_file_timestamp: bool = Form(...), autoplay: bool = Form(...), autoplay_volume: float = Form(...), + streaming: bool = Form(False), ): try: json_input_data = { @@ -851,6 +977,7 @@ async def tts_generate( "output_file_timestamp": output_file_timestamp, "autoplay": autoplay, "autoplay_volume": autoplay_volume, + "streaming": streaming, } JSONresult = TTSGenerator.validate_json_input(json_input_data) if JSONresult is None: @@ -858,982 +985,79 @@ async def tts_generate( else: return JSONResponse(content={"error": JSONresult}, status_code=400) if narrator_enabled: - #print("ORIGINAL UNTOUCHED STRING IS:", text_input,"\n") - if text_filtering in ["standard", "none"]: - cleaned_string = ( - text_input - .replace('"', '"<') - .replace('*', '<*') - ) - parts = re.split(r'(?<=<\*\s)|(?<=\.\s)|(?<=\."\<)|(?<=\."<)', cleaned_string) - parts = list(filter(lambda x: x.strip(), parts)) - elif text_filtering == "html": - cleaned_string = standard_filtering(text_input) - cleaned_string = narrator_filtering(cleaned_string) - parts = re.split(r'"|\.\*', cleaned_string) + processed_parts = process_text(text_input) audio_files_all_paragraphs = [] - audio_files_paragraph = [] - for i, part in enumerate(parts): - if len(part.strip()) <= 1: + for part_type, part in processed_parts: + # Skip parts that are too short + if len(part.strip()) <= 3: continue - # Figure out which type of line it is, then replace characters as necessary to avoid TTS trying to pronunce them, htmlunescape after. - # Character will always be a < with a letter immediately after it - if '<' in part and '<*' not in part and '< *' not in part and '< *' not in part and '< ' not in part and '< ' not in part: - cleaned_part = html.unescape(part.replace('<', '')) - voice_to_use = character_voice_gen - #Narrator will always be an * or < with an * a position or two after it. - elif '<*' in part or '< *' in part or '< *' in part or '*' in part: - cleaned_part = html.unescape(part.replace('<*', '').replace('< *', '').replace('< *', '').replace('*', '').replace('<. ', '')) + # Determine the voice to use based on the part type + if part_type == 'narrator': voice_to_use = narrator_voice_gen - #If the other two dont capture it, aka, the AI gave no * or " on the line, use non_quoted_text_is aka user interface, user can choose Char or Narrator - elif text_not_inside == "character": - cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) + print(f"[{params['branding']}TTSGen] \033[92mNarrator\033[0m") # Green + elif part_type == 'character': voice_to_use = character_voice_gen - elif text_not_inside == "narrator": - cleaned_part = html.unescape(part.replace('< ', '').replace('< ', '').replace('< ', '')) - voice_to_use = narrator_voice_gen - output_file = this_dir / "outputs" / f"{output_file_name}_{uuid.uuid4()}_{int(time.time())}_{i}.wav" + print(f"[{params['branding']}TTSGen] \033[36mCharacter\033[0m") # Yellow + else: + # Handle ambiguous parts based on user preference + voice_to_use = character_voice_gen if text_not_inside == "character" else narrator_voice_gen + voice_description = "\033[36mCharacter (Text-not-inside)\033[0m" if text_not_inside == "character" else "\033[92mNarrator (Text-not-inside)\033[0m" + print(f"[{params['branding']}TTSGen] {voice_description}") + # Replace multiple exclamation marks, question marks, or other punctuation with a single instance + cleaned_part = re.sub(r'([!?.])\1+', r'\1', part) + # Further clean to remove any other unwanted characters + cleaned_part = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_part) + # Remove all newline characters (single or multiple) + cleaned_part = re.sub(r'\n+', ' ', cleaned_part) + output_file = this_dir / "outputs" / f"{output_file_name}_{uuid.uuid4()}_{int(time.time())}.wav" output_file_str = output_file.as_posix() - await generate_audio(cleaned_part, voice_to_use, language, output_file_str) + response = await generate_audio(cleaned_part, voice_to_use, language, output_file_str, streaming) audio_path = output_file_str - audio_files_paragraph.append(audio_path) - # Accumulate audio files within the paragraph - audio_files_all_paragraphs.extend(audio_files_paragraph) + audio_files_all_paragraphs.append(audio_path) # Combine audio files across paragraphs - output_file_path, output_file_url = combine(output_file_timestamp, output_file_name, audio_files_all_paragraphs) + output_file_path, output_file_url, output_cache_url = combine(output_file_timestamp, output_file_name, audio_files_all_paragraphs) else: if output_file_timestamp: timestamp = int(time.time()) output_file_path = this_dir / "outputs" / f"{output_file_name}_{timestamp}.wav" output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}_{timestamp}.wav' + output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}.wav' else: output_file_path = this_dir / "outputs" / f"{output_file_name}.wav" output_file_url = f'http://{params["ip_address"]}:{params["port_number"]}/audio/{output_file_name}.wav' + output_cache_url = f'http://{params["ip_address"]}:{params["port_number"]}/audiocache/{output_file_name}_{timestamp}.wav' if text_filtering == "html": cleaned_string = html.unescape(standard_filtering(text_input)) + cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input) + # Further clean to remove any other unwanted characters + cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_string) + # Remove all newline characters (single or multiple) + cleaned_string = re.sub(r'\n+', ' ', cleaned_string) elif text_filtering == "standard": - cleaned_string = standard_filtering(text_input) + cleaned_string = re.sub(r'([!?.])\1+', r'\1', text_input) + # Further clean to remove any other unwanted characters + cleaned_string = re.sub(r'[^a-zA-Z0-9\s\.,;:!?\-\'"]', '', cleaned_string) + # Remove all newline characters (single or multiple) + cleaned_string = re.sub(r'\n+', ' ', cleaned_string) else: cleaned_string = text_input - await generate_audio(cleaned_string, character_voice_gen, language, output_file_path) - if sounddevice_installed == False: + response = await generate_audio(cleaned_string, character_voice_gen, language, output_file_path, streaming) + if sounddevice_installed == False or streaming == True: autoplay = False if autoplay: - play_audio(output_file_path, autoplay_volume) - return JSONResponse(content={"status": "generate-success", "output_file_path": str(output_file_path), "output_file_url": str(output_file_url)}, status_code=200) + play_audio(output_file_path, autoplay_volume) + if streaming: + return StreamingResponse(response, media_type="audio/wav") + return JSONResponse(content={"status": "generate-success", "output_file_path": str(output_file_path), "output_file_url": str(output_file_url), "output_cache_url": str(output_cache_url)}, status_code=200) except Exception as e: return JSONResponse(content={"status": "generate-failure", "error": "An error occurred"}, status_code=500) -############################################################# -#### DOCUMENTATION - README ETC - PRESENTED AS A WEBPAGE #### -############################################################# - -simple_webpage = """ - - - - - - - AllTalk TTS for Text generation webUI - - - - -

AllTalk TTS for Text generation webUI

- -

Table of Contents

- - -

Getting Started

-

AllTalk is a web interface, based around the Coqui TTS voice cloning/speech generation system. To generate TTS, you can use the provided gradio interface or interact with the server using JSON/CURL commands. 

-

Note: When loading up a new character in Text generation webUI it may look like nothing is happening for 20-30 seconds. Its actually processing the introduction section (greeting message) of the text and once that is completed, it will appear. You can see the activity occuring in the console window. Refreshing the page multiple times will try force the TTS engine to keep re-generating the text, so please just wait and check the console if needed.

-

Note: Ensure that your RP character card has asterisks around anything for the narration and double quotes around anything spoken. There is a complication ONLY with the greeting card so, ensuring it has the correct use of quotes and asterisks will help make sure that the greeting card sounds correct. I will aim to address this issue in a future update. In Text-generation-webUI parameters menu > character tab > greeting make sure that anything in there that is the narrator is in asterisks and anything spoken is in double quotes, then hit the save (💾) button.

-

AllTalk Minor Bug Fixes Changelog & Known issues

-

If I squash any minor bugs or find any issues, I will try to apply an update asap. If you think something isnt working correctly or you have a problem, check these two links below first.

- -

AllTalk
Github link here
Update instructions link here
Help and issues link here

Text generation webUI
Web interface link here
Documentation link here

-

Back to top of page

-

Server Information

- -

Back to top of page

- -

Demo/Test TTS

-
-
- - - - - - - - - - - - - - - {{ output_file_path }} - -
-
- - -

Back to top of page

- -

Using Voice Samples

-

Where are the sample voices stored?

-

Voice samples are stored in /alltalk_tts/voices/ and should be named using the following format name.wav

-

Where are the outputs stored & Automatic output wav file deletion.

-

Voice outputs are stored in /alltalk_tts/outputs/

-

You can configure automatic maintenence deletion of old wav files by setting Del WAV's older than in the settings above.

-

When Disabled your output wav files will be left untouched. When set to a setting 1 Day or greater, your output wav files older than that time period will be automatically deleted on start-up of AllTalk.

-

Where are the models stored?

-

This extension will download the 2.0.2 model to /alltalk_tts/models/

-

This TTS engine will also download the latest available model and store it wherever your OS normally stores it (Windows/Linux/Mac).

-

How do I create a new voice sample?

-

To create a new voice sample you need to make a wav file that is 22050Hz, Mono, 16 bit and between 6 to 30 seconds long, though 8 to 10 seconds is usually good enough. The model can handle up to a 30 second samples, however Ive not noticed any improvement in voice output from a much longer clips.

-

You want to find a nice clear selection of audio, so lets say you wanted to clone your favourite celebrity. You may go looking for an interview where they are talking. Pay close attention to the audio you are listening to and trying to sample. Are there noises in the backgroud, hiss on the soundtrack, a low humm, some quiet music playing or something? The better quality the audio the better the final TTS result. Dont forget, the AI that processes the sounds can hear everything in your sample and it will use them in the voice its trying to recreate.

-

Try make your clip one of nice flowing speech, like the included example files. No big pauses, gaps or other sounds. Preferably a sample that the person you are trying to copy will show a little vocal range and emotion in their voice. Also, try to avoid a clip starting or ending with breathy sounds (breathing in/out etc).

-

Editing your sample!

-

So youve downloaded your favoutie celebrity interview off Youtube, from here you need to chop it down to 6 to 30 seconds in length and resample it.

-

If you need to clean it up, do audio processing, volume level changes etc, do this before downsampling.

Using the latest version of Audacity select/highlight your 6 to 30 second clip and:

                  Tracks > Resample to 22050Hz then
                  Tracks > Mix > Stereo to Mono then
                  File > Export Audio saving it as a WAV of 22050Hz.

-

Save your generated wav file in the /alltalk_tts/voices/ folder.

-

Its worth mentioning that using AI generated audio clips may introduce unwanted sounds as its already a copy/simulation of a voice.

-

Why doesnt it sound like XXX Person?

-

Maybe you might be interested in trying Finetuning of the model. Otherwise, the reasons can be that you:

- -

Some samples just never seem to work correctly, so maybe try a different sample. Always remember though, this is an AI model attempting to re-create a voice, so you will never get a 100% match.

-

Back to top of page

- - -

Text Not inside

-

This only affects the Narrator function. Most AI models should be using asterisks or double quotes to differentiate between the Narrator or the Character, however, many models sometimes switch between using asterisks and double quotes or sometimes nothing at all for the text it outputs.

This leaves a bit of a mess because sometimes un-marked text is narration and sometimes its the character talking, leaving no clear way to know where to split sentences and what voice to use. Whilst there is no 100% solution at the moment many models lean more one way or the other as to what that unmarked text will be (character or narrator).

-

As such, the "Text not inside" function at least gives you the choice to set how you want the TTS engine to handle situations of un-marked text.

-
When the AI doesnt use an asterisk or a quote
-

Back to top of page

- - -

Low VRAM

-

The Low VRAM option is a crucial feature designed to enhance performance under constrained (VRAM) conditions, as the TTS models require 2GB-3GB of VRAM to run effectively. This feature strategically manages the relocation of the Text-to-Speech (TTS) model between your system's Random Access Memory (RAM) and VRAM, moving it between the two on the fly. Obviously, this is very useful for people who have smaller graphics cards and will use all their VRAM to load in their LLM.

-

When you dont have enough VRAM free after loading your LLM model into your VRAM (Normal Mode example below), you can see that with so little working space, your GPU will have to swap in and out bits of the TTS model, which causes horrible slowdown.

-

Note: An Nvidia Graphics card is required for the LowVRAM option to work, as you will just be using system RAM otherwise. 

-

How It Works:

-

The Low VRAM mode intelligently orchestrates the relocation of the entire TTS model and stores the TTS model in your system RAM. When the TTS engine requires VRAM for processing, the entire model seamlessly moves into VRAM, causing your LLM to unload/displace some layers, ensuring optimal performance of the TTS engine.

-

Post-TTS processing, the model moves back to system RAM, freeing up VRAM space for your Language Model (LLM) to load back in the missing layers. This adds about 1-2 seconds to both text generation by the LLM and the TTS engine.

-

By transferring the entire model between RAM and VRAM, the Low VRAM option avoids fragmentation, ensuring the TTS model remains cohesive and has all the working space it needs in your GPU, without having to just work on small bits of the TTS model at a time (which causes terrible slow down).

-

This creates a TTS generation performance Boost for Low VRAM Users and is particularly beneficial for users with less than 2GB of free VRAM after loading their LLM, delivering a substantial 5-10x improvement in TTS generation speed.

-
How Low VRAM Works
-

Back to top of page

- - -

Finetuning (Training the model)

- -

If you have a voice that the model doesnt quite reproduce correctly, or indeed you just want to improve the reproduced voice, then finetuning is a way to train your "XTTSv2 local" model (stored in /alltalk_tts/models/xxxxx/) on a specific voice. For this you will need:

- - - -

How will this work/How complicated is it?

- -

Everything has been done to make this as simple as possible. At its simplest, you can literally just download a large chunk of audio from an interview, and tell the finetuning to strip through it, find spoken parts and build your dataset. You can literally click 4 buttons, then copy a few files and you are done. At it's more complicated end you will clean up the audio a little beforehand, but its still only 4x buttons and copying a few files.

- -

The audio you will use:

- -

I would suggest that if its in an interview format, you cut out the interviewer speaking in audacity or your chosen audio editing package. You dont have to worry about being perfect with your cuts, the finetuning Step 1 will go and find spoken audio and cut it out for you. Is there is music over the spoken parts, for best quality you would cut out those parts, though its not 100% necessary. As always, try to avoid bad quality audio with noises in it (humming sounds, hiss etc). You can try something like Audioenhancer to try clean up noisier audio. There is no need to down-sample any of the audio, all of that is handled for you. Just give the finetuning some good quality audio to work with.

- -

Important requirements CUDA 11.8:

- -

As mentioned you must have a small portion of the Nvidia CUDA Toolkit 11.8 installed. Not higher or lower versions. Specifically 11.8. You do not have to uninstall any other versions, change any graphics drivers, reinstall torch or anything like that. There are instructions within the finetuning interface on doing this or you can also find them on this link here

- -

Starting Finetuning:

- -

Ensure you have followed the instructions on setting up the Nvidia CUDA Toolkit 11.8 here or the below procedure will fail.

- -

The below instructions are also available online here

- -
    -
  1. -

    Close all other applications that are using your GPU/VRAM and copy your audio samples into:
    -
    - /alltalk_tts/finetune/put-voice-samples-in-here/

    -
  2. -
  3. -

    In a command prompt/terminal window you need to move into your Text generation webUI folder:
    -
    - cd text-generation-webui

    -
  4. -
  5. -

    Start the Text generation webUI Python environment for your OS:
    -
    - cmd_windows.bat, ./cmd_linux.sh, cmd_macos.sh or cmd_wsl.bat

    -
  6. -
  7. -

    You can double check your search path environment still works correctly with nvcc --version. It should report back 11.8:
    -
    - Cuda compilation tools, release 11.8.

    -
  8. -
  9. -

    Move into your extensions folder:
    -
    - cd extensions

    -
  10. -
  11. -

    Move into the alltalk_tts folder:
    -
    - cd alltalk_tts

    -
  12. -
  13. -

    Install the finetune requirements file: pip install -r requirements_finetune.txt

    -
  14. -
  15. -

    Type python finetune.py and it should start up.

    -
  16. -
  17. -

    Follow the on-screen instructions when the web interface starts up.

    -
  18. -
  19. -

    When you have finished finetuning, the final tab will tell you what to do with your files and how to move your newly trained model to the correct location on disk.

    -
  20. -
- -

Back to top of page

- - -

DeepSpeed

-

DeepSpeed provides a 2x-3x speed boost for Text-to-Speech and AI tasks. It's all about making AI and TTS happen faster and more efficiently.

- -
DeepSpeed on vs off
-

DeepSpeed only works with the XTTSv2 Local model and will deactivate when other models are selected, even if the checkbox still shows as being selected.

-

Note: DeepSpeed/AllTalk may warn if the Nvidia Cuda Toolkit and CUDA_HOME environment variable isnt set correctly. On Linux you need CUDA_HOME configured correctly; on Windows, if you use the pre-built wheel its ok without.

-

Note: You do not need to set Text-generation-webUi's --deepspeed setting for AllTalk to be able to use DeepSpeed.

-

Back to top of page

- - -

DeepSpeed Setup - Linux

-

➡️DeepSpeed requires an Nvidia Graphics card!⬅️

-
    -
  1. Preferably use your built in package manager to install the CUDA toolkit. Alternatively download and install the Nvidia Cuda Toolkit for Linux Nvidia Cuda Toolkit 11.8 or 12.1
  2. -
  3. Open a terminal console.
  4. -
  5. Install libaio-dev (however your Linux version installs things) e.g. sudo apt install libaio-dev
  6. -
  7. Move into your Text generation webUI folder e.g. cd text-generation-webui
  8. -
  9. Start the Text generation webUI Python environment ./cmd_linux.sh
  10. -
  11. Text generation webUI overwrites the CUDA_HOME environment variable each time you ./cmd_linux.sh or ./start_linux.sh so you will need to either permanently change within the python environment OR set CUDA_HOME it each time you ./cmd_linux.sh. Details to change it each time are on the next step. Below is a link to Conda's manual and changing environment variables permanently though its possible changing it permanently could affect other extensions, you would have to test. Conda manual - Environment variables
  12. -
  13. You can temporarily set the CUDA_HOME environment with (Standard Ubuntu path below, but it could vary on other Linux flavours):

    export CUDA_HOME=/etc/alternatives/cuda every time you run ./cmd_linux.sh

    If you try to start DeepSpeed with the CUDA_HOME path set incorrectly, expect an error similar to:

             [Errno 2] No such file or directory: /home/yourname/text-generation-webui/installer_files/env/bin/nvcc

  14. -
  15. Now install deepspeed with pip install deepspeed
  16. -
  17. You can now start Text generation webUI python server.py ensuring to activate your extensions.

    Just to reiterate, starting Text-generation-webUI with ./start_linux.sh will overwrite the CUDA_HOME variable unless you have permanently changed it, hence always starting it with ./cmd_linux.sh then setting the environment variable manually export CUDA_HOME=/etc/alternatives/cuda and then python server.py which is how you would need to run it each time, unless you permanently set the environment variable for CUDA_HOME within Text-generation-webUI's standard Python environment.

    Removal - If it became necessary to uninstall DeepSpeed, you can do so with ./cmd_linux.sh and then pip uninstall deepspeed
  18. -
-

Back to top of page

- - -

DeepSpeed Setup - Windows

-

➡️DeepSpeed requires an Nvidia Graphics card!⬅️

-

DeepSpeed v11.2 will work on the current default text-generation-webui Python 3.11 environment! You have 2x options for how to setup DeepSpeed on Windows. A quick way Option 1 and a long way Option 2.

-

Thanks to @S95Sedan They managed to get DeepSpeed 11.2 working on Windows via making some edits to the original Microsoft DeepSpeed v11.2 installation. The original post is here.

-

OPTION 1 - Pre-Compiled Wheel Deepspeed v11.2 (Python 3.11 and 3.10)

-
    -
  1. Download the correct wheel version for your Python/Cuda from here and save the file it inside your text-generation-webui folder.
  2. -
  3. Open a command prompt window, move into your text-generation-webui folder you can now start the Python environment for text-generation-webui cmd_windows.bat
  4. -
  5. With the file that you saved in the text-generation-webui folder you now type the following, replacing your-version with the name of the file you have:

    pip install "deepspeed-0.11.2+your-version-win_amd64.whl"

  6. -
  7. This should install through cleanly and you should now have DeepSpeed v11.2 installed within the Python 3.11/3.10 environment of text-generation-webui.
  8. -
  9. When you start up text-generation-webui, and AllTalk starts, you should see:

                [AllTalk Startup] DeepSpeed Detected

  10. -
  11. Within AllTalk, you will now have a checkbox for Activate DeepSpeed though remember you can only change 1x setting every 15 or so seconds, so dont try to activate DeepSpeed and LowVRAM simultaneously. When you are happy it works, you can set the default start-up settings in the settings page.

    Removal - If it became necessary to uninstall DeepSpeed, you can do so with cmd_windows.bat and then pip uninstall deepspeed


    OPTION 2 - Manual build of DeepSpeed v11.2 (Python 3.11 and 3.10)

    Due to the complexity of this, and the complicated formatting, instructions can be found on this link
  12. -
-

Back to top of page

- - - -

TTS Models/Methods

-

It's worth noting that all models and methods can and do sound different from one another. Many people complained about the quality of audio produced by the 2.0.3 model, so this extension will download the 2.0.2 model to your models folder and give you the choice to use 2.0.2 (API Local and XTTSv2 Local) or use the most current model 2.0.3 (API TTS). As/When a new model is released by Coqui it will be downloaded by the TTS service on startup and stored wherever the TTS service keeps new models for your operating system.

- -

Back to top of page

- - -

Model Temperature and Repetition Settings

-

It is recommended not to modify these settings unless you fully comprehend their effects. A general overview is provided below for reference.

-

Changes to these settings won't take effect until you restart AllTalk/Text generation webUI.

-

These settings only affect API Local and XTTSv2 Local methods.

-

Repetition Penalty:

-

In the context of text-to-speech (TTS), the Repetition Penalty influences how the model handles the repetition of sounds, phonemes, or intonation patterns. Here's how it works:

- -

The factory setting for repetition penalty is 10.0

-

Temperature:

-

Temperature influences the randomness of the generated speech. Here's how it affects the output:

- -

The factory setting for temperature is 0.70

- - -

Temperature and Repetition Settings Examples:

- -

Factory settings should be fine for most people, however if you choose to experiment, setting extremely high or low values, especially without a good understanding of their effects, may lead to flat-sounding output or very strange-sounding output. It's advisable to experiment with adjustments incrementally and observe the impact on the generated speech to find a balance that suits your desired outcome.

-

Back to top of page

- - -

Start-up Checks

-

AllTalk performs a variety of checks on startup and will warn out messages at the console should you need to do something such as update your TTS version. 

-

A basic environment check to ensure everything should work e.g. is the model already downloaded, are the configuration files set correctly etc.

-

AllTalk will download the Xtts model (version 2.0.2) into your models folder. Many people didnt like the quality of the 2.0.3 model, however the latest model will be accessable on the API TTS setting (2.0.3 at the time of writing) so you have the best of both worlds.

-

Back to top of page

- -

Custom TTS Models and Model path

-

Its possible to set a custom model for the API Local and XTTSv2 Local methods, or indeed point it at the same model that API TTS uses (wherever it is stored on your OS of choice).

-

Many people did not like the sound quality of the Coqui 2.0.3 model, and as such the AllTalk downloads the 2.0.2 model seperately from the 2.0.3 model that TTS service downloads and manages.

-

Typically the 2.0.2 model is stored in your /alltalk_tts/models folder and it is downloaded on first start-up of the AllTalk_tts extension. However, you may either want to use a custom model version of your choosing, or re-point AllTalk to a different path on your system, or even point it so that API Local and XTTSv2 Local both use the same model that API TTS is using.

-

If you do choose to change the location there are a couple of things to note. 

- -

To change the model path, there are at minimum 2x settings you need to alter in the modeldownload.json file, base_path and model_path.

-

You would edit the settings in the modeldownload.json file as follows (make a backup of your current file in case):

        Windows path example: c:\\mystuff\\mydownloads\\myTTSmodel\\{files in here}
        base_path would be "c:\\mystuff\\mydownloads"
        model_path would be: "myTTSmodel"

-

Note: On Windows systems, you have to specify a double backslash \\ for each folder level in the path (as above)

-

        Linux path example: /home/myaccount/myTTSmodel/{files in here}
        base_path would be "/home/myaccount"
        model_path would be: "TTSmodel"

Once you restart Alltalk, it will check this path for the files and output any details at the console.

-

When you are happy it's' working correctly, you are welcome to go delete the models folder stored at /alltalk_tts/models.

-

If you wish to change the files that the modeldownloader is pulling at startup, you can futher edit the modeldownload.json and change the https addresses within this files files_to_download section  e.g.

-

"files_to_download": {
        "LICENSE.txt": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/LICENSE.txt?download=true",
        "README.md": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/README.md?download=true",
        "config.json": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/config.json?download=true",
        "model.pth": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/model.pth?download=true",
        "vocab.json": "https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/vocab.json?download=true"
 }

-

Back to top of page

- -

Configuration file settings

-

confignew.json file:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
KeyDefault ValueExplanation
"activate"trueSets activation state within Text-generation-webUI.
"autoplay"trueSets autoplay within Text generation webUI.
"branding""AllTalk"Used to change the default name. Requires a space e.g. "Mybrand ".
"deepspeed_activate"falseSets DeepSpeed activation on startup.
"delete_output_wavs""Disabled"Sets duration of outputs to delete.
"ip_address""127.0.0.1"Sets default IP address.
"language""English"Sets default language for Text-generation-webUI TTS.
"low_vram"falseSets default setting for LowVRAM mode.
"local_temperature""0.70"Sets default model temp for API Local and XTTSv2 Local.
"local_repetition_penalty""10.0"Sets default model repetition for API Local and XTTSv2 Local.
"tts_model_loaded"trueAllTalk internal use only. Do not change.
"tts_model_name""tts_models/multilingual/multi-dataset/xtts_v2"Sets default model that API TTS is looking for through the TTS service (separate to API Local and XTTSv2 Local).
"narrator_enabled"trueSets default narrator on/off in Text-generation-webUI TTS.
"narrator_voice""female_02.wav"Sets default wav to use for narrator in Text-generation-webUI TTS.
"port_number""7851"Sets default port number for AllTalk.
"output_folder_wav""extensions/alltalk_tts/outputs/"Sets default output path Text-generation-webUI should use for finding outputs.
"output_folder_wav_standalone""outputs/"Sets default output path in standalone mode.
"remove_trailing_dots"falseSets trailing dot removal pre-generating TTS.
"show_text"trueSets if text should be displayed below audio in Text-generation-webUI.
"tts_method_api_local"falseSets API Local as the default model/method for TTS.
"tts_method_api_tts"falseSets API TTS as the default model/method for TTS.
"tts_method_xtts_local"trueSets XTTSv2 Local as the default model/method for TTS.
"voice""female_01.wav"Sets default voice for TTS.
- -

modeldownload.json file:

- - - - - - - - - - - - - - - - - - - - - -
KeyValueDescription
"base_path""models"Sets local model base path for API Local and XTTSv2 Local.
"model_path""xttsv2_2.0.2"Sets local model folder for API Local and XTTSv2 Local below the base path.
"files_to_download" - - - - - - - - - - - - - - - - - - - - - - - - - -
FileDownload URL
"LICENSE.txt"https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/LICENSE.txt?download=true
"README.md"https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/README.md?download=true
"config.json"https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/config.json?download=true
"model.pth"https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/model.pth?download=true
"vocab.json"https://huggingface.co/coqui/XTTS-v2/resolve/v2.0.2/vocab.json?download=true
-
Sets the model files required to be downloaded into \base_path\model_path\ and where to download them from.
- -

JSON calls & CURL Commands

- -

Overview

-

The Text-to-Speech (TTS) Generation API allows you to generate speech from text input using various configuration options. This API supports both character and narrator voices, providing flexibility for creating dynamic and engaging audio content.

-

TTS Generation Endpoint

- -

Example command line

-

Standard TTS speech Example (standard text) generating a time-stamped file

-

curl -X POST "http://127.0.0.1:7851/api/tts-generate" -d "text_input=All of this is text spoken by the character. This is text not inside quotes, though that doesnt matter in the slightest" -d "text_filtering=standard" -d "character_voice_gen=female_01.wav" -d "narrator_enabled=false" -d "narrator_voice_gen=male_01.wav" -d "text_not_inside=character" -d "language=en" -d "output_file_name=myoutputfile" -d "output_file_timestamp=true" -d "autoplay=true" -d "autoplay_volume=0.8"

-

Narrator Example (standard text) generating a time-stamped file

-

curl -X POST "http://127.0.0.1:7851/api/tts-generate" -d "text_input=*This is text spoken by the narrator* \"This is text spoken by the character\". This is text not inside quotes." -d "text_filtering=standard" -d "character_voice_gen=female_01.wav" -d "narrator_enabled=true" -d "narrator_voice_gen=male_01.wav" -d "text_not_inside=character" -d "language=en" -d "output_file_name=myoutputfile" -d "output_file_timestamp=true" -d "autoplay=true" -d "autoplay_volume=0.8"

-

Note that if your text that needs to be generated contains double quotes you will need to escape them with \" (Please see the narrator example).

-

 Request Parameters

- -

TTS Generation Response

-

The API returns a JSON object with the following properties:

- -

Example JSON TTS Generation Response:

-

{"status": "generate-success", "output_file_path": "C:\\text-generation-webui\\extensions\\alltalk_tts\\outputs\\myoutputfile_1703149973.wav", "output_file_url": "http://127.0.0.1:7851/audio/myoutputfile_1703149973.wav"}

- - -

Switching Model

-

curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=API%20Local"
curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=API%20TTS"
curl -X POST "http://127.0.0.1:7851/api/reload?tts_method=XTTSv2%20Local"

-

Switch between the 3 models respectively.

-

JSON return {"status": "model-success"}

-

Switch DeepSpeed

-

curl -X POST "http://127.0.0.1:7851/api/deepspeed?new_deepspeed_value=True"

-

Replace True with False to disable DeepSpeed mode.

-

JSON return {"status": "deepspeed-success"}

-

Switching Low VRAM

-

curl -X POST "http://127.0.0.1:7851/api/lowvramsetting?new_low_vram_value=True"

-

Replace True with False to disable Low VRAM mode.

-

JSON return {"status": "lowvram-success"}

-

Ready Endpoint

-

Check if the Text-to-Speech (TTS) service is ready to accept requests.

- -

curl -X GET "http://127.0.0.1:7851/api/ready"

-

Voices List Endpoint

-

Retrieve a list of available voices for generating speech.

- -

curl -X GET "http://127.0.0.1:7851/api/voices"

-

JSON return: {"voices": ["voice1.wav", "voice2.wav", "voice3.wav"]}

-

Preview Voice Endpoint

-

Generate a preview of a specified voice with hardcoded settings.

- -

curl -X POST "http://127.0.0.1:7851/api/previewvoice/" -F "voice=female_01.wav"

-

Replace female_01.wav with the name of the voice sample you want to hear.

-

JSON return: {"status": "generate-success", "output_file_path": "/path/to/outputs/api_preview_voice.wav", "output_file_url": "http://127.0.0.1:7851/audio/api_preview_voice.wav"}

- -

Back to top of page

- -

Debugging and TTS Generation Information

-

Command line outputs are more verbose to assist in understanding backend processes and debugging.

-

Its possible during startup you can get a warning message such as:

            [AllTalk Startup] Warning TTS Subprocess has NOT started up yet, Will keep trying for 80 seconds maximum

This is normal behavior if the subprocess is taking a while to start, however, if there is an issue starting the subprocess, you may see multiples of this message and an it will time out after 80 seconds, resulting in the TTS engine not starting. Its likely that you are not in the correct python environment or one that has a TTS engine inside, if this happens, though the system will output a warning about that ahead of this message

-

Typically the command line console will output any warning or error messages. If you need to reset your default configuation, the settings are all listed above in the configuration details.

-

Back to top of page

-

Thanks & References

-

Coqui TTS Engine

- -

Extension coded by

- -

Thanks to & Text generation webUI

- -

Thanks to

- -

Back to top of page

- - - - -""" - ################################################### #### Webserver Startup & Initial model Loading #### ################################################### -# Create a Jinja2 template object -template = Template(simple_webpage) +# Get the admin interface template +template = templates.get_template("admin.html") # Render the template with the dynamic values rendered_html = template.render(params=params)