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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Upload the fixed model.py to HuggingFace
|
| 3 |
+
Run this script to update your model on HuggingFace
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from huggingface_hub import HfApi
|
| 7 |
+
import os
|
| 8 |
+
|
| 9 |
+
# Fixed model.py content with lazy loading
|
| 10 |
+
MODEL_PY_CONTENT = '''import sys
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 14 |
+
sys.path.append(current_dir)
|
| 15 |
+
|
| 16 |
+
from transformers import PreTrainedModel, PretrainedConfig, AutoConfig
|
| 17 |
+
import torch
|
| 18 |
+
import numpy as np
|
| 19 |
+
from f5_tts.infer.utils_infer import (
|
| 20 |
+
infer_process,
|
| 21 |
+
load_model,
|
| 22 |
+
load_vocoder,
|
| 23 |
+
preprocess_ref_audio_text,
|
| 24 |
+
)
|
| 25 |
+
from f5_tts.model import DiT
|
| 26 |
+
import soundfile as sf
|
| 27 |
+
import io
|
| 28 |
+
from pydub import AudioSegment, silence
|
| 29 |
+
from huggingface_hub import hf_hub_download
|
| 30 |
+
from safetensors.torch import load_file
|
| 31 |
+
import os
|
| 32 |
+
|
| 33 |
+
class INF5Config(PretrainedConfig):
|
| 34 |
+
model_type = "inf5"
|
| 35 |
+
|
| 36 |
+
def __init__(self, ckpt_path: str = "checkpoints/model_best.pt", vocab_path: str = "checkpoints/vocab.txt",
|
| 37 |
+
speed: float = 1.0, remove_sil: bool = True, **kwargs):
|
| 38 |
+
super().__init__(**kwargs)
|
| 39 |
+
self.ckpt_path = ckpt_path
|
| 40 |
+
self.vocab_path = vocab_path
|
| 41 |
+
self.speed = speed
|
| 42 |
+
self.remove_sil = remove_sil
|
| 43 |
+
|
| 44 |
+
class INF5Model(PreTrainedModel):
|
| 45 |
+
config_class = INF5Config
|
| 46 |
+
|
| 47 |
+
def __init__(self, config):
|
| 48 |
+
super().__init__(config)
|
| 49 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 50 |
+
self.device = device
|
| 51 |
+
|
| 52 |
+
# CRITICAL FIX: Don't load vocoder/model in __init__
|
| 53 |
+
# Use lazy loading instead to avoid meta tensor issues
|
| 54 |
+
self._vocoder = None
|
| 55 |
+
self._ema_model = None
|
| 56 |
+
|
| 57 |
+
# Store vocab path for lazy loading
|
| 58 |
+
try:
|
| 59 |
+
self._vocab_path = hf_hub_download(config.name_or_path, filename="checkpoints/vocab.txt")
|
| 60 |
+
except:
|
| 61 |
+
self._vocab_path = "checkpoints/vocab.txt"
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def vocoder(self):
|
| 65 |
+
"""Lazy load vocoder only when needed (avoids meta tensor issues)"""
|
| 66 |
+
if self._vocoder is None:
|
| 67 |
+
print("⚙️ Loading vocoder on-demand...")
|
| 68 |
+
# Force regular device context (not meta)
|
| 69 |
+
with torch.device('cpu'):
|
| 70 |
+
self._vocoder = load_vocoder(vocoder_name="vocos", is_local=False, device='cpu')
|
| 71 |
+
|
| 72 |
+
# Move to target device if not CPU
|
| 73 |
+
if self.device.type != 'cpu':
|
| 74 |
+
self._vocoder = self._vocoder.to(self.device)
|
| 75 |
+
|
| 76 |
+
self._vocoder = self._vocoder.eval()
|
| 77 |
+
print(f"✅ Vocoder loaded on {self.device}")
|
| 78 |
+
|
| 79 |
+
return self._vocoder
|
| 80 |
+
|
| 81 |
+
@property
|
| 82 |
+
def ema_model(self):
|
| 83 |
+
"""Lazy load ema_model only when needed"""
|
| 84 |
+
if self._ema_model is None:
|
| 85 |
+
print("⚙️ Loading EMA model on-demand...")
|
| 86 |
+
self._ema_model = load_model(
|
| 87 |
+
DiT,
|
| 88 |
+
dict(dim=1024, depth=22, heads=16, ff_mult=2, text_dim=512, conv_layers=4),
|
| 89 |
+
mel_spec_type="vocos",
|
| 90 |
+
vocab_file=self._vocab_path,
|
| 91 |
+
device=self.device
|
| 92 |
+
)
|
| 93 |
+
self._ema_model = self._ema_model.eval()
|
| 94 |
+
print(f"✅ EMA model loaded on {self.device}")
|
| 95 |
+
|
| 96 |
+
return self._ema_model
|
| 97 |
+
|
| 98 |
+
def forward(self, text: str, ref_audio_path: str, ref_text: str, speed: float = None):
|
| 99 |
+
"""
|
| 100 |
+
Generate speech given a reference audio & text input.
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
text (str): The text to be synthesized.
|
| 104 |
+
ref_audio_path (str): Path to the reference audio file.
|
| 105 |
+
ref_text (str): The reference text.
|
| 106 |
+
speed (float): Override speed (optional)
|
| 107 |
+
|
| 108 |
+
Returns:
|
| 109 |
+
np.array: Generated waveform.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
if not os.path.exists(ref_audio_path):
|
| 113 |
+
raise FileNotFoundError(f"Reference audio file {ref_audio_path} not found.")
|
| 114 |
+
|
| 115 |
+
# Use config speed if not provided
|
| 116 |
+
if speed is None:
|
| 117 |
+
speed = self.config.speed
|
| 118 |
+
|
| 119 |
+
# Load reference audio & text
|
| 120 |
+
ref_audio, ref_text = preprocess_ref_audio_text(ref_audio_path, ref_text)
|
| 121 |
+
|
| 122 |
+
# Access properties to trigger lazy loading
|
| 123 |
+
ema_model = self.ema_model
|
| 124 |
+
vocoder = self.vocoder
|
| 125 |
+
|
| 126 |
+
# Ensure on correct device
|
| 127 |
+
ema_model.to(self.device)
|
| 128 |
+
vocoder.to(self.device)
|
| 129 |
+
|
| 130 |
+
# Perform inference
|
| 131 |
+
audio, final_sample_rate, _ = infer_process(
|
| 132 |
+
ref_audio,
|
| 133 |
+
ref_text,
|
| 134 |
+
text,
|
| 135 |
+
ema_model,
|
| 136 |
+
vocoder,
|
| 137 |
+
mel_spec_type="vocos",
|
| 138 |
+
speed=speed,
|
| 139 |
+
device=self.device,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# Convert to pydub format and remove silence if needed
|
| 143 |
+
buffer = io.BytesIO()
|
| 144 |
+
sf.write(buffer, audio, samplerate=24000, format="WAV")
|
| 145 |
+
buffer.seek(0)
|
| 146 |
+
audio_segment = AudioSegment.from_file(buffer, format="wav")
|
| 147 |
+
|
| 148 |
+
if self.config.remove_sil:
|
| 149 |
+
non_silent_segs = silence.split_on_silence(
|
| 150 |
+
audio_segment,
|
| 151 |
+
min_silence_len=1000,
|
| 152 |
+
silence_thresh=-50,
|
| 153 |
+
keep_silence=500,
|
| 154 |
+
seek_step=10,
|
| 155 |
+
)
|
| 156 |
+
non_silent_wave = sum(non_silent_segs, AudioSegment.silent(duration=0))
|
| 157 |
+
audio_segment = non_silent_wave
|
| 158 |
+
|
| 159 |
+
# Normalize loudness
|
| 160 |
+
target_dBFS = -20.0
|
| 161 |
+
change_in_dBFS = target_dBFS - audio_segment.dBFS
|
| 162 |
+
audio_segment = audio_segment.apply_gain(change_in_dBFS)
|
| 163 |
+
|
| 164 |
+
return np.array(audio_segment.get_array_of_samples())
|
| 165 |
+
'''
|
| 166 |
+
|
| 167 |
+
def upload_fixed_model():
|
| 168 |
+
"""Upload the fixed model.py to HuggingFace"""
|
| 169 |
+
|
| 170 |
+
repo_id = "svp19/INF5" # Your repo
|
| 171 |
+
|
| 172 |
+
# Save the fixed model.py locally
|
| 173 |
+
with open("model.py", "w", encoding="utf-8") as f:
|
| 174 |
+
f.write(MODEL_PY_CONTENT)
|
| 175 |
+
|
| 176 |
+
print(f"📝 Saved fixed model.py locally")
|
| 177 |
+
|
| 178 |
+
# Upload to HuggingFace
|
| 179 |
+
api = HfApi()
|
| 180 |
+
|
| 181 |
+
try:
|
| 182 |
+
api.upload_file(
|
| 183 |
+
path_or_fileobj="model.py",
|
| 184 |
+
path_in_repo="model.py",
|
| 185 |
+
repo_id=repo_id,
|
| 186 |
+
repo_type="model",
|
| 187 |
+
commit_message="Fix: Use lazy loading for vocoder to avoid meta tensor issues"
|
| 188 |
+
)
|
| 189 |
+
print(f"✅ Successfully uploaded fixed model.py to {repo_id}")
|
| 190 |
+
print(f"🔗 https://huggingface.co/{repo_id}/blob/main/model.py")
|
| 191 |
+
|
| 192 |
+
except Exception as e:
|
| 193 |
+
print(f"❌ Upload failed: {e}")
|
| 194 |
+
raise
|
| 195 |
+
|
| 196 |
+
# Clean up
|
| 197 |
+
os.remove("model.py")
|
| 198 |
+
print("🧹 Cleaned up local file")
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
print("="*60)
|
| 202 |
+
print("🚀 Uploading Fixed model.py to HuggingFace")
|
| 203 |
+
print("="*60)
|
| 204 |
+
upload_fixed_model()
|
| 205 |
+
print("\n✨ Done! Now redeploy your Cerebrium app")
|
| 206 |
+
print(" Run: cerebrium deploy --no-cache")
|