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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
HuggingFace Space Demo for TextSyncMimi
|
| 4 |
+
Speech Editing with Token-Level Embedding Swapping
|
| 5 |
+
|
| 6 |
+
This demo loads the model from HuggingFace Hub and allows:
|
| 7 |
+
- Generating speech with different voices using OpenAI TTS
|
| 8 |
+
- Swapping speech embeddings at specific token positions
|
| 9 |
+
- Real-time speech editing
|
| 10 |
+
|
| 11 |
+
Prerequisites:
|
| 12 |
+
- Set OPENAI_API_KEY in Space secrets
|
| 13 |
+
- Model will be loaded from HuggingFace Hub
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import json
|
| 18 |
+
import tempfile
|
| 19 |
+
import argparse
|
| 20 |
+
from typing import List, Tuple, Optional
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
import torch.nn as nn
|
| 26 |
+
import soundfile as sf
|
| 27 |
+
import gradio as gr
|
| 28 |
+
from openai import OpenAI
|
| 29 |
+
from transformers import (
|
| 30 |
+
AutoModel,
|
| 31 |
+
AutoFeatureExtractor,
|
| 32 |
+
AutoTokenizer,
|
| 33 |
+
MimiModel,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# Constants
|
| 38 |
+
SAMPLE_RATE = 24000
|
| 39 |
+
FRAME_RATE = 12.5
|
| 40 |
+
TTS_VOICES = ["alloy", "ash", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer", "verse"]
|
| 41 |
+
MAX_Z_TOKENS = 50
|
| 42 |
+
END_TOKEN_THRESHOLD = 0.5
|
| 43 |
+
|
| 44 |
+
# Global variables
|
| 45 |
+
model = None
|
| 46 |
+
mimi_model = None
|
| 47 |
+
tokenizer = None
|
| 48 |
+
feature_extractor = None
|
| 49 |
+
device = None
|
| 50 |
+
openai_client = None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def load_audio_to_inputs(feature_extractor, audio_path: str, sample_rate: int) -> torch.Tensor:
|
| 54 |
+
"""Load audio file and convert to model inputs."""
|
| 55 |
+
import librosa
|
| 56 |
+
audio, sr = librosa.load(audio_path, sr=sample_rate, mono=True)
|
| 57 |
+
audio_inputs = feature_extractor(raw_audio=audio, return_tensors="pt", sampling_rate=sample_rate)
|
| 58 |
+
return audio_inputs.input_values
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def initialize_models(model_id: str, tokenizer_id: str = "meta-llama/Llama-3.1-8B-Instruct", hf_token: Optional[str] = None):
|
| 62 |
+
"""Initialize all models from HuggingFace Hub."""
|
| 63 |
+
global model, mimi_model, tokenizer, feature_extractor, device, openai_client
|
| 64 |
+
|
| 65 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 66 |
+
print(f"Using device: {device}")
|
| 67 |
+
|
| 68 |
+
print(f"Loading TextSyncMimi model from {model_id}...")
|
| 69 |
+
model = AutoModel.from_pretrained(
|
| 70 |
+
model_id,
|
| 71 |
+
trust_remote_code=True,
|
| 72 |
+
token=hf_token
|
| 73 |
+
)
|
| 74 |
+
model.to(device)
|
| 75 |
+
model.eval()
|
| 76 |
+
|
| 77 |
+
# Get mimi_model_id from config
|
| 78 |
+
mimi_model_id = model.config.mimi_model_id if hasattr(model.config, 'mimi_model_id') else "kyutai/mimi"
|
| 79 |
+
|
| 80 |
+
print("Loading Mimi model...")
|
| 81 |
+
mimi_model = MimiModel.from_pretrained(mimi_model_id, token=hf_token)
|
| 82 |
+
mimi_model.to(device)
|
| 83 |
+
mimi_model.eval()
|
| 84 |
+
|
| 85 |
+
print(f"Loading tokenizer from {tokenizer_id}...")
|
| 86 |
+
tokenizer = AutoTokenizer.from_pretrained(tokenizer_id, token=hf_token)
|
| 87 |
+
if tokenizer.pad_token is None:
|
| 88 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 89 |
+
|
| 90 |
+
print("Loading feature extractor...")
|
| 91 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(mimi_model_id, token=hf_token)
|
| 92 |
+
|
| 93 |
+
print("Initializing OpenAI client...")
|
| 94 |
+
openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
| 95 |
+
|
| 96 |
+
print("✅ All models loaded successfully!")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@torch.no_grad()
|
| 100 |
+
def compute_cross_attention_s(
|
| 101 |
+
model,
|
| 102 |
+
text_embeddings: torch.Tensor,
|
| 103 |
+
input_values: torch.Tensor,
|
| 104 |
+
device: str
|
| 105 |
+
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 106 |
+
"""Compute projected text embeddings and cross-attended speech embeddings."""
|
| 107 |
+
audio_attention_mask = torch.ones(1, input_values.shape[-1], dtype=torch.bool, device=device)
|
| 108 |
+
text_attention_mask = torch.ones(1, text_embeddings.shape[1], dtype=torch.bool, device=device)
|
| 109 |
+
|
| 110 |
+
# Encode speech
|
| 111 |
+
speech_embeddings = model.encode_audio_to_representation(
|
| 112 |
+
input_values.to(device),
|
| 113 |
+
audio_attention_mask=audio_attention_mask,
|
| 114 |
+
).transpose(1, 2)
|
| 115 |
+
|
| 116 |
+
# Project text
|
| 117 |
+
text_proj = model.text_proj(text_embeddings.to(device))
|
| 118 |
+
|
| 119 |
+
# Build attention masks
|
| 120 |
+
batch_size, text_seq_len = text_proj.shape[:2]
|
| 121 |
+
causal_mask = torch.tril(torch.ones(text_seq_len, text_seq_len, device=device, dtype=text_proj.dtype))
|
| 122 |
+
causal_mask = causal_mask.view(1, 1, text_seq_len, text_seq_len).expand(batch_size, -1, -1, -1)
|
| 123 |
+
pad_mask = text_attention_mask.view(batch_size, 1, 1, text_seq_len)
|
| 124 |
+
formatted_text_attention_mask = torch.where((causal_mask * pad_mask).bool(), 0.0, float("-inf"))
|
| 125 |
+
|
| 126 |
+
speech_seq_len = speech_embeddings.shape[1]
|
| 127 |
+
speech_mask = torch.ones(batch_size, speech_seq_len, dtype=torch.bool, device=device)
|
| 128 |
+
formatted_speech_attention_mask = torch.where(
|
| 129 |
+
speech_mask.view(batch_size, 1, 1, speech_seq_len), 0.0, float("-inf")
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
# Cross attention
|
| 133 |
+
cross_out = model.cross_attention_transformer(
|
| 134 |
+
hidden_states=text_proj,
|
| 135 |
+
encoder_hidden_states=speech_embeddings,
|
| 136 |
+
attention_mask=formatted_text_attention_mask,
|
| 137 |
+
encoder_attention_mask=formatted_speech_attention_mask,
|
| 138 |
+
alignment_chunk_sizes=None,
|
| 139 |
+
).last_hidden_state
|
| 140 |
+
|
| 141 |
+
return text_proj, cross_out, text_attention_mask
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@torch.no_grad()
|
| 145 |
+
def ar_generate_and_decode(
|
| 146 |
+
model,
|
| 147 |
+
mimi_model,
|
| 148 |
+
text_proj: torch.Tensor,
|
| 149 |
+
s_tokens: torch.Tensor,
|
| 150 |
+
text_attention_mask: torch.Tensor,
|
| 151 |
+
max_z_tokens: int,
|
| 152 |
+
end_token_threshold: float,
|
| 153 |
+
device: str
|
| 154 |
+
) -> np.ndarray:
|
| 155 |
+
"""Generate audio autoregressively and decode to waveform."""
|
| 156 |
+
batch_size, text_seq_len = text_proj.shape[:2]
|
| 157 |
+
|
| 158 |
+
text_speech_latent_emb = model.text_speech_latent_embed(torch.zeros(1, dtype=torch.long, device=device))
|
| 159 |
+
time_speech_start_emb = model.time_speech_start_embed(torch.zeros(1, dtype=torch.long, device=device))
|
| 160 |
+
time_speech_end_emb = model.time_speech_end_embed(torch.zeros(1, dtype=torch.long, device=device))
|
| 161 |
+
|
| 162 |
+
generated_z_tokens: List[torch.Tensor] = []
|
| 163 |
+
|
| 164 |
+
for b in range(batch_size):
|
| 165 |
+
if text_attention_mask is not None:
|
| 166 |
+
valid_text_len = int(text_attention_mask[b].sum().item())
|
| 167 |
+
else:
|
| 168 |
+
valid_text_len = text_seq_len
|
| 169 |
+
|
| 170 |
+
sequence: List[torch.Tensor] = [text_speech_latent_emb]
|
| 171 |
+
|
| 172 |
+
for i in range(valid_text_len):
|
| 173 |
+
t_i = text_proj[b, i:i+1]
|
| 174 |
+
s_i = s_tokens[b, i:i+1]
|
| 175 |
+
|
| 176 |
+
sequence.extend([t_i, s_i])
|
| 177 |
+
sequence.append(time_speech_start_emb)
|
| 178 |
+
|
| 179 |
+
z_count = 0
|
| 180 |
+
while z_count < max_z_tokens:
|
| 181 |
+
current_sequence = torch.cat(sequence, dim=0).unsqueeze(0)
|
| 182 |
+
ar_attention_mask = torch.ones(1, current_sequence.shape[1], dtype=torch.bool, device=device)
|
| 183 |
+
|
| 184 |
+
ar_outputs = model.ar_transformer(
|
| 185 |
+
hidden_states=current_sequence,
|
| 186 |
+
attention_mask=ar_attention_mask,
|
| 187 |
+
)
|
| 188 |
+
last_prediction = ar_outputs.last_hidden_state[0, -1:, :]
|
| 189 |
+
|
| 190 |
+
end_token_logit = model.end_token_classifier(last_prediction).squeeze(-1)
|
| 191 |
+
end_token_prob = torch.sigmoid(end_token_logit).item()
|
| 192 |
+
|
| 193 |
+
if end_token_prob >= end_token_threshold:
|
| 194 |
+
break
|
| 195 |
+
sequence.append(last_prediction)
|
| 196 |
+
generated_z_tokens.append(last_prediction.squeeze(0))
|
| 197 |
+
z_count += 1
|
| 198 |
+
|
| 199 |
+
sequence.append(time_speech_end_emb)
|
| 200 |
+
|
| 201 |
+
# Decode z tokens to audio
|
| 202 |
+
if len(generated_z_tokens) == 0:
|
| 203 |
+
audio_tensor = torch.zeros(1, 1, 1000, device=device)
|
| 204 |
+
else:
|
| 205 |
+
z_tokens_batch = torch.stack(generated_z_tokens, dim=0).unsqueeze(0)
|
| 206 |
+
embeddings_bct = z_tokens_batch.transpose(1, 2)
|
| 207 |
+
embeddings_upsampled = mimi_model.upsample(embeddings_bct)
|
| 208 |
+
decoder_outputs = mimi_model.decoder_transformer(embeddings_upsampled.transpose(1, 2), return_dict=True)
|
| 209 |
+
embeddings_after_dec = decoder_outputs.last_hidden_state.transpose(1, 2)
|
| 210 |
+
audio_tensor = mimi_model.decoder(embeddings_after_dec)
|
| 211 |
+
|
| 212 |
+
audio_numpy = audio_tensor.squeeze().detach().cpu().numpy()
|
| 213 |
+
if np.isnan(audio_numpy).any() or np.isinf(audio_numpy).any():
|
| 214 |
+
audio_numpy = np.nan_to_num(audio_numpy)
|
| 215 |
+
if audio_numpy.ndim > 1:
|
| 216 |
+
audio_numpy = audio_numpy.flatten()
|
| 217 |
+
return audio_numpy
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def generate_tts_audio(text: str, voice: str, instructions: str = None) -> str:
|
| 221 |
+
"""Generate TTS audio using OpenAI and return the file path."""
|
| 222 |
+
if not openai_client:
|
| 223 |
+
raise RuntimeError("OpenAI client not initialized")
|
| 224 |
+
|
| 225 |
+
if instructions and instructions.strip():
|
| 226 |
+
response = openai_client.audio.speech.create(
|
| 227 |
+
model="gpt-4o-mini-tts",
|
| 228 |
+
voice=voice,
|
| 229 |
+
input=text,
|
| 230 |
+
instructions=instructions.strip()
|
| 231 |
+
)
|
| 232 |
+
else:
|
| 233 |
+
response = openai_client.audio.speech.create(
|
| 234 |
+
model="tts-1",
|
| 235 |
+
voice=voice,
|
| 236 |
+
input=text
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file:
|
| 240 |
+
response.stream_to_file(temp_file.name)
|
| 241 |
+
return temp_file.name
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def process_inputs(transcript_text: str, voice1: str, voice2: str, instructions1: str = "", instructions2: str = ""):
|
| 245 |
+
"""Process inputs and generate audio."""
|
| 246 |
+
if not all([model, mimi_model, tokenizer, feature_extractor, openai_client]):
|
| 247 |
+
return "Please initialize models first!", None, None, None, None, None, None, None
|
| 248 |
+
|
| 249 |
+
if not transcript_text.strip():
|
| 250 |
+
return "Please provide a transcript!", None, None, None, None, None, None, None
|
| 251 |
+
|
| 252 |
+
if not voice1 or not voice2:
|
| 253 |
+
return "Please select voices for both audio samples!", None, None, None, None, None, None, None
|
| 254 |
+
|
| 255 |
+
# Tokenize
|
| 256 |
+
tokens = tokenizer(transcript_text.strip(), return_tensors="pt", add_special_tokens=False)
|
| 257 |
+
text_token_ids_cpu = tokens.input_ids.squeeze(0).tolist()
|
| 258 |
+
text_token_strs = tokenizer.convert_ids_to_tokens(text_token_ids_cpu)
|
| 259 |
+
text_token_ids = tokens.input_ids.to(device)
|
| 260 |
+
|
| 261 |
+
token_display = ""
|
| 262 |
+
for i, tok in enumerate(text_token_strs):
|
| 263 |
+
token_display += f"Token {i}: {tok}\n"
|
| 264 |
+
|
| 265 |
+
# Generate TTS audio
|
| 266 |
+
print(f"Generating TTS audio with voice '{voice1}'...")
|
| 267 |
+
audio1_path = generate_tts_audio(transcript_text.strip(), voice1, instructions1)
|
| 268 |
+
print(f"Generating TTS audio with voice '{voice2}'...")
|
| 269 |
+
audio2_path = generate_tts_audio(transcript_text.strip(), voice2, instructions2)
|
| 270 |
+
|
| 271 |
+
# Load audio
|
| 272 |
+
input_values_utt1 = load_audio_to_inputs(feature_extractor, audio1_path, SAMPLE_RATE)
|
| 273 |
+
input_values_utt2 = load_audio_to_inputs(feature_extractor, audio2_path, SAMPLE_RATE)
|
| 274 |
+
|
| 275 |
+
# Get text embeddings using model's built-in text_token_embedding
|
| 276 |
+
with torch.no_grad():
|
| 277 |
+
text_embeddings = model.text_token_embedding(text_token_ids)
|
| 278 |
+
|
| 279 |
+
# Compute cross-attention embeddings
|
| 280 |
+
t1_proj, s1_cross, text_attention_mask = compute_cross_attention_s(
|
| 281 |
+
model, text_embeddings, input_values_utt1, device
|
| 282 |
+
)
|
| 283 |
+
_, s2_cross, _ = compute_cross_attention_s(
|
| 284 |
+
model, text_embeddings, input_values_utt2, device
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
# Generate baseline audio
|
| 288 |
+
baseline_audio = ar_generate_and_decode(
|
| 289 |
+
model=model,
|
| 290 |
+
mimi_model=mimi_model,
|
| 291 |
+
text_proj=t1_proj,
|
| 292 |
+
s_tokens=s1_cross,
|
| 293 |
+
text_attention_mask=text_attention_mask,
|
| 294 |
+
max_z_tokens=MAX_Z_TOKENS,
|
| 295 |
+
end_token_threshold=END_TOKEN_THRESHOLD,
|
| 296 |
+
device=device,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
|
| 300 |
+
sf.write(f.name, baseline_audio, SAMPLE_RATE)
|
| 301 |
+
baseline_path = f.name
|
| 302 |
+
|
| 303 |
+
return (
|
| 304 |
+
"Processing completed successfully!",
|
| 305 |
+
token_display,
|
| 306 |
+
audio1_path,
|
| 307 |
+
audio2_path,
|
| 308 |
+
baseline_path,
|
| 309 |
+
json.dumps({
|
| 310 |
+
"t1_proj": t1_proj.cpu().numpy().tolist(),
|
| 311 |
+
"s1_cross": s1_cross.cpu().numpy().tolist(),
|
| 312 |
+
"s2_cross": s2_cross.cpu().numpy().tolist(),
|
| 313 |
+
"text_attention_mask": text_attention_mask.cpu().numpy().tolist(),
|
| 314 |
+
"num_tokens": len(text_token_strs)
|
| 315 |
+
}),
|
| 316 |
+
audio1_path,
|
| 317 |
+
audio2_path
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def swap_embeddings(embeddings_json: str, swap_indices: str):
|
| 322 |
+
"""Perform embedding swap at specified token indices."""
|
| 323 |
+
if not embeddings_json:
|
| 324 |
+
return "Please process inputs first!", None
|
| 325 |
+
|
| 326 |
+
if not swap_indices.strip():
|
| 327 |
+
return "Please specify token indices to swap (e.g., 0,2,5)!", None
|
| 328 |
+
|
| 329 |
+
# Parse stored embeddings
|
| 330 |
+
embeddings_data = json.loads(embeddings_json)
|
| 331 |
+
t1_proj = torch.tensor(embeddings_data["t1_proj"]).to(device)
|
| 332 |
+
s1_cross = torch.tensor(embeddings_data["s1_cross"]).to(device)
|
| 333 |
+
s2_cross = torch.tensor(embeddings_data["s2_cross"]).to(device)
|
| 334 |
+
text_attention_mask = torch.tensor(embeddings_data["text_attention_mask"]).to(device)
|
| 335 |
+
num_tokens = embeddings_data["num_tokens"]
|
| 336 |
+
|
| 337 |
+
# Parse indices
|
| 338 |
+
parts = [p.strip() for p in swap_indices.split(",")]
|
| 339 |
+
parsed = [int(p) for p in parts if p.isdigit()]
|
| 340 |
+
|
| 341 |
+
if len(parsed) == 0:
|
| 342 |
+
return "No valid indices provided! Use format: 0,2,5", None
|
| 343 |
+
|
| 344 |
+
valid_indices = [i for i in parsed if 0 <= i < num_tokens]
|
| 345 |
+
if len(valid_indices) == 0:
|
| 346 |
+
return f"All indices out of range! Valid range: 0-{num_tokens-1}", None
|
| 347 |
+
|
| 348 |
+
# Perform swap
|
| 349 |
+
s_swapped = s1_cross.clone()
|
| 350 |
+
for idx in valid_indices:
|
| 351 |
+
s_swapped[:, idx:idx+1, :] = s2_cross[:, idx:idx+1, :]
|
| 352 |
+
|
| 353 |
+
# Generate swapped audio
|
| 354 |
+
swapped_audio = ar_generate_and_decode(
|
| 355 |
+
model=model,
|
| 356 |
+
mimi_model=mimi_model,
|
| 357 |
+
text_proj=t1_proj,
|
| 358 |
+
s_tokens=s_swapped,
|
| 359 |
+
text_attention_mask=text_attention_mask,
|
| 360 |
+
max_z_tokens=MAX_Z_TOKENS,
|
| 361 |
+
end_token_threshold=END_TOKEN_THRESHOLD,
|
| 362 |
+
device=device,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
|
| 366 |
+
sf.write(f.name, swapped_audio, SAMPLE_RATE)
|
| 367 |
+
swapped_path = f.name
|
| 368 |
+
|
| 369 |
+
return f"Successfully swapped embeddings at token indices: {valid_indices}", swapped_path
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def create_gradio_interface():
|
| 373 |
+
"""Create the Gradio interface."""
|
| 374 |
+
with gr.Blocks(title="TextSyncMimi Demo") as interface:
|
| 375 |
+
gr.Markdown("# TextSyncMimi - Standalone Demo")
|
| 376 |
+
gr.Markdown("Generate two voice renditions using OpenAI TTS, then swap speech embeddings at token positions.")
|
| 377 |
+
gr.Markdown("**This demo uses only the self-contained TextSyncMimi-v1 model code.**")
|
| 378 |
+
|
| 379 |
+
with gr.Accordion("Style Instruction Examples", open=False):
|
| 380 |
+
gr.Markdown("""
|
| 381 |
+
**Example Instructions:**
|
| 382 |
+
- *Emotional:* "Speak with excitement and joy", "Sound sad and melancholy"
|
| 383 |
+
- *Pace:* "Speak slowly and deliberately", "Talk quickly and energetically"
|
| 384 |
+
- *Character:* "Sound like a wise professor", "Speak like an excited child"
|
| 385 |
+
""")
|
| 386 |
+
|
| 387 |
+
with gr.Row():
|
| 388 |
+
with gr.Column():
|
| 389 |
+
gr.Markdown("## Text-to-Speech Configuration")
|
| 390 |
+
transcript_text = gr.Textbox(
|
| 391 |
+
label="Transcript Text",
|
| 392 |
+
placeholder="Enter text to synthesize...",
|
| 393 |
+
lines=3
|
| 394 |
+
)
|
| 395 |
+
with gr.Row():
|
| 396 |
+
voice1 = gr.Dropdown(
|
| 397 |
+
choices=TTS_VOICES,
|
| 398 |
+
label="Voice 1",
|
| 399 |
+
value="alloy"
|
| 400 |
+
)
|
| 401 |
+
voice2 = gr.Dropdown(
|
| 402 |
+
choices=TTS_VOICES,
|
| 403 |
+
label="Voice 2",
|
| 404 |
+
value="echo"
|
| 405 |
+
)
|
| 406 |
+
instructions1 = gr.Textbox(
|
| 407 |
+
label="Style Instructions for Voice 1",
|
| 408 |
+
placeholder="e.g., Speak slowly and calmly",
|
| 409 |
+
lines=2
|
| 410 |
+
)
|
| 411 |
+
instructions2 = gr.Textbox(
|
| 412 |
+
label="Style Instructions for Voice 2",
|
| 413 |
+
placeholder="e.g., Speak quickly with excitement",
|
| 414 |
+
lines=2
|
| 415 |
+
)
|
| 416 |
+
process_btn = gr.Button("Generate & Process", variant="primary")
|
| 417 |
+
process_status = gr.Textbox(label="Status", interactive=False)
|
| 418 |
+
|
| 419 |
+
with gr.Column():
|
| 420 |
+
gr.Markdown("## Tokenization")
|
| 421 |
+
tokens_display = gr.Textbox(
|
| 422 |
+
label="Tokens",
|
| 423 |
+
lines=16,
|
| 424 |
+
interactive=False
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
with gr.Row():
|
| 428 |
+
with gr.Column():
|
| 429 |
+
gr.Markdown("## Generated TTS Audio")
|
| 430 |
+
generated_audio1 = gr.Audio(label="Generated Audio 1")
|
| 431 |
+
generated_audio2 = gr.Audio(label="Generated Audio 2")
|
| 432 |
+
|
| 433 |
+
with gr.Column():
|
| 434 |
+
gr.Markdown("## Model Output")
|
| 435 |
+
baseline_audio = gr.Audio(label="Baseline Reconstruction")
|
| 436 |
+
|
| 437 |
+
gr.Markdown("### Embedding Swap")
|
| 438 |
+
swap_indices_input = gr.Textbox(
|
| 439 |
+
label="Token Indices to Swap",
|
| 440 |
+
placeholder="e.g., 0,2,5"
|
| 441 |
+
)
|
| 442 |
+
swap_btn = gr.Button("Perform Swap")
|
| 443 |
+
swap_status = gr.Textbox(label="Swap Status", interactive=False)
|
| 444 |
+
swapped_audio = gr.Audio(label="Swapped Result")
|
| 445 |
+
|
| 446 |
+
# Hidden states
|
| 447 |
+
embeddings_state = gr.State()
|
| 448 |
+
audio1_state = gr.State()
|
| 449 |
+
audio2_state = gr.State()
|
| 450 |
+
|
| 451 |
+
# Event handlers
|
| 452 |
+
process_btn.click(
|
| 453 |
+
fn=process_inputs,
|
| 454 |
+
inputs=[transcript_text, voice1, voice2, instructions1, instructions2],
|
| 455 |
+
outputs=[process_status, tokens_display, generated_audio1, generated_audio2,
|
| 456 |
+
baseline_audio, embeddings_state, audio1_state, audio2_state]
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
swap_btn.click(
|
| 460 |
+
fn=swap_embeddings,
|
| 461 |
+
inputs=[embeddings_state, swap_indices_input],
|
| 462 |
+
outputs=[swap_status, swapped_audio]
|
| 463 |
+
)
|
| 464 |
+
|
| 465 |
+
return interface
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def main():
|
| 469 |
+
"""Main function."""
|
| 470 |
+
parser = argparse.ArgumentParser(description="HuggingFace Space Demo for TextSyncMimi")
|
| 471 |
+
parser.add_argument(
|
| 472 |
+
"--model_id",
|
| 473 |
+
type=str,
|
| 474 |
+
default="potsawee/TextSyncMimi-v1",
|
| 475 |
+
help="HuggingFace model ID"
|
| 476 |
+
)
|
| 477 |
+
parser.add_argument(
|
| 478 |
+
"--tokenizer_id",
|
| 479 |
+
type=str,
|
| 480 |
+
default="meta-llama/Llama-3.1-8B-Instruct",
|
| 481 |
+
help="HuggingFace tokenizer ID"
|
| 482 |
+
)
|
| 483 |
+
parser.add_argument(
|
| 484 |
+
"--hf_token",
|
| 485 |
+
type=str,
|
| 486 |
+
default=None,
|
| 487 |
+
help="Hugging Face token (or set HF_TOKEN env var)"
|
| 488 |
+
)
|
| 489 |
+
parser.add_argument(
|
| 490 |
+
"--port",
|
| 491 |
+
type=int,
|
| 492 |
+
default=7860,
|
| 493 |
+
help="Port for Gradio app"
|
| 494 |
+
)
|
| 495 |
+
parser.add_argument(
|
| 496 |
+
"--share",
|
| 497 |
+
action="store_true",
|
| 498 |
+
help="Create public share link"
|
| 499 |
+
)
|
| 500 |
+
args = parser.parse_args()
|
| 501 |
+
|
| 502 |
+
# Check OpenAI API key
|
| 503 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 504 |
+
print("❌ Error: OPENAI_API_KEY environment variable is required!")
|
| 505 |
+
print("Set it: export OPENAI_API_KEY=your_key_here")
|
| 506 |
+
return
|
| 507 |
+
|
| 508 |
+
# Get HF token
|
| 509 |
+
hf_token = args.hf_token or os.getenv("HF_TOKEN")
|
| 510 |
+
|
| 511 |
+
# Initialize models
|
| 512 |
+
print(f"🚀 Initializing TextSyncMimi from HuggingFace Hub: {args.model_id}...")
|
| 513 |
+
initialize_models(args.model_id, args.tokenizer_id, hf_token)
|
| 514 |
+
print("🌐 Launching Gradio interface...")
|
| 515 |
+
|
| 516 |
+
# Launch
|
| 517 |
+
interface = create_gradio_interface()
|
| 518 |
+
interface.launch(server_port=args.port, share=args.share)
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
if __name__ == "__main__":
|
| 522 |
+
main()
|
| 523 |
+
|