Update handler.py
Browse files- handler.py +161 -69
handler.py
CHANGED
|
@@ -1,107 +1,199 @@
|
|
| 1 |
import torch
|
| 2 |
-
|
| 3 |
import soundfile as sf
|
| 4 |
import io
|
| 5 |
-
import numpy as np
|
| 6 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
class EndpointHandler():
|
| 9 |
def __init__(self, path=""):
|
| 10 |
"""
|
| 11 |
-
Initializes the handler. Loads
|
| 12 |
-
'path'
|
| 13 |
"""
|
| 14 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 15 |
print(f"Using device: {self.device}")
|
| 16 |
|
| 17 |
-
# Define
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
# --- Load Model Components ---
|
| 21 |
-
# Adjust these lines based on the specific classes your Orpheus model needs
|
| 22 |
-
# It might be AutoModelForSpeechSeq2Seq, VitsModel, BarkModel, etc.
|
| 23 |
-
# Ensure you use the correct class names from the transformers library or
|
| 24 |
-
# the library your model relies on.
|
| 25 |
try:
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
self.model.to(self.device)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# --- Get Sampling Rate ---
|
| 34 |
-
# Try to get sampling rate from config, provide a default if not found
|
| 35 |
-
# Common locations: model.config.sampling_rate or processor.feature_extractor.sampling_rate
|
| 36 |
-
# Adjust this based on your specific model architecture!
|
| 37 |
-
self.sampling_rate = getattr(self.model.config, 'sampling_rate', None)
|
| 38 |
-
if self.sampling_rate is None and hasattr(self.processor, 'feature_extractor'):
|
| 39 |
-
self.sampling_rate = getattr(self.processor.feature_extractor, 'sampling_rate', 16000) # Default fallback
|
| 40 |
-
elif self.sampling_rate is None:
|
| 41 |
-
self.sampling_rate = 16000 # Default fallback if no config found
|
| 42 |
-
print(f"Using sampling rate: {self.sampling_rate}")
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
except Exception as e:
|
| 46 |
-
print(f"Error
|
| 47 |
-
raise RuntimeError(f"Failed to load
|
| 48 |
-
|
| 49 |
|
| 50 |
def __call__(self, data: dict) -> bytes:
|
| 51 |
"""
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
Should return raw audio bytes (e.g., WAV format).
|
| 55 |
"""
|
| 56 |
try:
|
| 57 |
-
# --- Get Inputs ---
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
if inputs_text is None:
|
| 61 |
raise ValueError("Missing 'inputs' key in request data")
|
| 62 |
|
| 63 |
-
# Optional: handle other parameters passed in the request
|
| 64 |
parameters = data.pop("parameters", {})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
# --- Preprocess Text ---
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
# If your model needs specific args like speaker_embeddings, handle them here
|
| 75 |
-
# Example: speaker_embeddings = self.load_speaker_embedding(...)
|
| 76 |
-
# output = self.model.generate(**processed_inputs, speaker_embeddings=speaker_embeddings, **parameters)
|
| 77 |
-
output = self.model.generate(**processed_inputs, **parameters)
|
| 78 |
|
|
|
|
|
|
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
#
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
else:
|
| 92 |
-
|
| 93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
#
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
# --- Convert to WAV Bytes ---
|
| 102 |
-
# Use an in-memory buffer to store the WAV file
|
| 103 |
buffer = io.BytesIO()
|
| 104 |
-
sf.write(buffer,
|
| 105 |
buffer.seek(0)
|
| 106 |
wav_bytes = buffer.read()
|
| 107 |
|
|
@@ -109,6 +201,6 @@ class EndpointHandler():
|
|
| 109 |
return wav_bytes
|
| 110 |
|
| 111 |
except Exception as e:
|
| 112 |
-
print(f"Error during inference: {e}")
|
| 113 |
-
# Re-raise
|
| 114 |
raise RuntimeError(f"Inference failed: {e}")
|
|
|
|
| 1 |
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
import soundfile as sf
|
| 4 |
import io
|
|
|
|
| 5 |
import os
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 7 |
+
from snac import SNAC # Assuming SNAC is installed via requirements.txt
|
| 8 |
+
|
| 9 |
+
# --- Helper Function (can be outside or inside the class) ---
|
| 10 |
+
def redistribute_codes_static(code_list):
|
| 11 |
+
""" Reorganizes the flattened token list into three separate layers for SNAC. """
|
| 12 |
+
layer_1, layer_2, layer_3 = [], [], []
|
| 13 |
+
num_groups = len(code_list) // 7 # Use floor division
|
| 14 |
|
| 15 |
+
for i in range(num_groups):
|
| 16 |
+
idx = 7 * i
|
| 17 |
+
try:
|
| 18 |
+
layer_1.append(code_list[idx])
|
| 19 |
+
layer_2.append(code_list[idx + 1] - 4096)
|
| 20 |
+
layer_3.append(code_list[idx + 2] - (2 * 4096))
|
| 21 |
+
layer_3.append(code_list[idx + 3] - (3 * 4096))
|
| 22 |
+
layer_2.append(code_list[idx + 4] - (4 * 4096))
|
| 23 |
+
layer_3.append(code_list[idx + 5] - (5 * 4096))
|
| 24 |
+
layer_3.append(code_list[idx + 6] - (6 * 4096))
|
| 25 |
+
except IndexError:
|
| 26 |
+
print(f"Warning: Index out of range during code redistribution at group {i}. Code list length: {len(code_list)}")
|
| 27 |
+
break # Stop processing if indices go out of bounds
|
| 28 |
+
|
| 29 |
+
# Ensure tensors are created even if empty
|
| 30 |
+
codes = [
|
| 31 |
+
torch.tensor(layer_1 or [0]).unsqueeze(0).long(), # Use long dtype, provide default if empty
|
| 32 |
+
torch.tensor(layer_2 or [0]).unsqueeze(0).long(),
|
| 33 |
+
torch.tensor(layer_3 or [0]).unsqueeze(0).long()
|
| 34 |
+
]
|
| 35 |
+
# Remove the default [0] if lists were actually populated
|
| 36 |
+
if layer_1: codes[0] = torch.tensor(layer_1).unsqueeze(0).long()
|
| 37 |
+
if layer_2: codes[1] = torch.tensor(layer_2).unsqueeze(0).long()
|
| 38 |
+
if layer_3: codes[2] = torch.tensor(layer_3).unsqueeze(0).long()
|
| 39 |
+
|
| 40 |
+
return codes
|
| 41 |
+
|
| 42 |
+
# --- Endpoint Handler Class ---
|
| 43 |
class EndpointHandler():
|
| 44 |
def __init__(self, path=""):
|
| 45 |
"""
|
| 46 |
+
Initializes the handler. Loads both Orpheus LLM and SNAC Vocoder.
|
| 47 |
+
'path' points to the directory containing the Orpheus model files specified in the endpoint config.
|
| 48 |
"""
|
| 49 |
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 50 |
print(f"Using device: {self.device}")
|
| 51 |
|
| 52 |
+
# Define Model Names/Paths
|
| 53 |
+
# Orpheus LLM path is determined by the endpoint configuration ('path' variable)
|
| 54 |
+
orpheus_model_path = path if path else "hypaai/Hypa_Orpheus-3b-0.1-ft-unsloth-merged_16bit"
|
| 55 |
+
snac_model_name = "hubertsiuzdak/snac_24khz"
|
| 56 |
+
|
| 57 |
+
# Define Special Token IDs (matching your script)
|
| 58 |
+
self.start_human_token_id = 128259
|
| 59 |
+
self.end_text_token_id = 128009
|
| 60 |
+
self.end_human_token_id = 128260
|
| 61 |
+
# self.padding_token_id = 128263 # Not needed for single sequence generation
|
| 62 |
+
self.start_audio_token_id = 128257
|
| 63 |
+
self.end_audio_token_id = 128258
|
| 64 |
+
self.audio_code_offset = 128266
|
| 65 |
+
|
| 66 |
+
# Define sampling rate
|
| 67 |
+
self.sampling_rate = 24000
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
try:
|
| 70 |
+
# Load Orpheus LLM and Tokenizer
|
| 71 |
+
print(f"Loading Orpheus tokenizer from: {orpheus_model_path}")
|
| 72 |
+
self.tokenizer = AutoTokenizer.from_pretrained(orpheus_model_path)
|
| 73 |
+
print(f"Loading Orpheus model from: {orpheus_model_path}")
|
| 74 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 75 |
+
orpheus_model_path,
|
| 76 |
+
torch_dtype=torch.bfloat16 # Use bfloat16 as in your script
|
| 77 |
+
)
|
| 78 |
self.model.to(self.device)
|
| 79 |
+
self.model.eval() # Set model to evaluation mode
|
| 80 |
+
print("Orpheus model and tokenizer loaded successfully.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
+
# Load SNAC Vocoder
|
| 83 |
+
print(f"Loading SNAC model from: {snac_model_name}")
|
| 84 |
+
self.snac_model = SNAC.from_pretrained(snac_model_name)
|
| 85 |
+
self.snac_model.to(self.device) # Move SNAC to the same device
|
| 86 |
+
self.snac_model.eval() # Set model to evaluation mode
|
| 87 |
+
print("SNAC model loaded successfully.")
|
| 88 |
|
| 89 |
except Exception as e:
|
| 90 |
+
print(f"Error during model loading: {e}")
|
| 91 |
+
raise RuntimeError(f"Failed to load models.", e)
|
|
|
|
| 92 |
|
| 93 |
def __call__(self, data: dict) -> bytes:
|
| 94 |
"""
|
| 95 |
+
Handles incoming API requests for TTS inference.
|
| 96 |
+
Expects data['inputs'] (text) and optionally data['parameters']
|
|
|
|
| 97 |
"""
|
| 98 |
try:
|
| 99 |
+
# --- Get Inputs & Parameters ---
|
| 100 |
+
text = data.pop("inputs", None)
|
| 101 |
+
if text is None:
|
|
|
|
| 102 |
raise ValueError("Missing 'inputs' key in request data")
|
| 103 |
|
|
|
|
| 104 |
parameters = data.pop("parameters", {})
|
| 105 |
+
# Default voice if not provided
|
| 106 |
+
voice = parameters.get("voice", "Eniola")
|
| 107 |
+
# Default generation parameters (merge with provided ones)
|
| 108 |
+
gen_params = {
|
| 109 |
+
"max_new_tokens": 1200,
|
| 110 |
+
"do_sample": True,
|
| 111 |
+
"temperature": 0.6,
|
| 112 |
+
"top_p": 0.95,
|
| 113 |
+
"repetition_penalty": 1.1,
|
| 114 |
+
"num_return_sequences": 1,
|
| 115 |
+
"eos_token_id": self.end_audio_token_id,
|
| 116 |
+
**parameters # Overwrite defaults with user params
|
| 117 |
+
}
|
| 118 |
+
# Remove non-generate params if they were passed
|
| 119 |
+
gen_params.pop("voice", None)
|
| 120 |
+
|
| 121 |
+
print(f"Received request: text='{text[:50]}...', voice='{voice}', params={gen_params}")
|
| 122 |
|
| 123 |
# --- Preprocess Text ---
|
| 124 |
+
prompt = f"{voice}: {text}"
|
| 125 |
+
input_ids = self.tokenizer(prompt, return_tensors="pt").input_ids
|
| 126 |
|
| 127 |
+
# Add special tokens: SOH + Input Tokens + EOT + EOH
|
| 128 |
+
start_token_tensor = torch.tensor([[self.start_human_token_id]], dtype=torch.int64)
|
| 129 |
+
end_tokens_tensor = torch.tensor([[self.end_text_token_id, self.end_human_token_id]], dtype=torch.int64)
|
| 130 |
+
processed_input_ids = torch.cat([start_token_tensor, input_ids, end_tokens_tensor], dim=1).to(self.device)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
+
# Create attention mask (all ones for single, unpadded sequence)
|
| 133 |
+
attention_mask = torch.ones_like(processed_input_ids).to(self.device)
|
| 134 |
|
| 135 |
+
print(f"Processed input shape: {processed_input_ids.shape}")
|
| 136 |
+
|
| 137 |
+
# --- Generate Audio Codes (LLM Inference) ---
|
| 138 |
+
with torch.no_grad():
|
| 139 |
+
generated_ids = self.model.generate(
|
| 140 |
+
input_ids=processed_input_ids,
|
| 141 |
+
attention_mask=attention_mask,
|
| 142 |
+
**gen_params
|
| 143 |
+
)
|
| 144 |
+
print(f"Generated IDs shape: {generated_ids.shape}")
|
| 145 |
+
|
| 146 |
+
# --- Process Generated Tokens (Extract Audio Codes) ---
|
| 147 |
+
# Find the last Start of Audio token
|
| 148 |
+
soa_indices = (generated_ids[0] == self.start_audio_token_id).nonzero(as_tuple=True)[0]
|
| 149 |
+
if len(soa_indices) == 0:
|
| 150 |
+
print("Warning: Start of Audio token (128257) not found in generated sequence!")
|
| 151 |
+
# Handle this case: maybe return error, or try processing from start?
|
| 152 |
+
# For now, let's assume it might still contain codes and try processing all generated *new* tokens
|
| 153 |
+
start_idx = processed_input_ids.shape[1] # Start after the input prompt
|
| 154 |
else:
|
| 155 |
+
start_idx = soa_indices[-1].item() + 1 # Start after the last SOA token
|
| 156 |
+
|
| 157 |
+
# Extract potential audio codes (after last SOA or after input)
|
| 158 |
+
cropped_tokens = generated_ids[0, start_idx:]
|
| 159 |
+
|
| 160 |
+
# Remove End of Audio tokens
|
| 161 |
+
audio_codes_raw = cropped_tokens[cropped_tokens != self.end_audio_token_id]
|
| 162 |
+
print(f"Extracted raw audio codes count: {len(audio_codes_raw)}")
|
| 163 |
+
|
| 164 |
+
if len(audio_codes_raw) == 0:
|
| 165 |
+
raise ValueError("No audio codes generated or extracted after processing.")
|
| 166 |
|
| 167 |
+
# --- Prepare Codes for SNAC Vocoder ---
|
| 168 |
+
# Adjust token values
|
| 169 |
+
adjusted_codes = [t.item() - self.audio_code_offset for t in audio_codes_raw]
|
| 170 |
|
| 171 |
+
# Trim to multiple of 7
|
| 172 |
+
num_codes = len(adjusted_codes)
|
| 173 |
+
valid_length = (num_codes // 7) * 7
|
| 174 |
+
if valid_length == 0:
|
| 175 |
+
raise ValueError(f"Not enough audio codes ({num_codes}) to form a multiple of 7 after processing.")
|
| 176 |
+
trimmed_codes = adjusted_codes[:valid_length]
|
| 177 |
+
print(f"Trimmed adjusted audio codes count: {len(trimmed_codes)}")
|
| 178 |
+
|
| 179 |
+
# --- Redistribute Codes ---
|
| 180 |
+
# Use static method or instance method, ensure tensors are on correct device
|
| 181 |
+
snac_input_codes = redistribute_codes_static(trimmed_codes)
|
| 182 |
+
snac_input_codes = [layer.to(self.device) for layer in snac_input_codes]
|
| 183 |
+
|
| 184 |
+
# --- Decode Audio (SNAC Inference) ---
|
| 185 |
+
print("Decoding audio with SNAC...")
|
| 186 |
+
with torch.no_grad():
|
| 187 |
+
audio_hat = self.snac_model.decode(snac_input_codes)
|
| 188 |
+
print(f"Decoded audio tensor shape: {audio_hat.shape}") # Should be [1, 1, num_samples]
|
| 189 |
+
|
| 190 |
+
# --- Postprocess Audio ---
|
| 191 |
+
# Move to CPU, remove batch/channel dims, convert to numpy
|
| 192 |
+
audio_waveform = audio_hat.detach().squeeze().cpu().numpy()
|
| 193 |
|
| 194 |
# --- Convert to WAV Bytes ---
|
|
|
|
| 195 |
buffer = io.BytesIO()
|
| 196 |
+
sf.write(buffer, audio_waveform, self.sampling_rate, format='WAV')
|
| 197 |
buffer.seek(0)
|
| 198 |
wav_bytes = buffer.read()
|
| 199 |
|
|
|
|
| 201 |
return wav_bytes
|
| 202 |
|
| 203 |
except Exception as e:
|
| 204 |
+
print(f"Error during inference call: {e}")
|
| 205 |
+
# Re-raise for endpoint framework
|
| 206 |
raise RuntimeError(f"Inference failed: {e}")
|