Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Commit
·
749c08c
1
Parent(s):
1d188b4
Refactor: Separate frontend and backend code
Browse filesMoved Gradio app and related files to 'frontend_app/' and Modal backend
code to 'backend_modal/' for clearer separation and easier deployment.
This view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +0 -805
- {configs → backend_modal/configs}/qwen2.5_1.5b_64k.json +0 -0
- {configs → backend_modal/configs}/qwen2.5_7b_32k.json +0 -0
- {example → backend_modal/example}/1p_EN2CH.mp4 +0 -0
- {example → backend_modal/example}/2p_see_u_again.mp4 +0 -0
- {example → backend_modal/example}/4p_climate_45min.mp4 +0 -0
- backend_modal/modal_runner.py +230 -0
- {modular → backend_modal/modular}/__init__.py +0 -0
- {modular → backend_modal/modular}/configuration_vibevoice.py +0 -0
- {modular → backend_modal/modular}/modeling_vibevoice.py +0 -0
- {modular → backend_modal/modular}/modeling_vibevoice_inference.py +0 -0
- {modular → backend_modal/modular}/modular_vibevoice_diffusion_head.py +0 -0
- {modular → backend_modal/modular}/modular_vibevoice_text_tokenizer.py +0 -0
- {modular → backend_modal/modular}/modular_vibevoice_tokenizer.py +0 -0
- {modular → backend_modal/modular}/streamer.py +0 -0
- packages.txt → backend_modal/packages.txt +0 -0
- {processor → backend_modal/processor}/__init__.py +0 -0
- {processor → backend_modal/processor}/vibevoice_processor.py +0 -0
- {processor → backend_modal/processor}/vibevoice_tokenizer_processor.py +0 -0
- {schedule → backend_modal/schedule}/__init__.py +0 -0
- {schedule → backend_modal/schedule}/dpm_solver.py +0 -0
- {schedule → backend_modal/schedule}/timestep_sampler.py +0 -0
- {scripts → backend_modal/scripts}/__init__.py +0 -0
- {scripts → backend_modal/scripts}/convert_nnscaler_checkpoint_to_transformers.py +0 -0
- setup_voices.sh → backend_modal/setup_voices.sh +0 -0
- {text_examples → backend_modal/text_examples}/1p_ai_tedtalk.txt +0 -0
- {text_examples → backend_modal/text_examples}/1p_ai_tedtalk_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/1p_politcal_speech.txt +0 -0
- {text_examples → backend_modal/text_examples}/1p_politcal_speech_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/2p_financeipo_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/2p_financeipo_meeting_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/2p_telehealth_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/2p_telehealth_meeting_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/3p_military_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/3p_military_meeting_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/3p_oil_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/3p_oil_meeting_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/4p_gamecreation_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/4p_gamecreation_meeting_natural.txt +0 -0
- {text_examples → backend_modal/text_examples}/4p_product_meeting.txt +0 -0
- {text_examples → backend_modal/text_examples}/4p_product_meeting_natural.txt +0 -0
- {voices → backend_modal/voices}/en-Alice_woman.wav +0 -0
- {voices → backend_modal/voices}/en-Alice_woman_bgm.wav +0 -0
- {voices → backend_modal/voices}/en-Carter_man.wav +0 -0
- {voices → backend_modal/voices}/en-Frank_man.wav +0 -0
- {voices → backend_modal/voices}/en-Maya_woman.wav +0 -0
- {voices → backend_modal/voices}/en-Yasser_man.wav +0 -0
- {voices → backend_modal/voices}/in-Samuel_man.wav +0 -0
- {voices → backend_modal/voices}/zh-Anchen_man_bgm.wav +0 -0
- {voices → backend_modal/voices}/zh-Bowen_man.wav +0 -0
app.py
DELETED
|
@@ -1,805 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import time
|
| 3 |
-
import numpy as np
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import librosa
|
| 6 |
-
import soundfile as sf
|
| 7 |
-
import torch
|
| 8 |
-
import traceback
|
| 9 |
-
import threading
|
| 10 |
-
from spaces import GPU
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
from contextlib import contextmanager
|
| 13 |
-
|
| 14 |
-
from modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
|
| 15 |
-
from processor.vibevoice_processor import VibeVoiceProcessor
|
| 16 |
-
from modular.streamer import AudioStreamer
|
| 17 |
-
from transformers.utils import logging
|
| 18 |
-
from transformers import set_seed
|
| 19 |
-
|
| 20 |
-
logging.set_verbosity_info()
|
| 21 |
-
logger = logging.get_logger(__name__)
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
class VibeVoiceDemo:
|
| 26 |
-
def __init__(self, model_paths: dict, device: str = "cuda", inference_steps: int = 5):
|
| 27 |
-
"""
|
| 28 |
-
model_paths: dict like {"VibeVoice-1.5B": "microsoft/VibeVoice-1.5B",
|
| 29 |
-
"VibeVoice-7B": "microsoft/VibeVoice-7B"}
|
| 30 |
-
"""
|
| 31 |
-
self.model_paths = model_paths
|
| 32 |
-
self.device = device
|
| 33 |
-
self.inference_steps = inference_steps
|
| 34 |
-
|
| 35 |
-
self.is_generating = False
|
| 36 |
-
|
| 37 |
-
# Multi-model holders
|
| 38 |
-
self.models = {} # name -> model
|
| 39 |
-
self.processors = {} # name -> processor
|
| 40 |
-
self.current_model_name = None
|
| 41 |
-
|
| 42 |
-
self.available_voices = {}
|
| 43 |
-
|
| 44 |
-
# Set compiler flags for better performance
|
| 45 |
-
if torch.cuda.is_available() and hasattr(torch, '_inductor'):
|
| 46 |
-
if hasattr(torch._inductor, 'config'):
|
| 47 |
-
torch._inductor.config.conv_1x1_as_mm = True
|
| 48 |
-
torch._inductor.config.coordinate_descent_tuning = True
|
| 49 |
-
torch._inductor.config.epilogue_fusion = False
|
| 50 |
-
torch._inductor.config.coordinate_descent_check_all_directions = True
|
| 51 |
-
|
| 52 |
-
self.load_models() # load all on CPU
|
| 53 |
-
self.setup_voice_presets()
|
| 54 |
-
self.load_example_scripts()
|
| 55 |
-
|
| 56 |
-
def load_models(self):
|
| 57 |
-
print("Loading processors and models on CPU...")
|
| 58 |
-
|
| 59 |
-
# Debug: Show cache location
|
| 60 |
-
import os
|
| 61 |
-
cache_dir = os.path.expanduser("~/.cache/huggingface/hub")
|
| 62 |
-
print(f"HuggingFace cache directory: {cache_dir}")
|
| 63 |
-
if os.path.exists(cache_dir):
|
| 64 |
-
print(f"Cache exists. Size: {sum(os.path.getsize(os.path.join(dirpath, filename)) for dirpath, _, filenames in os.walk(cache_dir) for filename in filenames) / (1024**3):.2f} GB")
|
| 65 |
-
print("Cached models:")
|
| 66 |
-
for item in os.listdir(cache_dir):
|
| 67 |
-
if item.startswith("models--"):
|
| 68 |
-
print(f" - {item}")
|
| 69 |
-
|
| 70 |
-
for name, path in self.model_paths.items():
|
| 71 |
-
print(f" - {name} from {path}")
|
| 72 |
-
proc = VibeVoiceProcessor.from_pretrained(path)
|
| 73 |
-
# Use SDPA (Scaled Dot Product Attention) for better memory efficiency
|
| 74 |
-
# Flash Attention 2 disabled to reduce memory usage on L4 GPUs
|
| 75 |
-
mdl = VibeVoiceForConditionalGenerationInference.from_pretrained(
|
| 76 |
-
path,
|
| 77 |
-
torch_dtype=torch.bfloat16,
|
| 78 |
-
attn_implementation="sdpa" # More memory efficient than flash_attention_2
|
| 79 |
-
)
|
| 80 |
-
print(f" SDPA (memory-efficient) attention enabled for {name}")
|
| 81 |
-
# Keep on CPU initially
|
| 82 |
-
self.processors[name] = proc
|
| 83 |
-
self.models[name] = mdl
|
| 84 |
-
# choose default
|
| 85 |
-
self.current_model_name = next(iter(self.models))
|
| 86 |
-
print(f"Default model is {self.current_model_name}")
|
| 87 |
-
|
| 88 |
-
def _place_model(self, target_name: str):
|
| 89 |
-
"""
|
| 90 |
-
Move the selected model to CUDA and push all others back to CPU.
|
| 91 |
-
"""
|
| 92 |
-
# Clear GPU cache before moving models
|
| 93 |
-
if torch.cuda.is_available():
|
| 94 |
-
torch.cuda.empty_cache()
|
| 95 |
-
|
| 96 |
-
for name, mdl in self.models.items():
|
| 97 |
-
if name == target_name:
|
| 98 |
-
self.models[name] = mdl.to(self.device)
|
| 99 |
-
else:
|
| 100 |
-
self.models[name] = mdl.to("cpu")
|
| 101 |
-
|
| 102 |
-
# Clear cache again after model placement
|
| 103 |
-
if torch.cuda.is_available():
|
| 104 |
-
torch.cuda.empty_cache()
|
| 105 |
-
|
| 106 |
-
self.current_model_name = target_name
|
| 107 |
-
print(f"Model {target_name} is now on {self.device}. Others moved to CPU.")
|
| 108 |
-
|
| 109 |
-
def setup_voice_presets(self):
|
| 110 |
-
voices_dir = os.path.join(os.path.dirname(__file__), "voices")
|
| 111 |
-
if not os.path.exists(voices_dir):
|
| 112 |
-
print(f"Warning: Voices directory not found at {voices_dir}")
|
| 113 |
-
return
|
| 114 |
-
wav_files = [f for f in os.listdir(voices_dir)
|
| 115 |
-
if f.lower().endswith(('.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac'))]
|
| 116 |
-
for wav_file in wav_files:
|
| 117 |
-
name = os.path.splitext(wav_file)[0]
|
| 118 |
-
self.available_voices[name] = os.path.join(voices_dir, wav_file)
|
| 119 |
-
print(f"Voices loaded: {list(self.available_voices.keys())}")
|
| 120 |
-
|
| 121 |
-
# Organize voices by gender
|
| 122 |
-
self.male_voices = [
|
| 123 |
-
"en-Carter_man",
|
| 124 |
-
"en-Frank_man",
|
| 125 |
-
"en-Yasser_man",
|
| 126 |
-
"in-Samuel_man",
|
| 127 |
-
"zh-Anchen_man_bgm",
|
| 128 |
-
"zh-Bowen_man"
|
| 129 |
-
]
|
| 130 |
-
self.female_voices = [
|
| 131 |
-
"en-Alice_woman_bgm",
|
| 132 |
-
"en-Alice_woman",
|
| 133 |
-
"en-Maya_woman",
|
| 134 |
-
"zh-Xinran_woman"
|
| 135 |
-
]
|
| 136 |
-
|
| 137 |
-
def read_audio(self, audio_path: str, target_sr: int = 24000) -> np.ndarray:
|
| 138 |
-
try:
|
| 139 |
-
wav, sr = sf.read(audio_path)
|
| 140 |
-
if len(wav.shape) > 1:
|
| 141 |
-
wav = np.mean(wav, axis=1)
|
| 142 |
-
if sr != target_sr:
|
| 143 |
-
wav = librosa.resample(wav, orig_sr=sr, target_sr=target_sr)
|
| 144 |
-
return wav
|
| 145 |
-
except Exception as e:
|
| 146 |
-
print(f"Error reading audio {audio_path}: {e}")
|
| 147 |
-
return np.array([])
|
| 148 |
-
|
| 149 |
-
@GPU(duration=120)
|
| 150 |
-
def generate_podcast(self,
|
| 151 |
-
num_speakers: int,
|
| 152 |
-
script: str,
|
| 153 |
-
speaker_1: str = None,
|
| 154 |
-
speaker_2: str = None,
|
| 155 |
-
speaker_3: str = None,
|
| 156 |
-
speaker_4: str = None,
|
| 157 |
-
cfg_scale: float = 1.3,
|
| 158 |
-
model_name: str = None):
|
| 159 |
-
"""
|
| 160 |
-
Generates a conference as a single audio file from a script and saves it.
|
| 161 |
-
Non-streaming.
|
| 162 |
-
"""
|
| 163 |
-
try:
|
| 164 |
-
# pick model
|
| 165 |
-
model_name = model_name or self.current_model_name
|
| 166 |
-
if model_name not in self.models:
|
| 167 |
-
raise gr.Error(f"Unknown model: {model_name}")
|
| 168 |
-
|
| 169 |
-
# place models on devices
|
| 170 |
-
self._place_model(model_name)
|
| 171 |
-
model = self.models[model_name]
|
| 172 |
-
processor = self.processors[model_name]
|
| 173 |
-
|
| 174 |
-
print(f"Using model {model_name} on {self.device}")
|
| 175 |
-
|
| 176 |
-
# Additional cache clear before generation
|
| 177 |
-
if torch.cuda.is_available():
|
| 178 |
-
torch.cuda.empty_cache()
|
| 179 |
-
|
| 180 |
-
model.eval()
|
| 181 |
-
model.set_ddpm_inference_steps(num_steps=self.inference_steps)
|
| 182 |
-
|
| 183 |
-
self.is_generating = True
|
| 184 |
-
|
| 185 |
-
if not script.strip():
|
| 186 |
-
raise gr.Error("Error: Please provide a script.")
|
| 187 |
-
|
| 188 |
-
script = script.replace("’", "'")
|
| 189 |
-
|
| 190 |
-
if not 1 <= num_speakers <= 4:
|
| 191 |
-
raise gr.Error("Error: Number of speakers must be between 1 and 4.")
|
| 192 |
-
|
| 193 |
-
selected_speakers = [speaker_1, speaker_2, speaker_3, speaker_4][:num_speakers]
|
| 194 |
-
for i, speaker_name in enumerate(selected_speakers):
|
| 195 |
-
if not speaker_name or speaker_name not in self.available_voices:
|
| 196 |
-
raise gr.Error(f"Error: Please select a valid speaker for Speaker {i+1}.")
|
| 197 |
-
|
| 198 |
-
log = f"Generating conference with {num_speakers} speakers\n"
|
| 199 |
-
log += f"Model: {model_name}\n"
|
| 200 |
-
log += f"Parameters: CFG Scale={cfg_scale}\n"
|
| 201 |
-
log += f"Speakers: {', '.join(selected_speakers)}\n"
|
| 202 |
-
|
| 203 |
-
voice_samples = []
|
| 204 |
-
for speaker_name in selected_speakers:
|
| 205 |
-
audio_path = self.available_voices[speaker_name]
|
| 206 |
-
audio_data = self.read_audio(audio_path)
|
| 207 |
-
if len(audio_data) == 0:
|
| 208 |
-
raise gr.Error(f"Error: Failed to load audio for {speaker_name}")
|
| 209 |
-
voice_samples.append(audio_data)
|
| 210 |
-
|
| 211 |
-
log += f"Loaded {len(voice_samples)} voice samples\n"
|
| 212 |
-
|
| 213 |
-
lines = script.strip().split('\n')
|
| 214 |
-
formatted_script_lines = []
|
| 215 |
-
for line in lines:
|
| 216 |
-
line = line.strip()
|
| 217 |
-
if not line:
|
| 218 |
-
continue
|
| 219 |
-
if line.startswith('Speaker ') and ':' in line:
|
| 220 |
-
formatted_script_lines.append(line)
|
| 221 |
-
else:
|
| 222 |
-
speaker_id = len(formatted_script_lines) % num_speakers
|
| 223 |
-
formatted_script_lines.append(f"Speaker {speaker_id}: {line}")
|
| 224 |
-
|
| 225 |
-
formatted_script = '\n'.join(formatted_script_lines)
|
| 226 |
-
log += f"Formatted script with {len(formatted_script_lines)} turns\n"
|
| 227 |
-
log += "Processing with VibeVoice...\n"
|
| 228 |
-
|
| 229 |
-
inputs = processor(
|
| 230 |
-
text=[formatted_script],
|
| 231 |
-
voice_samples=[voice_samples],
|
| 232 |
-
padding=True,
|
| 233 |
-
return_tensors="pt",
|
| 234 |
-
return_attention_mask=True,
|
| 235 |
-
)
|
| 236 |
-
|
| 237 |
-
start_time = time.time()
|
| 238 |
-
|
| 239 |
-
# Use efficient attention backend
|
| 240 |
-
if torch.cuda.is_available() and hasattr(torch.nn.attention, 'SDPBackend'):
|
| 241 |
-
from torch.nn.attention import SDPBackend, sdpa_kernel
|
| 242 |
-
with sdpa_kernel(SDPBackend.EFFICIENT_ATTENTION):
|
| 243 |
-
outputs = model.generate(
|
| 244 |
-
**inputs,
|
| 245 |
-
max_new_tokens=None,
|
| 246 |
-
cfg_scale=cfg_scale,
|
| 247 |
-
tokenizer=processor.tokenizer,
|
| 248 |
-
generation_config={'do_sample': False},
|
| 249 |
-
verbose=False,
|
| 250 |
-
)
|
| 251 |
-
else:
|
| 252 |
-
outputs = model.generate(
|
| 253 |
-
**inputs,
|
| 254 |
-
max_new_tokens=None,
|
| 255 |
-
cfg_scale=cfg_scale,
|
| 256 |
-
tokenizer=processor.tokenizer,
|
| 257 |
-
generation_config={'do_sample': False},
|
| 258 |
-
verbose=False,
|
| 259 |
-
)
|
| 260 |
-
generation_time = time.time() - start_time
|
| 261 |
-
|
| 262 |
-
if hasattr(outputs, 'speech_outputs') and outputs.speech_outputs[0] is not None:
|
| 263 |
-
audio_tensor = outputs.speech_outputs[0]
|
| 264 |
-
audio = audio_tensor.cpu().float().numpy()
|
| 265 |
-
else:
|
| 266 |
-
raise gr.Error("Error: No audio was generated by the model. Please try again.")
|
| 267 |
-
|
| 268 |
-
if audio.ndim > 1:
|
| 269 |
-
audio = audio.squeeze()
|
| 270 |
-
|
| 271 |
-
sample_rate = 24000
|
| 272 |
-
|
| 273 |
-
output_dir = "outputs"
|
| 274 |
-
os.makedirs(output_dir, exist_ok=True)
|
| 275 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 276 |
-
file_path = os.path.join(output_dir, f"conference_{timestamp}.wav")
|
| 277 |
-
sf.write(file_path, audio, sample_rate)
|
| 278 |
-
print(f"Conference saved to {file_path}")
|
| 279 |
-
|
| 280 |
-
total_duration = len(audio) / sample_rate
|
| 281 |
-
log += f"Generation completed in {generation_time:.2f} seconds\n"
|
| 282 |
-
log += f"Final audio duration: {total_duration:.2f} seconds\n"
|
| 283 |
-
log += f"Successfully saved conference to: {file_path}\n"
|
| 284 |
-
|
| 285 |
-
self.is_generating = False
|
| 286 |
-
return (sample_rate, audio), log
|
| 287 |
-
|
| 288 |
-
except gr.Error as e:
|
| 289 |
-
self.is_generating = False
|
| 290 |
-
error_msg = f"Input Error: {str(e)}"
|
| 291 |
-
print(error_msg)
|
| 292 |
-
return None, error_msg
|
| 293 |
-
|
| 294 |
-
except Exception as e:
|
| 295 |
-
self.is_generating = False
|
| 296 |
-
error_msg = f"An unexpected error occurred: {str(e)}"
|
| 297 |
-
print(error_msg)
|
| 298 |
-
traceback.print_exc()
|
| 299 |
-
return None, error_msg
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
@staticmethod
|
| 303 |
-
def _infer_num_speakers_from_script(script: str) -> int:
|
| 304 |
-
"""
|
| 305 |
-
Infer number of speakers by counting distinct 'Speaker X:' tags in the script.
|
| 306 |
-
Robust to 0- or 1-indexed labels and repeated turns.
|
| 307 |
-
Falls back to 1 if none found.
|
| 308 |
-
"""
|
| 309 |
-
import re
|
| 310 |
-
ids = re.findall(r'(?mi)^\s*Speaker\s+(\d+)\s*:', script)
|
| 311 |
-
return len({int(x) for x in ids}) if ids else 1
|
| 312 |
-
|
| 313 |
-
def load_example_scripts(self):
|
| 314 |
-
examples_dir = os.path.join(os.path.dirname(__file__), "text_examples")
|
| 315 |
-
self.example_scripts = []
|
| 316 |
-
self.example_scripts_natural = []
|
| 317 |
-
if not os.path.exists(examples_dir):
|
| 318 |
-
return
|
| 319 |
-
|
| 320 |
-
original_files = [
|
| 321 |
-
"1p_ai_tedtalk.txt",
|
| 322 |
-
"1p_politcal_speech.txt",
|
| 323 |
-
"2p_financeipo_meeting.txt",
|
| 324 |
-
"2p_telehealth_meeting.txt",
|
| 325 |
-
"3p_military_meeting.txt",
|
| 326 |
-
"3p_oil_meeting.txt",
|
| 327 |
-
"4p_gamecreation_meeting.txt",
|
| 328 |
-
"4p_product_meeting.txt"
|
| 329 |
-
]
|
| 330 |
-
|
| 331 |
-
# Gender mapping for each script's speakers
|
| 332 |
-
self.script_speaker_genders = [
|
| 333 |
-
["female"], # AI TED Talk - Rachel
|
| 334 |
-
["neutral"], # Political Speech - generic speaker
|
| 335 |
-
["male", "female"], # Finance IPO - James, Patricia
|
| 336 |
-
["female", "male"], # Telehealth - Jennifer, Tom
|
| 337 |
-
["female", "male", "female"], # Military - Sarah, David, Lisa
|
| 338 |
-
["male", "female", "male"], # Oil - Robert, Lisa, Michael
|
| 339 |
-
["male", "female", "male", "male"], # Game Creation - Alex, Sarah, Marcus, Emma
|
| 340 |
-
["female", "male", "female", "male"] # Product Meeting - Sarah, Marcus, Jennifer, David
|
| 341 |
-
]
|
| 342 |
-
|
| 343 |
-
for txt_file in original_files:
|
| 344 |
-
try:
|
| 345 |
-
with open(os.path.join(examples_dir, txt_file), 'r', encoding='utf-8') as f:
|
| 346 |
-
script_content = f.read().strip()
|
| 347 |
-
if script_content:
|
| 348 |
-
num_speakers = self._infer_num_speakers_from_script(script_content)
|
| 349 |
-
self.example_scripts.append([num_speakers, script_content])
|
| 350 |
-
|
| 351 |
-
natural_file = txt_file.replace('.txt', '_natural.txt')
|
| 352 |
-
natural_path = os.path.join(examples_dir, natural_file)
|
| 353 |
-
if os.path.exists(natural_path):
|
| 354 |
-
with open(natural_path, 'r', encoding='utf-8') as f:
|
| 355 |
-
natural_content = f.read().strip()
|
| 356 |
-
if natural_content:
|
| 357 |
-
num_speakers = self._infer_num_speakers_from_script(natural_content)
|
| 358 |
-
self.example_scripts_natural.append([num_speakers, natural_content])
|
| 359 |
-
else:
|
| 360 |
-
self.example_scripts_natural.append([num_speakers, script_content])
|
| 361 |
-
except Exception as e:
|
| 362 |
-
print(f"Error loading {txt_file}: {e}")
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
def convert_to_16_bit_wav(data):
|
| 366 |
-
if torch.is_tensor(data):
|
| 367 |
-
data = data.detach().cpu().numpy()
|
| 368 |
-
data = np.array(data)
|
| 369 |
-
if np.max(np.abs(data)) > 1.0:
|
| 370 |
-
data = data / np.max(np.abs(data))
|
| 371 |
-
return (data * 32767).astype(np.int16)
|
| 372 |
-
|
| 373 |
-
# Set synthwave theme
|
| 374 |
-
theme = gr.themes.Ocean(
|
| 375 |
-
primary_hue="indigo",
|
| 376 |
-
secondary_hue="fuchsia",
|
| 377 |
-
neutral_hue="slate",
|
| 378 |
-
).set(
|
| 379 |
-
button_large_radius='*radius_sm'
|
| 380 |
-
)
|
| 381 |
-
|
| 382 |
-
def set_working_state(*components, transcript_box=None):
|
| 383 |
-
"""
|
| 384 |
-
Disable all interactive components and show progress in transcript/log box.
|
| 385 |
-
Usage: set_working_state(generate_btn, random_example_btn, transcript_box=log_output)
|
| 386 |
-
"""
|
| 387 |
-
updates = [gr.update(interactive=False) for _ in components]
|
| 388 |
-
if transcript_box is not None:
|
| 389 |
-
updates.append(gr.update(value="Generating... please wait", interactive=False))
|
| 390 |
-
return tuple(updates)
|
| 391 |
-
|
| 392 |
-
def set_idle_state(*components, transcript_box=None):
|
| 393 |
-
"""
|
| 394 |
-
Re-enable all interactive components and transcript/log box.
|
| 395 |
-
Usage: set_idle_state(generate_btn, random_example_btn, transcript_box=log_output)
|
| 396 |
-
"""
|
| 397 |
-
updates = [gr.update(interactive=True) for _ in components]
|
| 398 |
-
if transcript_box is not None:
|
| 399 |
-
updates.append(gr.update(interactive=True))
|
| 400 |
-
return tuple(updates)
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
def create_demo_interface(demo_instance: VibeVoiceDemo):
|
| 404 |
-
custom_css = """ """
|
| 405 |
-
|
| 406 |
-
with gr.Blocks(
|
| 407 |
-
title="VibeVoice - Conference Generator",
|
| 408 |
-
css=custom_css,
|
| 409 |
-
theme=theme,
|
| 410 |
-
) as interface:
|
| 411 |
-
|
| 412 |
-
# Simple image
|
| 413 |
-
gr.HTML("""
|
| 414 |
-
<div style="width: 100%; margin-bottom: 20px;">
|
| 415 |
-
<img src="https://huggingface.co/spaces/ACloudCenter/Conference-Generator-VibeVoice/resolve/main/public/images/banner.png"
|
| 416 |
-
style="width: 100%; height: auto; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.2);"
|
| 417 |
-
alt="Canary-Qwen Transcriber Banner">
|
| 418 |
-
</div>
|
| 419 |
-
""")
|
| 420 |
-
gr.Markdown("## NOTE: The Large model takes significant generation time with limited increase in quality. I recommend trying 1.5 first.")
|
| 421 |
-
|
| 422 |
-
with gr.Tabs():
|
| 423 |
-
with gr.Tab("Generate"):
|
| 424 |
-
gr.Markdown("### Generated Conference")
|
| 425 |
-
complete_audio_output = gr.Audio(
|
| 426 |
-
label="Complete Conference (Download)",
|
| 427 |
-
type="numpy",
|
| 428 |
-
elem_classes="audio-output complete-audio-section",
|
| 429 |
-
autoplay=False,
|
| 430 |
-
show_download_button=True,
|
| 431 |
-
visible=True
|
| 432 |
-
)
|
| 433 |
-
|
| 434 |
-
with gr.Row():
|
| 435 |
-
with gr.Column(scale=1, elem_classes="settings-card"):
|
| 436 |
-
gr.Markdown("### Conference Settings")
|
| 437 |
-
|
| 438 |
-
# Model dropdown
|
| 439 |
-
model_dropdown = gr.Dropdown(
|
| 440 |
-
choices=list(demo_instance.models.keys()),
|
| 441 |
-
value=demo_instance.current_model_name,
|
| 442 |
-
label="Model",
|
| 443 |
-
)
|
| 444 |
-
|
| 445 |
-
num_speakers = gr.Slider(
|
| 446 |
-
minimum=1, maximum=4, value=2, step=1,
|
| 447 |
-
label="Number of Speakers",
|
| 448 |
-
elem_classes="slider-container"
|
| 449 |
-
)
|
| 450 |
-
|
| 451 |
-
gr.Markdown("### Speaker Selection")
|
| 452 |
-
available_speaker_names = list(demo_instance.available_voices.keys())
|
| 453 |
-
default_speakers = ['en-Alice_woman', 'en-Carter_man', 'en-Frank_man', 'en-Maya_woman']
|
| 454 |
-
|
| 455 |
-
speaker_selections = []
|
| 456 |
-
for i in range(4):
|
| 457 |
-
default_value = default_speakers[i] if i < len(default_speakers) else None
|
| 458 |
-
speaker = gr.Dropdown(
|
| 459 |
-
choices=available_speaker_names,
|
| 460 |
-
value=default_value,
|
| 461 |
-
label=f"Speaker {i+1}",
|
| 462 |
-
visible=(i < 2),
|
| 463 |
-
elem_classes="speaker-item"
|
| 464 |
-
)
|
| 465 |
-
speaker_selections.append(speaker)
|
| 466 |
-
|
| 467 |
-
gr.Markdown("### Advanced Settings")
|
| 468 |
-
with gr.Accordion("Generation Parameters", open=False):
|
| 469 |
-
cfg_scale = gr.Slider(
|
| 470 |
-
minimum=1.0, maximum=2.0, value=1.3, step=0.05,
|
| 471 |
-
label="CFG Scale (Guidance Strength)",
|
| 472 |
-
elem_classes="slider-container"
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
with gr.Column(scale=2, elem_classes="generation-card"):
|
| 476 |
-
gr.Markdown("### Script Input")
|
| 477 |
-
script_input = gr.Textbox(
|
| 478 |
-
label="Conversation Script",
|
| 479 |
-
placeholder="Enter your conference script here...",
|
| 480 |
-
lines=12,
|
| 481 |
-
max_lines=20,
|
| 482 |
-
elem_classes="script-input"
|
| 483 |
-
)
|
| 484 |
-
|
| 485 |
-
with gr.Row():
|
| 486 |
-
random_example_btn = gr.Button(
|
| 487 |
-
"Random Example", size="lg",
|
| 488 |
-
variant="secondary", elem_classes="random-btn", scale=1
|
| 489 |
-
)
|
| 490 |
-
generate_btn = gr.Button(
|
| 491 |
-
"🚀 Generate Conference", size="lg",
|
| 492 |
-
variant="primary", elem_classes="generate-btn", scale=2
|
| 493 |
-
)
|
| 494 |
-
|
| 495 |
-
with gr.Row():
|
| 496 |
-
with gr.Column(scale=1):
|
| 497 |
-
gr.Markdown("### Example Scripts")
|
| 498 |
-
with gr.Row():
|
| 499 |
-
use_natural = gr.Checkbox(
|
| 500 |
-
value=True,
|
| 501 |
-
label="Natural talking sounds",
|
| 502 |
-
scale=1
|
| 503 |
-
)
|
| 504 |
-
duration_display = gr.Textbox(
|
| 505 |
-
value="",
|
| 506 |
-
label="Est. Duration",
|
| 507 |
-
interactive=False,
|
| 508 |
-
scale=1
|
| 509 |
-
)
|
| 510 |
-
|
| 511 |
-
example_names = [
|
| 512 |
-
"AI TED Talk",
|
| 513 |
-
"Political Speech",
|
| 514 |
-
"Finance IPO Meeting",
|
| 515 |
-
"Telehealth Meeting",
|
| 516 |
-
"Military Meeting",
|
| 517 |
-
"Oil Meeting",
|
| 518 |
-
"Game Creation Meeting",
|
| 519 |
-
"Product Meeting"
|
| 520 |
-
]
|
| 521 |
-
|
| 522 |
-
example_buttons = []
|
| 523 |
-
with gr.Row():
|
| 524 |
-
for i in range(min(4, len(example_names))):
|
| 525 |
-
btn = gr.Button(example_names[i], size="sm", variant="secondary")
|
| 526 |
-
example_buttons.append(btn)
|
| 527 |
-
|
| 528 |
-
with gr.Row():
|
| 529 |
-
for i in range(4, min(8, len(example_names))):
|
| 530 |
-
btn = gr.Button(example_names[i], size="sm", variant="secondary")
|
| 531 |
-
example_buttons.append(btn)
|
| 532 |
-
|
| 533 |
-
log_output = gr.Textbox(
|
| 534 |
-
label="Generation Log",
|
| 535 |
-
lines=8, max_lines=15,
|
| 536 |
-
interactive=False,
|
| 537 |
-
elem_classes="log-output"
|
| 538 |
-
)
|
| 539 |
-
|
| 540 |
-
def update_speaker_visibility(num_speakers):
|
| 541 |
-
return [gr.update(visible=(i < num_speakers)) for i in range(4)]
|
| 542 |
-
|
| 543 |
-
num_speakers.change(
|
| 544 |
-
fn=update_speaker_visibility,
|
| 545 |
-
inputs=[num_speakers],
|
| 546 |
-
outputs=speaker_selections
|
| 547 |
-
)
|
| 548 |
-
|
| 549 |
-
def update_duration_display(script_text):
|
| 550 |
-
if not script_text or script_text.strip() == "":
|
| 551 |
-
return ""
|
| 552 |
-
|
| 553 |
-
words = script_text.split()
|
| 554 |
-
word_count = len(words)
|
| 555 |
-
wpm = 150
|
| 556 |
-
estimated_minutes = word_count / wpm
|
| 557 |
-
|
| 558 |
-
if estimated_minutes < 1:
|
| 559 |
-
duration_str = f"{int(estimated_minutes * 60)} sec"
|
| 560 |
-
else:
|
| 561 |
-
minutes = int(estimated_minutes)
|
| 562 |
-
seconds = int((estimated_minutes - minutes) * 60)
|
| 563 |
-
if seconds > 0:
|
| 564 |
-
duration_str = f"{minutes}m {seconds}s"
|
| 565 |
-
else:
|
| 566 |
-
duration_str = f"{minutes} min"
|
| 567 |
-
|
| 568 |
-
return f"{word_count} words • ~{duration_str}"
|
| 569 |
-
|
| 570 |
-
script_input.change(
|
| 571 |
-
fn=update_duration_display,
|
| 572 |
-
inputs=[script_input],
|
| 573 |
-
outputs=[duration_display]
|
| 574 |
-
)
|
| 575 |
-
|
| 576 |
-
def generate_podcast_wrapper(model_choice, num_speakers, script, *speakers_and_params):
|
| 577 |
-
try:
|
| 578 |
-
speakers = speakers_and_params[:4]
|
| 579 |
-
cfg_scale_val = speakers_and_params[4]
|
| 580 |
-
audio, log = demo_instance.generate_podcast(
|
| 581 |
-
num_speakers=int(num_speakers),
|
| 582 |
-
script=script,
|
| 583 |
-
speaker_1=speakers[0],
|
| 584 |
-
speaker_2=speakers[1],
|
| 585 |
-
speaker_3=speakers[2],
|
| 586 |
-
speaker_4=speakers[3],
|
| 587 |
-
cfg_scale=cfg_scale_val,
|
| 588 |
-
model_name=model_choice
|
| 589 |
-
)
|
| 590 |
-
return audio, log
|
| 591 |
-
except Exception as e:
|
| 592 |
-
traceback.print_exc()
|
| 593 |
-
return None, f"Error: {str(e)}"
|
| 594 |
-
|
| 595 |
-
def on_generate_start():
|
| 596 |
-
return gr.update(interactive=False), gr.update(interactive=False), gr.update(value="🔄 Initializing generation...\n⏳ This may take up to 2 minutes depending on script length...")
|
| 597 |
-
|
| 598 |
-
def on_generate_complete(audio, log):
|
| 599 |
-
return gr.update(interactive=True), gr.update(interactive=True), audio, log
|
| 600 |
-
|
| 601 |
-
generate_click = generate_btn.click(
|
| 602 |
-
fn=on_generate_start,
|
| 603 |
-
inputs=[],
|
| 604 |
-
outputs=[generate_btn, random_example_btn, log_output],
|
| 605 |
-
queue=False
|
| 606 |
-
).then(
|
| 607 |
-
fn=generate_podcast_wrapper,
|
| 608 |
-
inputs=[model_dropdown, num_speakers, script_input] + speaker_selections + [cfg_scale],
|
| 609 |
-
outputs=[complete_audio_output, log_output],
|
| 610 |
-
queue=True
|
| 611 |
-
).then(
|
| 612 |
-
fn=lambda: (gr.update(interactive=True), gr.update(interactive=True)),
|
| 613 |
-
inputs=[],
|
| 614 |
-
outputs=[generate_btn, random_example_btn],
|
| 615 |
-
queue=False
|
| 616 |
-
)
|
| 617 |
-
|
| 618 |
-
def load_random_example(use_natural_checkbox):
|
| 619 |
-
import random
|
| 620 |
-
scripts_list = demo_instance.example_scripts_natural if use_natural_checkbox else demo_instance.example_scripts
|
| 621 |
-
if scripts_list:
|
| 622 |
-
idx = random.randint(0, len(scripts_list) - 1)
|
| 623 |
-
num_speakers_value, script_value = scripts_list[idx]
|
| 624 |
-
|
| 625 |
-
# Get gender preferences for this script
|
| 626 |
-
genders = demo_instance.script_speaker_genders[idx] if idx < len(demo_instance.script_speaker_genders) else []
|
| 627 |
-
|
| 628 |
-
# Select appropriate voices based on gender
|
| 629 |
-
voice_selections = []
|
| 630 |
-
for i in range(4):
|
| 631 |
-
if i < len(genders):
|
| 632 |
-
gender = genders[i]
|
| 633 |
-
if gender == "male" and demo_instance.male_voices:
|
| 634 |
-
voice = random.choice(demo_instance.male_voices)
|
| 635 |
-
elif gender == "female" and demo_instance.female_voices:
|
| 636 |
-
voice = random.choice(demo_instance.female_voices)
|
| 637 |
-
else:
|
| 638 |
-
# neutral or fallback
|
| 639 |
-
all_voices = list(demo_instance.available_voices.keys())
|
| 640 |
-
voice = random.choice(all_voices) if all_voices else None
|
| 641 |
-
else:
|
| 642 |
-
voice = None
|
| 643 |
-
voice_selections.append(voice)
|
| 644 |
-
|
| 645 |
-
return [num_speakers_value, script_value] + voice_selections
|
| 646 |
-
return [2, "Speaker 0: Welcome to our AI conference demo!\nSpeaker 1: Thanks, excited to be here!"] + [None, None, None, None]
|
| 647 |
-
|
| 648 |
-
random_example_btn.click(
|
| 649 |
-
fn=load_random_example,
|
| 650 |
-
inputs=[use_natural],
|
| 651 |
-
outputs=[num_speakers, script_input] + speaker_selections,
|
| 652 |
-
queue=False
|
| 653 |
-
)
|
| 654 |
-
|
| 655 |
-
def load_specific_example(idx, use_natural_checkbox):
|
| 656 |
-
import random
|
| 657 |
-
scripts_list = demo_instance.example_scripts_natural if use_natural_checkbox else demo_instance.example_scripts
|
| 658 |
-
if idx < len(scripts_list):
|
| 659 |
-
num_speakers_value, script_value = scripts_list[idx]
|
| 660 |
-
# Get gender preferences for this script
|
| 661 |
-
genders = demo_instance.script_speaker_genders[idx] if idx < len(demo_instance.script_speaker_genders) else []
|
| 662 |
-
|
| 663 |
-
# Select appropriate voices based on gender
|
| 664 |
-
voice_selections = []
|
| 665 |
-
for i in range(4):
|
| 666 |
-
if i < len(genders):
|
| 667 |
-
gender = genders[i]
|
| 668 |
-
if gender == "male" and demo_instance.male_voices:
|
| 669 |
-
voice = random.choice(demo_instance.male_voices)
|
| 670 |
-
elif gender == "female" and demo_instance.female_voices:
|
| 671 |
-
voice = random.choice(demo_instance.female_voices)
|
| 672 |
-
else:
|
| 673 |
-
# neutral or fallback
|
| 674 |
-
all_voices = list(demo_instance.available_voices.keys())
|
| 675 |
-
voice = random.choice(all_voices) if all_voices else None
|
| 676 |
-
else:
|
| 677 |
-
voice = None
|
| 678 |
-
voice_selections.append(voice)
|
| 679 |
-
|
| 680 |
-
# Return values for all outputs
|
| 681 |
-
return [num_speakers_value, script_value] + voice_selections
|
| 682 |
-
return [2, ""] + [None, None, None, None]
|
| 683 |
-
|
| 684 |
-
for idx, btn in enumerate(example_buttons):
|
| 685 |
-
btn.click(
|
| 686 |
-
fn=lambda nat, i=idx: load_specific_example(i, nat),
|
| 687 |
-
inputs=[use_natural],
|
| 688 |
-
outputs=[num_speakers, script_input] + speaker_selections,
|
| 689 |
-
queue=False
|
| 690 |
-
)
|
| 691 |
-
|
| 692 |
-
with gr.Tab("Architecture"):
|
| 693 |
-
with gr.Row():
|
| 694 |
-
gr.Markdown('''VibeVoice is a novel framework designed for generating expressive, long-form, multi-speaker conversational audio, "
|
| 695 |
-
"such as conferences, from text. It addresses significant challenges in traditional Text-to-Speech (TTS) systems, particularly "
|
| 696 |
-
"in scalability, speaker consistency, and natural turn-taking. A core innovation of VibeVoice is its use of continuous "
|
| 697 |
-
"speech tokenizers (Acoustic and Semantic) operating at an ultra-low frame rate of 7.5 Hz. These tokenizers efficiently "
|
| 698 |
-
"preserve audio fidelity while significantly boosting computational efficiency for processing long sequences. VibeVoice "
|
| 699 |
-
"employs a next-token diffusion framework, leveraging a Large Language Model (LLM) to understand textual context and "
|
| 700 |
-
"dialogue flow, and a diffusion head to generate high-fidelity acoustic details. The model can synthesize speech up to "
|
| 701 |
-
"90 minutes long with up to 4 distinct speakers, surpassing the typical 1-2 speaker limits of many prior models.''')
|
| 702 |
-
with gr.Row():
|
| 703 |
-
with gr.Column():
|
| 704 |
-
gr.Markdown("## VibeVoice: A Frontier Open-Source Text-to-Speech Model")
|
| 705 |
-
|
| 706 |
-
gr.Markdown("""
|
| 707 |
-
### Overview
|
| 708 |
-
|
| 709 |
-
VibeVoice is a novel framework designed for generating expressive, long-form, multi-speaker conversational audio,
|
| 710 |
-
such as conferences, from text. It addresses significant challenges in traditional Text-to-Speech (TTS) systems,
|
| 711 |
-
particularly in scalability, speaker consistency, and natural turn-taking.
|
| 712 |
-
|
| 713 |
-
### Training Architecture
|
| 714 |
-
|
| 715 |
-
**Transformer-based Large Language Model** integrated with specialized acoustic and semantic tokenizers and a diffusion-based decoding head.
|
| 716 |
-
|
| 717 |
-
**Core Components:**
|
| 718 |
-
- **LLM**: Qwen2.5-1.5B for this release
|
| 719 |
-
- **Acoustic Tokenizer**: Based on a σ-VAE variant with mirror-symmetric encoder-decoder structure (~340M parameters each)
|
| 720 |
-
- 7 stages of modified Transformer blocks
|
| 721 |
-
- Achieves 3200x downsampling from 24kHz input
|
| 722 |
-
- **Semantic Tokenizer**: Encoder mirrors the Acoustic Tokenizer's architecture
|
| 723 |
-
- Trained with an ASR proxy task
|
| 724 |
-
- **Diffusion Head**: Lightweight module (4 layers, ~123M parameters)
|
| 725 |
-
- Conditioned on LLM hidden states
|
| 726 |
-
- Uses DDPM process with Classifier-Free Guidance
|
| 727 |
-
|
| 728 |
-
### Training Details
|
| 729 |
-
|
| 730 |
-
**Context Length**: Trained with curriculum up to 65,536 tokens
|
| 731 |
-
|
| 732 |
-
**Training Stages:**
|
| 733 |
-
1. **Tokenizer Pre-training**: Acoustic and Semantic tokenizers trained separately
|
| 734 |
-
2. **VibeVoice Training**: Frozen tokenizers, only LLM and diffusion head trained
|
| 735 |
-
- Curriculum learning: 4k → 16K → 32K → 64K tokens
|
| 736 |
-
|
| 737 |
-
### Model Variants
|
| 738 |
-
|
| 739 |
-
| Model | Context Length | Generation Length | Parameters |
|
| 740 |
-
|-------|---------------|-------------------|------------|
|
| 741 |
-
| VibeVoice-0.5B-Streaming | - | - | Coming Soon |
|
| 742 |
-
| **VibeVoice-1.5B** | 64K | ~90 min | 2.7B |
|
| 743 |
-
| VibeVoice-Large | 32K | ~45 min | Redacted |
|
| 744 |
-
|
| 745 |
-
### Technical Specifications
|
| 746 |
-
- **Frame Rate**: Ultra-low 7.5 Hz for efficiency
|
| 747 |
-
- **Sample Rate**: 24kHz audio output
|
| 748 |
-
- **Max Duration**: Up to 90 minutes
|
| 749 |
-
- **Speaker Capacity**: 1-4 distinct speakers
|
| 750 |
-
- **Languages**: English and Chinese
|
| 751 |
-
|
| 752 |
-
### Key Innovations
|
| 753 |
-
- Continuous speech tokenizers at ultra-low frame rate
|
| 754 |
-
- Next-token diffusion framework
|
| 755 |
-
- Curriculum learning for long-form generation
|
| 756 |
-
- Multi-speaker consistency without explicit modeling
|
| 757 |
-
""")
|
| 758 |
-
|
| 759 |
-
with gr.Column(scale=2):
|
| 760 |
-
gr.HTML("""
|
| 761 |
-
<div style="text-align: center;">
|
| 762 |
-
<div style="margin: 20px 0;">
|
| 763 |
-
<img src="https://huggingface.co/spaces/ACloudCenter/Conference-Generator-VibeVoice/resolve/main/public/images/diagram.jpg"
|
| 764 |
-
style="max-width: 100%; height: auto; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"
|
| 765 |
-
alt="VibeVoice Architecture Diagram">
|
| 766 |
-
</div>
|
| 767 |
-
<div style="margin: 20px 0;">
|
| 768 |
-
<img src="https://huggingface.co/spaces/ACloudCenter/Conference-Generator-VibeVoice/resolve/main/public/images/chart.png"
|
| 769 |
-
style="max-width: 100%; height: auto; border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"
|
| 770 |
-
alt="VibeVoice Performance Chart">
|
| 771 |
-
</div>
|
| 772 |
-
</div>
|
| 773 |
-
""")
|
| 774 |
-
|
| 775 |
-
return interface
|
| 776 |
-
|
| 777 |
-
def run_demo(
|
| 778 |
-
model_paths: dict = None,
|
| 779 |
-
device: str = "cuda",
|
| 780 |
-
inference_steps: int = 5,
|
| 781 |
-
share: bool = True,
|
| 782 |
-
):
|
| 783 |
-
"""
|
| 784 |
-
model_paths default includes two entries. Replace paths as needed.
|
| 785 |
-
"""
|
| 786 |
-
if model_paths is None:
|
| 787 |
-
model_paths = {
|
| 788 |
-
"VibeVoice-1.5B": "microsoft/VibeVoice-1.5B",
|
| 789 |
-
"VibeVoice-7B": "vibevoice/VibeVoice-7B",
|
| 790 |
-
}
|
| 791 |
-
|
| 792 |
-
set_seed(42)
|
| 793 |
-
demo_instance = VibeVoiceDemo(model_paths, device, inference_steps)
|
| 794 |
-
interface = create_demo_interface(demo_instance)
|
| 795 |
-
interface.queue().launch(
|
| 796 |
-
share=share,
|
| 797 |
-
server_name="0.0.0.0" if share else "127.0.0.1",
|
| 798 |
-
show_error=True,
|
| 799 |
-
show_api=False
|
| 800 |
-
)
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
if __name__ == "__main__":
|
| 805 |
-
run_demo()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
{configs → backend_modal/configs}/qwen2.5_1.5b_64k.json
RENAMED
|
File without changes
|
{configs → backend_modal/configs}/qwen2.5_7b_32k.json
RENAMED
|
File without changes
|
{example → backend_modal/example}/1p_EN2CH.mp4
RENAMED
|
File without changes
|
{example → backend_modal/example}/2p_see_u_again.mp4
RENAMED
|
File without changes
|
{example → backend_modal/example}/4p_climate_45min.mp4
RENAMED
|
File without changes
|
backend_modal/modal_runner.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import numpy as np
|
| 4 |
+
import librosa
|
| 5 |
+
import soundfile as sf
|
| 6 |
+
import torch
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
|
| 9 |
+
# Modal-specific imports
|
| 10 |
+
import modal
|
| 11 |
+
|
| 12 |
+
# Define the Modal Stub
|
| 13 |
+
image = (
|
| 14 |
+
modal.Image.debian_slim(python_version="3.10")
|
| 15 |
+
.pip_install(
|
| 16 |
+
"torch",
|
| 17 |
+
"accelerate==1.6.0",
|
| 18 |
+
"transformers==4.51.3",
|
| 19 |
+
"diffusers",
|
| 20 |
+
"tqdm",
|
| 21 |
+
"numpy",
|
| 22 |
+
"scipy",
|
| 23 |
+
"ml-collections",
|
| 24 |
+
"absl-py",
|
| 25 |
+
"soundfile",
|
| 26 |
+
"librosa",
|
| 27 |
+
"pydub",
|
| 28 |
+
)
|
| 29 |
+
.add_local_dir("./modular", remote_path="/root/modular")
|
| 30 |
+
.add_local_dir("./processor", remote_path="/root/processor")
|
| 31 |
+
.add_local_dir("./voices", remote_path="/root/voices")
|
| 32 |
+
.add_local_dir("./text_examples", remote_path="/root/text_examples")
|
| 33 |
+
.add_local_dir("./schedule", remote_path="/root/schedule")
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
app = modal.App(
|
| 37 |
+
name="vibevoice-generator",
|
| 38 |
+
image=image,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@app.cls(gpu="T4", scaledown_window=300, secrets=[modal.Secret.from_name("hf-secret")])
|
| 43 |
+
class VibeVoiceModel:
|
| 44 |
+
def __init__(self, model_paths: dict = None):
|
| 45 |
+
if model_paths is None:
|
| 46 |
+
self.model_paths = {
|
| 47 |
+
"VibeVoice-1.5B": "microsoft/VibeVoice-1.5B",
|
| 48 |
+
"VibeVoice-7B": "vibevoice/VibeVoice-7B",
|
| 49 |
+
}
|
| 50 |
+
else:
|
| 51 |
+
self.model_paths = model_paths
|
| 52 |
+
|
| 53 |
+
self.device = "cuda"
|
| 54 |
+
self.inference_steps = 5
|
| 55 |
+
|
| 56 |
+
@modal.enter()
|
| 57 |
+
def load_models(self):
|
| 58 |
+
"""
|
| 59 |
+
This method is run once when the container starts.
|
| 60 |
+
It downloads and loads all models onto the GPU.
|
| 61 |
+
"""
|
| 62 |
+
# Project-specific imports are moved here to run inside the container
|
| 63 |
+
from modular.modeling_vibevoice_inference import VibeVoiceForConditionalGenerationInference
|
| 64 |
+
from processor.vibevoice_processor import VibeVoiceProcessor
|
| 65 |
+
|
| 66 |
+
print("Entering container and loading models to GPU...")
|
| 67 |
+
|
| 68 |
+
# Set compiler flags for better performance
|
| 69 |
+
if torch.cuda.is_available() and hasattr(torch, '_inductor'):
|
| 70 |
+
if hasattr(torch._inductor, 'config'):
|
| 71 |
+
torch._inductor.config.conv_1x1_as_mm = True
|
| 72 |
+
torch._inductor.config.coordinate_descent_tuning = True
|
| 73 |
+
torch._inductor.config.epilogue_fusion = False
|
| 74 |
+
torch._inductor.config.coordinate_descent_check_all_directions = True
|
| 75 |
+
|
| 76 |
+
self.models = {}
|
| 77 |
+
self.processors = {}
|
| 78 |
+
|
| 79 |
+
for name, path in self.model_paths.items():
|
| 80 |
+
print(f" - Loading {name} from {path}")
|
| 81 |
+
proc = VibeVoiceProcessor.from_pretrained(path)
|
| 82 |
+
mdl = VibeVoiceForConditionalGenerationInference.from_pretrained(
|
| 83 |
+
path,
|
| 84 |
+
torch_dtype=torch.bfloat16,
|
| 85 |
+
attn_implementation="sdpa"
|
| 86 |
+
).to(self.device)
|
| 87 |
+
mdl.eval()
|
| 88 |
+
print(f" {name} loaded to {self.device}")
|
| 89 |
+
self.processors[name] = proc
|
| 90 |
+
self.models[name] = mdl
|
| 91 |
+
|
| 92 |
+
self.setup_voice_presets()
|
| 93 |
+
print("Model loading complete.")
|
| 94 |
+
|
| 95 |
+
def setup_voice_presets(self):
|
| 96 |
+
self.available_voices = {}
|
| 97 |
+
voices_dir = "/root/voices" # Using remote path from Mount
|
| 98 |
+
if not os.path.exists(voices_dir):
|
| 99 |
+
print(f"Warning: Voices directory not found at {voices_dir}")
|
| 100 |
+
return
|
| 101 |
+
wav_files = [f for f in os.listdir(voices_dir)
|
| 102 |
+
if f.lower().endswith(('.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac'))]
|
| 103 |
+
for wav_file in wav_files:
|
| 104 |
+
name = os.path.splitext(wav_file)[0]
|
| 105 |
+
self.available_voices[name] = os.path.join(voices_dir, wav_file)
|
| 106 |
+
print(f"Voices loaded: {list(self.available_voices.keys())}")
|
| 107 |
+
|
| 108 |
+
def read_audio(self, audio_path: str, target_sr: int = 24000) -> np.ndarray:
|
| 109 |
+
try:
|
| 110 |
+
wav, sr = sf.read(audio_path)
|
| 111 |
+
if len(wav.shape) > 1:
|
| 112 |
+
wav = np.mean(wav, axis=1)
|
| 113 |
+
if sr != target_sr:
|
| 114 |
+
wav = librosa.resample(wav, orig_sr=sr, target_sr=target_sr)
|
| 115 |
+
return wav
|
| 116 |
+
except Exception as e:
|
| 117 |
+
print(f"Error reading audio {audio_path}: {e}")
|
| 118 |
+
return np.array([])
|
| 119 |
+
|
| 120 |
+
@modal.method()
|
| 121 |
+
def generate_podcast(self,
|
| 122 |
+
num_speakers: int,
|
| 123 |
+
script: str,
|
| 124 |
+
model_name: str,
|
| 125 |
+
cfg_scale: float,
|
| 126 |
+
speaker_1: str = None,
|
| 127 |
+
speaker_2: str = None,
|
| 128 |
+
speaker_3: str = None,
|
| 129 |
+
speaker_4: str = None):
|
| 130 |
+
"""
|
| 131 |
+
This is the main inference function that will be called from the Gradio app.
|
| 132 |
+
"""
|
| 133 |
+
try:
|
| 134 |
+
if model_name not in self.models:
|
| 135 |
+
raise ValueError(f"Unknown model: {model_name}")
|
| 136 |
+
|
| 137 |
+
model = self.models[model_name]
|
| 138 |
+
processor = self.processors[model_name]
|
| 139 |
+
model.set_ddpm_inference_steps(num_steps=self.inference_steps)
|
| 140 |
+
|
| 141 |
+
print(f"Generating with model {model_name} on {self.device}")
|
| 142 |
+
|
| 143 |
+
if not script.strip():
|
| 144 |
+
raise ValueError("Error: Please provide a script.")
|
| 145 |
+
|
| 146 |
+
script = script.replace("’", "'")
|
| 147 |
+
|
| 148 |
+
if not 1 <= num_speakers <= 4:
|
| 149 |
+
raise ValueError("Error: Number of speakers must be between 1 and 4.")
|
| 150 |
+
|
| 151 |
+
selected_speakers = [speaker_1, speaker_2, speaker_3, speaker_4][:num_speakers]
|
| 152 |
+
for i, speaker_name in enumerate(selected_speakers):
|
| 153 |
+
if not speaker_name or speaker_name not in self.available_voices:
|
| 154 |
+
raise ValueError(f"Error: Please select a valid speaker for Speaker {i+1}.")
|
| 155 |
+
|
| 156 |
+
log = f"Generating conference with {num_speakers} speakers\n"
|
| 157 |
+
log += f"Model: {model_name}\n"
|
| 158 |
+
log += f"Parameters: CFG Scale={cfg_scale}\n"
|
| 159 |
+
log += f"Speakers: {', '.join(selected_speakers)}\n"
|
| 160 |
+
|
| 161 |
+
voice_samples = []
|
| 162 |
+
for speaker_name in selected_speakers:
|
| 163 |
+
audio_path = self.available_voices[speaker_name]
|
| 164 |
+
audio_data = self.read_audio(audio_path)
|
| 165 |
+
if len(audio_data) == 0:
|
| 166 |
+
raise ValueError(f"Error: Failed to load audio for {speaker_name}")
|
| 167 |
+
voice_samples.append(audio_data)
|
| 168 |
+
|
| 169 |
+
log += f"Loaded {len(voice_samples)} voice samples\n"
|
| 170 |
+
|
| 171 |
+
lines = script.strip().split('\n')
|
| 172 |
+
formatted_script_lines = []
|
| 173 |
+
for line in lines:
|
| 174 |
+
line = line.strip()
|
| 175 |
+
if not line: continue
|
| 176 |
+
if line.startswith('Speaker ') and ':' in line:
|
| 177 |
+
formatted_script_lines.append(line)
|
| 178 |
+
else:
|
| 179 |
+
speaker_id = len(formatted_script_lines) % num_speakers
|
| 180 |
+
formatted_script_lines.append(f"Speaker {speaker_id}: {line}")
|
| 181 |
+
|
| 182 |
+
formatted_script = '\n'.join(formatted_script_lines)
|
| 183 |
+
log += f"Formatted script with {len(formatted_script_lines)} turns\n"
|
| 184 |
+
log += "Processing with VibeVoice...\n"
|
| 185 |
+
|
| 186 |
+
inputs = processor(
|
| 187 |
+
text=[formatted_script],
|
| 188 |
+
voice_samples=[voice_samples],
|
| 189 |
+
padding=True,
|
| 190 |
+
return_tensors="pt",
|
| 191 |
+
return_attention_mask=True,
|
| 192 |
+
).to(self.device)
|
| 193 |
+
|
| 194 |
+
start_time = time.time()
|
| 195 |
+
|
| 196 |
+
with torch.inference_mode():
|
| 197 |
+
outputs = model.generate(
|
| 198 |
+
**inputs,
|
| 199 |
+
max_new_tokens=None,
|
| 200 |
+
cfg_scale=cfg_scale,
|
| 201 |
+
tokenizer=processor.tokenizer,
|
| 202 |
+
generation_config={'do_sample': False},
|
| 203 |
+
verbose=False,
|
| 204 |
+
)
|
| 205 |
+
generation_time = time.time() - start_time
|
| 206 |
+
|
| 207 |
+
if hasattr(outputs, 'speech_outputs') and outputs.speech_outputs[0] is not None:
|
| 208 |
+
audio_tensor = outputs.speech_outputs[0]
|
| 209 |
+
audio = audio_tensor.cpu().float().numpy()
|
| 210 |
+
else:
|
| 211 |
+
raise RuntimeError("Error: No audio was generated by the model.")
|
| 212 |
+
|
| 213 |
+
if audio.ndim > 1:
|
| 214 |
+
audio = audio.squeeze()
|
| 215 |
+
|
| 216 |
+
sample_rate = 24000
|
| 217 |
+
total_duration = len(audio) / sample_rate
|
| 218 |
+
log += f"Generation completed in {generation_time:.2f} seconds\n"
|
| 219 |
+
log += f"Final audio duration: {total_duration:.2f} seconds\n"
|
| 220 |
+
|
| 221 |
+
# Return the raw audio data and sample rate, Gradio will handle the rest
|
| 222 |
+
return (sample_rate, audio), log
|
| 223 |
+
|
| 224 |
+
except Exception as e:
|
| 225 |
+
import traceback
|
| 226 |
+
error_msg = f"An unexpected error occurred on Modal: {str(e)}\n{traceback.format_exc()}"
|
| 227 |
+
print(error_msg)
|
| 228 |
+
# Return a special value or raise an exception that the client can handle
|
| 229 |
+
# For Gradio, returning a log message is often best.
|
| 230 |
+
return None, error_msg
|
{modular → backend_modal/modular}/__init__.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/configuration_vibevoice.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/modeling_vibevoice.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/modeling_vibevoice_inference.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/modular_vibevoice_diffusion_head.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/modular_vibevoice_text_tokenizer.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/modular_vibevoice_tokenizer.py
RENAMED
|
File without changes
|
{modular → backend_modal/modular}/streamer.py
RENAMED
|
File without changes
|
packages.txt → backend_modal/packages.txt
RENAMED
|
File without changes
|
{processor → backend_modal/processor}/__init__.py
RENAMED
|
File without changes
|
{processor → backend_modal/processor}/vibevoice_processor.py
RENAMED
|
File without changes
|
{processor → backend_modal/processor}/vibevoice_tokenizer_processor.py
RENAMED
|
File without changes
|
{schedule → backend_modal/schedule}/__init__.py
RENAMED
|
File without changes
|
{schedule → backend_modal/schedule}/dpm_solver.py
RENAMED
|
File without changes
|
{schedule → backend_modal/schedule}/timestep_sampler.py
RENAMED
|
File without changes
|
{scripts → backend_modal/scripts}/__init__.py
RENAMED
|
File without changes
|
{scripts → backend_modal/scripts}/convert_nnscaler_checkpoint_to_transformers.py
RENAMED
|
File without changes
|
setup_voices.sh → backend_modal/setup_voices.sh
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/1p_ai_tedtalk.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/1p_ai_tedtalk_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/1p_politcal_speech.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/1p_politcal_speech_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/2p_financeipo_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/2p_financeipo_meeting_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/2p_telehealth_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/2p_telehealth_meeting_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/3p_military_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/3p_military_meeting_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/3p_oil_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/3p_oil_meeting_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/4p_gamecreation_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/4p_gamecreation_meeting_natural.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/4p_product_meeting.txt
RENAMED
|
File without changes
|
{text_examples → backend_modal/text_examples}/4p_product_meeting_natural.txt
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Alice_woman.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Alice_woman_bgm.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Carter_man.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Frank_man.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Maya_woman.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/en-Yasser_man.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/in-Samuel_man.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/zh-Anchen_man_bgm.wav
RENAMED
|
File without changes
|
{voices → backend_modal/voices}/zh-Bowen_man.wav
RENAMED
|
File without changes
|