File size: 10,457 Bytes
6ef63ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
"""
πŸ—½ Jerome Voice Generator
Type anything β†’ hear Jerome say it with his thick New York accent.
Uses Edge TTS for base speech + RVC for voice conversion.
"""

import os
import sys
import subprocess
import asyncio
import tempfile
import shutil
import logging
import gradio as gr
import edge_tts
from huggingface_hub import hf_hub_download

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ─── Configuration ───────────────────────────────────────────
MODEL_REPO = "khobster/jerome"
MODEL_FILE = "jerome_100e_1000s.pth"
INDEX_FILE = "jerome.index"
APPLIO_DIR = "/app/applio"
MODEL_DIR = "/app/models"
TEMP_DIR = "/app/temp"

# Edge TTS voices (male voices that work well as RVC input)
TTS_VOICES = {
    "Guy (US)": "en-US-GuyNeural",
    "Andrew (US)": "en-US-AndrewNeural",
    "Eric (US)": "en-US-EricNeural",
    "Christopher (US)": "en-US-ChristopherNeural",
    "Roger (US)": "en-US-RogerNeural",
    "Ryan (UK)": "en-GB-RyanNeural",
}

DEFAULT_VOICE = "en-US-GuyNeural"

# ─── Setup ───────────────────────────────────────────────────

def setup():
    """Download model files and verify Applio installation."""
    os.makedirs(MODEL_DIR, exist_ok=True)
    os.makedirs(TEMP_DIR, exist_ok=True)
    
    # Download RVC model from HuggingFace
    logger.info("Downloading Jerome's RVC model...")
    model_path = hf_hub_download(
        repo_id=MODEL_REPO,
        filename=MODEL_FILE,
        local_dir=MODEL_DIR,
    )
    logger.info(f"Model downloaded: {model_path}")
    
    index_path = hf_hub_download(
        repo_id=MODEL_REPO,
        filename=INDEX_FILE,
        local_dir=MODEL_DIR,
    )
    logger.info(f"Index downloaded: {index_path}")
    
    # Verify Applio is available
    if not os.path.exists(os.path.join(APPLIO_DIR, "core.py")):
        raise RuntimeError("Applio not found! Check Dockerfile.")
    
    return model_path, index_path

# ─── TTS Engine ──────────────────────────────────────────────

async def generate_base_tts(text: str, voice: str, output_path: str):
    """Generate base speech using Edge TTS."""
    communicate = edge_tts.Communicate(text, voice)
    await communicate.save(output_path)
    logger.info(f"Base TTS generated: {output_path}")

# ─── RVC Conversion ─────────────────────────────────────────

def convert_voice(input_path: str, output_path: str, model_path: str, 
                  index_path: str, f0_shift: int = 0, index_rate: float = 0.75):
    """Convert voice using Applio's RVC inference."""
    
    cmd = [
        sys.executable, os.path.join(APPLIO_DIR, "core.py"), "infer",
        "--input_path", input_path,
        "--output_path", output_path,
        "--pth_path", model_path,
        "--index_path", index_path,
        "--f0_method", "rmvpe",
        "--pitch", str(f0_shift),
        "--index_rate", str(index_rate),
        "--filter_radius", "3",
        "--volume_envelope", "0.25",
        "--protect", "0.33",
        "--hop_length", "128",
        "--split_audio", "False",
        "--f0_autotune", "False",
        "--clean_audio", "True",
        "--clean_strength", "0.5",
        "--export_format", "WAV",
        "--embedder_model", "contentvec",
    ]
    
    logger.info(f"Running RVC inference...")
    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        timeout=120,
        cwd=APPLIO_DIR,
        env={**os.environ, "PYTHONPATH": f"{APPLIO_DIR}:{APPLIO_DIR}/rvc/train"}
    )
    
    if result.returncode != 0:
        logger.error(f"RVC STDOUT: {result.stdout}")
        logger.error(f"RVC STDERR: {result.stderr}")
        raise RuntimeError(f"RVC inference failed: {result.stderr[-500:]}")
    
    if not os.path.exists(output_path):
        # Check if output was saved elsewhere
        logger.warning(f"Output not at expected path, searching...")
        raise RuntimeError("RVC did not produce output file")
    
    logger.info(f"Voice conversion complete: {output_path}")

# ─── Main Pipeline ───────────────────────────────────────────

def text_to_jerome(text: str, voice_name: str = "Guy (US)", 
                   pitch_shift: int = 0, index_rate: float = 0.75):
    """Full pipeline: Text β†’ Base TTS β†’ RVC β†’ Jerome's voice"""
    
    if not text.strip():
        return None
    
    voice = TTS_VOICES.get(voice_name, DEFAULT_VOICE)
    
    # Create temp files
    base_path = os.path.join(TEMP_DIR, "base_tts.wav")
    output_path = os.path.join(TEMP_DIR, "jerome_output.wav")
    
    # Clean up old files
    for p in [base_path, output_path]:
        if os.path.exists(p):
            os.remove(p)
    
    try:
        # Step 1: Generate base TTS
        asyncio.run(generate_base_tts(text, voice, base_path))
        
        if not os.path.exists(base_path):
            return None
        
        # Step 2: Convert to Jerome's voice
        convert_voice(
            input_path=base_path,
            output_path=output_path,
            model_path=os.path.join(MODEL_DIR, MODEL_FILE),
            index_path=os.path.join(MODEL_DIR, INDEX_FILE),
            f0_shift=pitch_shift,
            index_rate=index_rate,
        )
        
        if os.path.exists(output_path):
            return output_path
        else:
            return base_path  # Fallback to base TTS
            
    except Exception as e:
        logger.error(f"Pipeline error: {e}")
        # Return base TTS as fallback
        if os.path.exists(base_path):
            return base_path
        return None

# ─── Gradio UI ───────────────────────────────────────────────

def build_ui():
    """Build the Gradio interface."""
    
    with gr.Blocks(
        title="Jerome Voice Generator",
        theme=gr.themes.Base(
            primary_hue=gr.themes.colors.orange,
            secondary_hue=gr.themes.colors.amber,
            neutral_hue=gr.themes.colors.gray,
            font=["Inter", "system-ui", "sans-serif"],
        ),
        css="""
        .main-title { 
            text-align: center; 
            font-size: 2.5em; 
            font-weight: 800;
            margin-bottom: 0;
            background: linear-gradient(135deg, #ff6b35, #f7c948);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .subtitle {
            text-align: center;
            color: #666;
            font-size: 1.1em;
            margin-top: 0;
        }
        footer { display: none !important; }
        """
    ) as demo:
        
        gr.HTML("""
            <h1 class="main-title">πŸ—½ Jerome Voice Generator</h1>
            <p class="subtitle">Type anything and hear Jerome say it β€” straight outta New York</p>
        """)
        
        with gr.Row():
            with gr.Column(scale=3):
                text_input = gr.Textbox(
                    label="What should Jerome say?",
                    placeholder="Yo, let me tell you somethin' about this game right here...",
                    lines=3,
                    max_lines=10,
                )
                
                generate_btn = gr.Button(
                    "🎀 Make Jerome Say It",
                    variant="primary",
                    size="lg",
                )
            
            with gr.Column(scale=2):
                audio_output = gr.Audio(
                    label="Jerome's Voice",
                    type="filepath",
                )
        
        with gr.Accordion("βš™οΈ Advanced Settings", open=False):
            with gr.Row():
                voice_select = gr.Dropdown(
                    choices=list(TTS_VOICES.keys()),
                    value="Guy (US)",
                    label="Base Voice (input to RVC)",
                    info="The base TTS voice that gets converted to Jerome's voice"
                )
                pitch_shift = gr.Slider(
                    minimum=-12, maximum=12, value=0, step=1,
                    label="Pitch Shift (semitones)",
                    info="Adjust if the output pitch sounds off"
                )
                index_rate = gr.Slider(
                    minimum=0, maximum=1, value=0.75, step=0.05,
                    label="Index Rate",
                    info="How much to use the voice index (higher = more like training data)"
                )
        
        # Example phrases
        gr.Examples(
            examples=[
                ["Yo what's good everybody, welcome back to the show!"],
                ["Let me tell you somethin', this team ain't got what it takes to win a championship."],
                ["I'm walkin' here! You believe this guy? Unbelievable."],
                ["Listen, the pizza in this city? Fuggedaboutit. Best in the world, no question."],
                ["Alright folks, that's gonna wrap it up for tonight. Thanks for tuning in!"],
            ],
            inputs=text_input,
        )
        
        generate_btn.click(
            fn=text_to_jerome,
            inputs=[text_input, voice_select, pitch_shift, index_rate],
            outputs=audio_output,
        )
        
        # Also generate on Enter
        text_input.submit(
            fn=text_to_jerome,
            inputs=[text_input, voice_select, pitch_shift, index_rate],
            outputs=audio_output,
        )
    
    return demo

# ─── Launch ──────────────────────────────────────────────────

if __name__ == "__main__":
    logger.info("πŸ—½ Starting Jerome Voice Generator...")
    
    # Setup: download model
    model_path, index_path = setup()
    logger.info(f"Model ready: {model_path}")
    logger.info(f"Index ready: {index_path}")
    
    # Build and launch UI
    demo = build_ui()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
    )