├── .gitignore ├── examples ├── example_leo.wav └── example_tara.wav ├── requirements.txt ├── example.py ├── README.md ├── decoder.py ├── LICENSE └── gguf_orpheus.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | outputs/ 3 | venv/ 4 | .DS_Store -------------------------------------------------------------------------------- /examples/example_leo.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlgorithmicKing737/orpheus-tts-local-openai/HEAD/examples/example_leo.wav -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch>=2.0.0 2 | numpy>=1.20.0 3 | sounddevice>=0.4.4 4 | requests>=2.25.0 5 | wave>=0.0.2 6 | snac>=1.2.1 7 | -------------------------------------------------------------------------------- /examples/example_tara.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlgorithmicKing737/orpheus-tts-local-openai/HEAD/examples/example_tara.wav -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Simple example of using Orpheus TTS as a library. 4 | This script demonstrates how to generate speech and save it to a file. 5 | """ 6 | 7 | from gguf_orpheus import generate_speech_from_api, AVAILABLE_VOICES 8 | 9 | def text_to_speech(text, voice="tara", output_file=None): 10 | """ 11 | Convert text to speech using Orpheus TTS. 12 | 13 | Args: 14 | text (str): The text to convert to speech 15 | voice (str): The voice to use (default: tara) 16 | output_file (str): Path to save the audio file (default: None) 17 | 18 | Returns: 19 | list: Audio segments 20 | """ 21 | print(f"Converting: '{text}' with voice '{voice}'") 22 | 23 | # Generate speech 24 | audio_segments = generate_speech_from_api( 25 | prompt=text, 26 | voice=voice, 27 | output_file=output_file 28 | ) 29 | 30 | return audio_segments 31 | 32 | def main(): 33 | # Example 1: Generate speech with Tara voice 34 | text_to_speech( 35 | "Hello, I'm Tara. This is an example of using Orpheus TTS as a library.", 36 | voice="tara", 37 | output_file="example_tara.wav" 38 | ) 39 | 40 | # Example 2: Generate speech with a different voice 41 | text_to_speech( 42 | "Hi there, I'm Leo. I have a different voice than Tara.", 43 | voice="leo", 44 | output_file="example_leo.wav" 45 | ) 46 | 47 | print("All available voices:") 48 | for voice in AVAILABLE_VOICES: 49 | print(f"- {voice}") 50 | 51 | if __name__ == "__main__": 52 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Orpheus-TTS-Local (OpenAI API Edition) 2 | ## All the credit goes to [isaiahbjork](https://github.com/isaiahbjork/orpheus-tts-local) I only modified the gguf_orpheus.py with Gemini 2.0 Flash 01-21 3 | 4 | A lightweight client for running [Orpheus TTS](https://huggingface.co/canopylabs/orpheus-3b-0.1-ft) locally using LM Studio API. 5 | 6 | ## Features 7 | 8 | - 🎧 High-quality Text-to-Speech using the Orpheus TTS model 9 | - 💻 Completely local - no cloud API keys needed 10 | - 🔊 Multiple voice options (tara, leah, jess, leo, dan, mia, zac, zoe) 11 | - 💾 Save audio to WAV files 12 | 13 | ## Quick Setup 14 | 15 | 1. Install [LM Studio](https://lmstudio.ai/) 16 | 2. Download the [Orpheus TTS model (orpheus-3b-0.1-ft-q4_k_m.gguf)](https://huggingface.co/isaiahbjork/orpheus-3b-0.1-ft-Q4_K_M-GGUF) in LM Studio 17 | 3. Load the Orpheus model in LM Studio 18 | 4. Start the local server in LM Studio (default: http://127.0.0.1:1234) 19 | 5. Clone this repo ```git clone https://github.com/AlgorithmicKing/orpheus-tts-local-openai.git``` 20 | 6. Install dependencies: 21 | ``` 22 | python3 -m venv venv 23 | source venv/bin/activate 24 | pip install -r requirements.txt 25 | ``` 26 | 7. Run the script: 27 | ``` 28 | python gguf_orpheus.py 29 | ``` 30 | 31 | ### TTS Settings in OpenWebUI 32 | 33 | - Text-to-Speech Engine: OpenAI. 34 | - URL: http://localhost:5000/v1. 35 | - API: not-needed. 36 | - TTS Voice: Any from the "Available Voices" section. 37 | - TTS Model: not-needed. 38 | 39 | ### Options 40 | 41 | - `--list-voices`: List available TTS voices and exit. This will print the list of available voices to the console and then stop the server from starting. 42 | - `--host`: The host address to bind the API server to. (default: `0.0.0.0` - meaning it will listen on all available network interfaces, making it accessible from other machines on your network). 43 | - `--port`: The port number to run the API server on. (default: `5000`). 44 | - `--debug`: Run the Flask API server in debug mode. Useful for development and seeing detailed error messages, but not recommended for production. 45 | 46 | ## Available Voices 47 | 48 | - tara - Best overall voice for general use (default) 49 | - leah 50 | - jess 51 | - leo 52 | - dan 53 | - mia 54 | - zac 55 | - zoe 56 | 57 | ## Emotion 58 | You can add emotion to the speech by adding the following tags: 59 | ```xml 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | ``` 70 | 71 | ## License 72 | 73 | Apache 2.0 74 | 75 | -------------------------------------------------------------------------------- /decoder.py: -------------------------------------------------------------------------------- 1 | from snac import SNAC 2 | import numpy as np 3 | import torch 4 | import asyncio 5 | import threading 6 | import queue 7 | 8 | 9 | model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz").eval() 10 | 11 | # Check if CUDA is available and set device accordingly 12 | snac_device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu" 13 | print(f"Using device: {snac_device}") 14 | model = model.to(snac_device) 15 | 16 | 17 | def convert_to_audio(multiframe, count): 18 | frames = [] 19 | if len(multiframe) < 7: 20 | return 21 | 22 | codes_0 = torch.tensor([], device=snac_device, dtype=torch.int32) 23 | codes_1 = torch.tensor([], device=snac_device, dtype=torch.int32) 24 | codes_2 = torch.tensor([], device=snac_device, dtype=torch.int32) 25 | 26 | num_frames = len(multiframe) // 7 27 | frame = multiframe[:num_frames*7] 28 | 29 | for j in range(num_frames): 30 | i = 7*j 31 | if codes_0.shape[0] == 0: 32 | codes_0 = torch.tensor([frame[i]], device=snac_device, dtype=torch.int32) 33 | else: 34 | codes_0 = torch.cat([codes_0, torch.tensor([frame[i]], device=snac_device, dtype=torch.int32)]) 35 | 36 | if codes_1.shape[0] == 0: 37 | 38 | codes_1 = torch.tensor([frame[i+1]], device=snac_device, dtype=torch.int32) 39 | codes_1 = torch.cat([codes_1, torch.tensor([frame[i+4]], device=snac_device, dtype=torch.int32)]) 40 | else: 41 | codes_1 = torch.cat([codes_1, torch.tensor([frame[i+1]], device=snac_device, dtype=torch.int32)]) 42 | codes_1 = torch.cat([codes_1, torch.tensor([frame[i+4]], device=snac_device, dtype=torch.int32)]) 43 | 44 | if codes_2.shape[0] == 0: 45 | codes_2 = torch.tensor([frame[i+2]], device=snac_device, dtype=torch.int32) 46 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+3]], device=snac_device, dtype=torch.int32)]) 47 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+5]], device=snac_device, dtype=torch.int32)]) 48 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+6]], device=snac_device, dtype=torch.int32)]) 49 | else: 50 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+2]], device=snac_device, dtype=torch.int32)]) 51 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+3]], device=snac_device, dtype=torch.int32)]) 52 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+5]], device=snac_device, dtype=torch.int32)]) 53 | codes_2 = torch.cat([codes_2, torch.tensor([frame[i+6]], device=snac_device, dtype=torch.int32)]) 54 | 55 | codes = [codes_0.unsqueeze(0), codes_1.unsqueeze(0), codes_2.unsqueeze(0)] 56 | # check that all tokens are between 0 and 4096 otherwise return * 57 | if torch.any(codes[0] < 0) or torch.any(codes[0] > 4096) or torch.any(codes[1] < 0) or torch.any(codes[1] > 4096) or torch.any(codes[2] < 0) or torch.any(codes[2] > 4096): 58 | return 59 | 60 | with torch.inference_mode(): 61 | audio_hat = model.decode(codes) 62 | 63 | audio_slice = audio_hat[:, :, 2048:4096] 64 | detached_audio = audio_slice.detach().cpu() 65 | audio_np = detached_audio.numpy() 66 | audio_int16 = (audio_np * 32767).astype(np.int16) 67 | audio_bytes = audio_int16.tobytes() 68 | return audio_bytes 69 | 70 | def turn_token_into_id(token_string, index): 71 | # Strip whitespace 72 | token_string = token_string.strip() 73 | 74 | # Find the last token in the string 75 | last_token_start = token_string.rfind(""): 86 | try: 87 | number_str = last_token[14:-1] 88 | return int(number_str) - 10 - ((index % 7) * 4096) 89 | except ValueError: 90 | return None 91 | else: 92 | return None 93 | 94 | 95 | async def tokens_decoder(token_gen): 96 | buffer = [] 97 | count = 0 98 | async for token_sim in token_gen: 99 | token = turn_token_into_id(token_sim, count) 100 | if token is None: 101 | pass 102 | else: 103 | if token > 0: 104 | buffer.append(token) 105 | count += 1 106 | 107 | if count % 7 == 0 and count > 27: 108 | buffer_to_proc = buffer[-28:] 109 | audio_samples = convert_to_audio(buffer_to_proc, count) 110 | if audio_samples is not None: 111 | yield audio_samples 112 | 113 | 114 | # ------------------ Synchronous Tokens Decoder Wrapper ------------------ # 115 | def tokens_decoder_sync(syn_token_gen): 116 | 117 | audio_queue = queue.Queue() 118 | 119 | # Convert the synchronous token generator into an async generator. 120 | async def async_token_gen(): 121 | for token in syn_token_gen: 122 | yield token 123 | 124 | async def async_producer(): 125 | # tokens_decoder.tokens_decoder is assumed to be an async generator that processes tokens. 126 | async for audio_chunk in tokens_decoder(async_token_gen()): 127 | audio_queue.put(audio_chunk) 128 | audio_queue.put(None) # Sentinel 129 | 130 | def run_async(): 131 | asyncio.run(async_producer()) 132 | 133 | thread = threading.Thread(target=run_async) 134 | thread.start() 135 | 136 | while True: 137 | audio = audio_queue.get() 138 | if audio is None: 139 | break 140 | yield audio 141 | 142 | thread.join() -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /gguf_orpheus.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import requests 4 | import json 5 | import time 6 | import wave 7 | import numpy as np 8 | import sounddevice as sd 9 | import argparse 10 | import threading 11 | import queue 12 | import asyncio 13 | from flask import Flask, request, jsonify, stream_with_context, Response 14 | import re # Import the regular expression module 15 | 16 | # LM Studio API settings (These will now be configurable via arguments, defaults are kept) 17 | DEFAULT_API_URL_PREFIX = "http://127.0.0.1:1234" 18 | API_COMPLETIONS_ENDPOINT = "/v1/completions" 19 | HEADERS = { 20 | "Content-Type": "application/json" 21 | } 22 | 23 | # Model parameters (Keep these as they are, but model name will be configurable) 24 | DEFAULT_MODEL_NAME = "orpheus-3b-0.1-ft-q4_k_m" 25 | MAX_TOKENS = 1200 26 | TEMPERATURE = 0.6 27 | TOP_P = 0.9 28 | REPETITION_PENALTY = 1.1 29 | SAMPLE_RATE = 24000 # SNAC model uses 24kHz 30 | 31 | # Available voices (Keep these as they are) 32 | AVAILABLE_VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"] 33 | DEFAULT_VOICE = "tara" # Best voice according to documentation 34 | 35 | # Special token IDs (Keep these as they are) 36 | START_TOKEN_ID = 128259 37 | END_TOKEN_IDS = [128009, 128260, 128261, 128257] 38 | CUSTOM_TOKEN_PREFIX = " 0: 97 | token_text = data['choices'][0].get('text', '') 98 | token_counter += 1 99 | if token_text: 100 | yield token_text 101 | except json.JSONDecodeError as e: 102 | print(f"Error decoding JSON: {e}") 103 | continue 104 | 105 | print("Token generation complete") 106 | 107 | def turn_token_into_id(token_string, index): 108 | """Convert token string to numeric ID for audio processing.""" 109 | # Strip whitespace 110 | token_string = token_string.strip() 111 | 112 | # Find the last token in the string 113 | last_token_start = token_string.rfind(CUSTOM_TOKEN_PREFIX) 114 | 115 | if last_token_start == -1: 116 | return None 117 | 118 | # Extract the last token 119 | last_token = token_string[last_token_start:] 120 | 121 | # Process the last token 122 | if last_token.startswith(CUSTOM_TOKEN_PREFIX) and last_token.endswith(">"): 123 | try: 124 | number_str = last_token[14:-1] 125 | token_id = int(number_str) - 10 - ((index % 7) * 4096) 126 | return token_id 127 | except ValueError: 128 | return None 129 | else: 130 | return None 131 | 132 | def convert_to_audio(multiframe, count): 133 | """Convert token frames to audio.""" 134 | from decoder import convert_to_audio as orpheus_convert_to_audio # keep import here 135 | return orpheus_convert_to_audio(multiframe, count) 136 | 137 | 138 | def tokens_decoder_sync_generator(syn_token_gen): 139 | """Synchronous token decoder that converts token stream to audio byte stream. 140 | Modified to yield ALL audio bytes as ONE single chunk at the end, instead of streaming segments. 141 | """ 142 | audio_segments = [] # To collect all audio segments for saving to file 143 | buffer = [] 144 | count = 0 145 | for token_text in syn_token_gen: 146 | token = turn_token_into_id(token_text, count) 147 | if token is not None and token > 0: 148 | buffer.append(token) 149 | count += 1 150 | 151 | # Convert to audio when we have enough tokens 152 | if count % 7 == 0 and count > 27: 153 | buffer_to_proc = buffer[-28:] 154 | audio_samples = convert_to_audio(buffer_to_proc, count) 155 | if audio_samples is not None: 156 | audio_segments.append(audio_samples) # Append segment for file saving 157 | 158 | # After generator finishes, yield ALL audio bytes as ONE single chunk 159 | print("Tokens decoded, yielding ALL audio bytes as single chunk.") # Added log 160 | yield b''.join(audio_segments) # Yield all segments joined together at the end 161 | 162 | 163 | def generate_speech_from_api_generator(prompt, api_url_prefix, model_name, voice=DEFAULT_VOICE, temperature=TEMPERATURE, 164 | top_p=TOP_P, max_tokens=MAX_TOKENS, repetition_penalty=REPETITION_PENALTY): 165 | """Generate speech from text using Orpheus model via LM Studio API and return audio byte stream generator.""" 166 | token_generator = generate_tokens_from_api( 167 | prompt=prompt, 168 | api_url_prefix=api_url_prefix, # Pass API URL prefix 169 | model_name=model_name, # Pass model name 170 | voice=voice, 171 | temperature=temperature, 172 | top_p=top_p, 173 | max_tokens=max_tokens, 174 | repetition_penalty=repetition_penalty 175 | ) 176 | return tokens_decoder_sync_generator(token_generator) 177 | 178 | 179 | @app.route('/v1/audio/speech', methods=['POST']) # Explicitly define the endpoint as '/v1/audio/speech' 180 | def speech_endpoint(): 181 | """ 182 | Endpoint for speech generation, matching OpenWebUI's expected URL: 183 | /v1/audio/speech 184 | Expects text in the 'input' field of the JSON request (OpenWebUI format). 185 | Modified to: 1) Save audio to disk FIRST. 2) Then send the SAVED file as response. 186 | """ 187 | print("Request received at /v1/audio/speech") # Log request arrival 188 | try: 189 | content_type = request.headers.get('Content-Type') 190 | print(f"Content-Type: {content_type}") # Log Content-Type 191 | if content_type != 'application/json': 192 | print(f"Error: Expected application/json, but got: {content_type}") 193 | return jsonify({"error": "Expected Content-Type: application/json"}), 400 194 | 195 | data = request.get_json() 196 | print(f"Received JSON data: {data}") # Log received JSON data 197 | 198 | text_input = data.get('input') # Try to get text from 'input' field (OpenWebUI) 199 | if not text_input: 200 | text_input = data.get('text') # Fallback to 'text' field (if you might use it elsewhere) 201 | 202 | if not text_input: 203 | print("Error: Missing 'input' or 'text' in request body") # Log missing text error 204 | return jsonify({"error": "Missing 'input' or 'text' in request body"}), 400 205 | 206 | # --- Remove extra spaces from input text --- 207 | text_input = text_input.strip() # Remove leading/trailing spaces 208 | text_input = " ".join(text_input.split()) # Normalize internal spaces (optional, but good practice) 209 | 210 | print(f"Extracted text from input: {text_input}") # Log extracted text 211 | 212 | voice = data.get('voice', DEFAULT_VOICE) # Get voice from request, default to DEFAULT_VOICE 213 | temperature = data.get('temperature', TEMPERATURE) 214 | top_p = data.get('top_p', TOP_P) 215 | repetition_penalty = data.get('repetition_penalty', REPETITION_PENALTY) 216 | max_tokens = data.get('max_tokens', MAX_TOKENS) 217 | 218 | # --- Get API URL prefix and model name from app config, fallback to defaults if not set --- 219 | api_url_prefix = app.config.get('API_URL_PREFIX', DEFAULT_API_URL_PREFIX) 220 | model_name = app.config.get('MODEL_NAME', DEFAULT_MODEL_NAME) 221 | 222 | # --- Filename and Output Folder Logic --- 223 | output_folder = "output" 224 | os.makedirs(output_folder, exist_ok=True) # Create 'output' folder if it doesn't exist 225 | 226 | # Get first two words for filename 227 | first_two_words = " ".join(text_input.strip().split()[:2]) 228 | safe_filename = re.sub(r'[^a-zA-Z0-9_]', '_', first_two_words) # Sanitize filename 229 | timestamp = time.strftime("%Y%m%d_%H%M%S") 230 | output_file_path = os.path.join(output_folder, f"{safe_filename}_{timestamp}.wav") 231 | print(f"Saving audio to: {output_file_path}") # Log saving path 232 | 233 | def generate(): # Modified generate function - now just saves to file and returns filepath 234 | all_audio_bytes = b'' # To accumulate all audio bytes 235 | audio_generator = generate_speech_from_api_generator( 236 | prompt=text_input, # Use the extracted text_input here 237 | api_url_prefix=api_url_prefix, # Use configured API URL prefix 238 | model_name=model_name, # Use configured model name 239 | voice=voice, 240 | temperature=temperature, 241 | top_p=top_p, 242 | repetition_penalty=repetition_penalty, 243 | max_tokens=max_tokens 244 | ) 245 | for audio_chunk in audio_generator: # Expecting only ONE chunk now from tokens_decoder_sync_generator 246 | if isinstance(audio_chunk, bytes): 247 | all_audio_bytes += audio_chunk # Accumulate 248 | else: 249 | print(f"Warning: Unexpected type from audio_generator: {type(audio_chunk)}") 250 | 251 | print("Generate function finished, SAVING audio to file.") # Log saving 252 | 253 | # --- Save WAV file --- 254 | if all_audio_bytes: # Only save if there's audio data 255 | with wave.open(output_file_path, "wb") as wf: 256 | wf.setnchannels(1) 257 | wf.setsampwidth(2) # Assuming 16-bit PCM 258 | wf.setframerate(SAMPLE_RATE) 259 | wf.writeframes(all_audio_bytes) 260 | print(f"Audio saved to: {output_file_path}") 261 | else: 262 | print("No audio data generated, skipping file save.") 263 | return None # Indicate no file path to send 264 | 265 | return output_file_path # Return the filepath of the saved file 266 | 267 | 268 | # --- Generate and get output filepath --- 269 | saved_file_path = generate() # Now generate() returns filepath 270 | 271 | if saved_file_path: # Check if filepath was returned (meaning audio was generated and saved) 272 | print(f"Reading saved audio file: {saved_file_path} for response.") # Log file reading 273 | with open(saved_file_path, 'rb') as audio_file: # Open in binary read mode 274 | audio_response_data = audio_file.read() # Read all file content into bytes 275 | print("Sending saved audio file content as response.") # Log response sending 276 | return Response(audio_response_data, mimetype='audio/wav') # Send file content as response 277 | else: 278 | return jsonify({"error": "Audio generation failed, no audio file saved."}), 500 # Error if no file 279 | 280 | 281 | except Exception as e: 282 | error_message = f"Exception in speech_endpoint: {e}" 283 | print(error_message) # Log any exceptions 284 | return jsonify({"error": error_message}), 500 # Return 500 for internal server error 285 | 286 | 287 | @app.route('/v1/audio/voices', methods=['GET']) # Changed to /v1/audio/voices 288 | def voices_endpoint(): 289 | """Returns a list of available voices for /v1/audio/voices endpoint""" 290 | available_voices_list = [{"name": voice, "id": voice} for voice in AVAILABLE_VOICES] #openai style voices list 291 | print(f"Serving voices list: {available_voices_list} at /v1/audio/voices") # Log voice list serving 292 | return jsonify({"data": available_voices_list}) 293 | 294 | @app.route('/', methods=['GET']) 295 | def root(): 296 | return jsonify({"message": "Orpheus TTS API is running"}) 297 | 298 | 299 | def list_available_voices(): # Keep this function for command line utility 300 | """List all available voices with the recommended one marked.""" 301 | print("Available voices (in order of conversational realism):") 302 | for i, voice in enumerate(AVAILABLE_VOICES): 303 | marker = "★" if voice == DEFAULT_VOICE else " " 304 | print(f"{marker} {voice}") 305 | print(f"\nDefault voice: {DEFAULT_VOICE}") 306 | 307 | print("\nAvailable emotion tags:") 308 | print(", , , , , , , ") 309 | 310 | 311 | def main(): 312 | parser = argparse.ArgumentParser(description="Orpheus Text-to-Speech API Server") 313 | parser.add_argument("--list-voices", action="store_true", help="List available voices and exit") 314 | parser.add_argument("--host", type=str, default="0.0.0.0", help="Host for the API server") 315 | parser.add_argument("--port", type=int, default=5000, help="Port for the API server") 316 | parser.add_argument("--debug", action="store_true", help="Run Flask in debug mode") 317 | parser.add_argument("--api-url-prefix", type=str, default=DEFAULT_API_URL_PREFIX, help=f"API URL prefix (e.g., http://your-lm-studio-host:port), default: {DEFAULT_API_URL_PREFIX}") 318 | parser.add_argument("--model", type=str, default=DEFAULT_MODEL_NAME, help=f"Model name for API payload, default: {DEFAULT_MODEL_NAME}") 319 | 320 | 321 | args = parser.parse_args() 322 | 323 | if args.list_voices: 324 | list_available_voices() 325 | return 326 | 327 | # Configure Flask app with API URL prefix and model name from arguments 328 | app.config['API_URL_PREFIX'] = args.api_url_prefix 329 | app.config['MODEL_NAME'] = args.model 330 | 331 | print("Starting Orpheus TTS API Server...") 332 | print(f"API URL Prefix: {app.config['API_URL_PREFIX']}") 333 | print(f"Model Name: {app.config['MODEL_NAME']}") 334 | print(f"Listening on http://{args.host}:{args.port}") 335 | app.run(host=args.host, port=args.port, debug=args.debug, threaded=False, processes=1) # important threaded=False and processes=1 for LM Studio 336 | 337 | 338 | if __name__ == "__main__": 339 | main() 340 | --------------------------------------------------------------------------------