File size: 12,017 Bytes
0c0737d
afd6946
 
0c0737d
afd6946
ebb49bc
0c0737d
 
afd6946
 
 
 
 
9de60e0
afd6946
ebb49bc
afd6946
 
 
136a3d3
0c0737d
 
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9de60e0
136a3d3
afd6946
 
 
 
136a3d3
 
afd6946
 
 
 
 
 
ebb49bc
 
036af98
afd6946
 
 
 
 
 
 
 
 
036af98
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56f6bc2
ebb49bc
afd6946
 
 
 
 
 
 
 
ebb49bc
 
afd6946
 
 
 
 
0c0737d
afd6946
0c0737d
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb49bc
afd6946
036af98
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebb49bc
0c0737d
afd6946
 
0c0737d
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c0737d
afd6946
 
 
 
 
 
 
bc55770
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036af98
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc55770
afd6946
 
 
 
 
 
 
 
 
 
0c0737d
afd6946
 
036af98
 
afd6946
 
 
 
036af98
afd6946
 
0c0737d
 
afd6946
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
036af98
afd6946
 
 
 
 
 
036af98
afd6946
 
 
 
 
0c0737d
afd6946
0c0737d
afd6946
 
 
 
 
 
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import gradio as gr
import torch
import numpy as np
import tempfile
import time
import warnings
warnings.filterwarnings("ignore")

# HTML with inline CSS for white background and black text
html_with_css = """
<!DOCTYPE html>
<html>
<head>
<style>
body, .gradio-container {
    background: white !important;
    color: #333333 !important;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    margin: 0;
    padding: 20px;
}

.header {
    text-align: center;
    padding: 2rem;
    background: linear-gradient(135deg, #4F46E5 0%, #7C3AED 100%);
    border-radius: 16px;
    margin-bottom: 2rem;
    color: white;
}

.header h1 {
    font-size: 2.5em;
    margin: 0 0 0.5rem 0;
    font-weight: 700;
}

/* BLACK TEXT ON WHITE - MOST IMPORTANT */
textarea {
    background: white !important;
    border: 2px solid #4F46E5 !important;
    border-radius: 12px !important;
    color: #000000 !important; /* Pure black text */
    padding: 1rem !important;
    font-size: 16px !important;
    width: 100% !important;
    min-height: 120px !important;
    font-family: monospace !important;
}

textarea::placeholder {
    color: #666666 !important;
}

button {
    padding: 0.75rem 1.5rem !important;
    border-radius: 10px !important;
    font-weight: 600 !important;
    margin: 0.5rem !important;
    cursor: pointer !important;
}

.primary-btn {
    background: linear-gradient(135deg, #4F46E5 0%, #7C3AED 100%) !important;
    border: none !important;
    color: white !important;
}

.secondary-btn {
    background: white !important;
    border: 2px solid #D1D5DB !important;
    color: #374151 !important;
}

.card {
    background: white;
    border: 1px solid #E5E7EB;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 1rem;
}

.status-success {
    background: #DCFCE7;
    border: 1px solid #86EFAC;
    border-left: 4px solid #10B981;
    color: #065F46;
    padding: 1rem;
    border-radius: 8px;
    margin: 1rem 0;
}

.status-info {
    background: #DBEAFE;
    border: 1px solid #93C5FD;
    border-left: 4px solid #3B82F6;
    color: #1E40AF;
    padding: 1rem;
    border-radius: 8px;
    margin: 1rem 0;
}
</style>
</head>
<body>
<div class="header">
    <h1>🎡 Text-to-Speech</h1>
    <p>Convert text to speech with smaller AI model</p>
</div>
</body>
</html>
"""

print("πŸš€ Starting TTS System...")

# Try to load a SMALLER TTS model that fits in free tier
def load_small_tts_model():
    """Load a smaller TTS model that fits in Hugging Face Spaces free tier"""
    try:
        print("πŸ“₯ Loading smaller TTS model...")
        
        # Option 1: Try Coqui TTS (smaller footprint)
        try:
            from TTS.api import TTS
            # Using a small multilingual model
            tts_model = TTS(model_name="tts_models/multilingual/multi-dataset/xtts_v2", progress_bar=False)
            print("βœ… Loaded Coqui XTTS model")
            return ("coqui", tts_model)
        except ImportError:
            print("  Coqui TTS not available")
        
        # Option 2: Try SpeechT5 (smaller than VibeVoice)
        try:
            from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
            import torch
            
            processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
            model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
            vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
            
            # Use CPU to save memory
            model = model.to("cpu")
            vocoder = vocoder.to("cpu")
            
            print("βœ… Loaded SpeechT5 model (CPU)")
            return ("speecht5", {"processor": processor, "model": model, "vocoder": vocoder})
        except Exception as e:
            print(f"  SpeechT5 failed: {e}")
        
        # Option 3: Try Bark (small and fast)
        try:
            from transformers import AutoProcessor, BarkModel
            import torch
            
            processor = AutoProcessor.from_pretrained("suno/bark-small")
            model = BarkModel.from_pretrained("suno/bark-small")
            
            # Use CPU
            model = model.to("cpu")
            
            print("βœ… Loaded Bark model (CPU)")
            return ("bark", {"processor": processor, "model": model})
        except Exception as e:
            print(f"  Bark failed: {e}")
        
        print("⚠️ No small TTS model loaded, using gTTS fallback")
        return ("gtts", None)
        
    except Exception as e:
        print(f"❌ Error loading models: {e}")
        return ("gtts", None)

# Load model
model_type, tts_model = load_small_tts_model()

def generate_with_model(text, speed=1.0):
    """Generate speech using the loaded model"""
    try:
        if not text or not text.strip():
            return None, None
        
        print(f"πŸ”Š Generating: {text[:50]}...")
        
        if model_type == "coqui" and tts_model:
            # Coqui TTS
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
                tts_model.tts_to_file(text=text, file_path=f.name)
                return f.name, 24000
        
        elif model_type == "speecht5" and tts_model:
            # SpeechT5
            processor = tts_model["processor"]
            model = tts_model["model"]
            vocoder = tts_model["vocoder"]
            
            inputs = processor(text=text, return_tensors="pt")
            
            with torch.no_grad():
                speech = model.generate_speech(inputs["input_ids"], vocoder=vocoder)
            
            audio = speech.numpy()
            
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
                import scipy.io.wavfile
                scipy.io.wavfile.write(f.name, 16000, audio.astype(np.float32))
                return f.name, 16000
        
        elif model_type == "bark" and tts_model:
            # Bark
            processor = tts_model["processor"]
            model = tts_model["model"]
            
            inputs = processor(text, return_tensors="pt")
            
            with torch.no_grad():
                audio_array = model.generate(**inputs)
                audio_array = audio_array.cpu().numpy().squeeze()
            
            with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
                import scipy.io.wavfile
                scipy.io.wavfile.write(f.name, 24000, audio_array.astype(np.float32))
                return f.name, 24000
        
        return None, None
        
    except Exception as e:
        print(f"❌ Model generation error: {e}")
        return None, None

def generate_with_gtts(text):
    """Fallback to gTTS (requires internet but works well)"""
    try:
        from gtts import gTTS
        
        with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
            tts = gTTS(text=text, lang='en', slow=False)
            tts.save(f.name)
            return f.name, "gTTS"
    except Exception as e:
        print(f"❌ gTTS error: {e}")
        return None, None

def create_basic_audio(text):
    """Create basic audio as last resort"""
    import scipy.io.wavfile
    
    duration = min(len(text) * 0.05, 5)
    sr = 24000
    t = np.linspace(0, duration, int(sr * duration))
    
    # Create varied audio
    base_freq = 220
    audio = np.zeros_like(t)
    
    for i, char in enumerate(text[:20]):
        freq = base_freq + (ord(char) % 300)
        amp = 0.3 / (i + 1)
        audio += amp * np.sin(2 * np.pi * freq * t)
    
    envelope = np.exp(-2 * t) * (1 - np.exp(-8 * t))
    audio *= envelope
    
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
        scipy.io.wavfile.write(f.name, sr, audio.astype(np.float32))
        return f.name, "Basic"

# Create the interface
with gr.Blocks() as demo:
    # Add CSS as HTML
    gr.HTML(html_with_css)
    
    # Main layout
    with gr.Row():
        # Input column
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“ Enter Text")
            text_input = gr.Textbox(
                label="",
                placeholder="Type your text here... (Black text on white background)",
                lines=5
            )
            
            with gr.Row():
                speed = gr.Slider(
                    minimum=0.5,
                    maximum=2.0,
                    value=1.0,
                    step=0.1,
                    label="Speed"
                )
            
            with gr.Row():
                generate_btn = gr.Button("✨ Generate Speech", variant="primary")
                clear_btn = gr.Button("Clear", variant="secondary")
        
        # Output column
        with gr.Column(scale=1):
            gr.Markdown("### 🎧 Audio Output")
            audio_output = gr.Audio(type="filepath", label="")
            status = gr.HTML("""
            <div class="status-info">
                <strong>Ready</strong><br>
                Enter text and click Generate Speech
            </div>
            """)
    
    # Model info
    gr.Markdown("### ℹ️ System Information")
    
    if model_type == "coqui":
        gr.Markdown("βœ… **Model**: Coqui XTTS (Multilingual)")
    elif model_type == "speecht5":
        gr.Markdown("βœ… **Model**: Microsoft SpeechT5")
    elif model_type == "bark":
        gr.Markdown("βœ… **Model**: Suno Bark")
    elif model_type == "gtts":
        gr.Markdown("⚠️ **Model**: gTTS (Fallback - requires internet)")
    else:
        gr.Markdown("⚠️ **Model**: Basic audio generation")
    
    # Examples
    gr.Markdown("### πŸ’‘ Examples")
    gr.Examples(
        examples=[
            ["Hello! Welcome to the text-to-speech system."],
            ["This is a demonstration of AI speech synthesis."],
            ["The quick brown fox jumps over the lazy dog."],
            ["Artificial intelligence is transforming technology."]
        ],
        inputs=text_input,
        label="Click to try:"
    )
    
    # Event handlers
    def process_text(text, speed_val):
        if not text or not text.strip():
            return None, """
            <div class="status-info">
                <strong>⚠️ Please enter text</strong><br>
                Type something in the text box above
            </div>
            """
        
        print(f"Processing: {text[:50]}...")
        
        # Try model first
        audio_file, sr = generate_with_model(text, speed_val)
        source = "AI Model"
        
        # Fallback to gTTS
        if audio_file is None:
            audio_file, source = generate_with_gtts(text)
        
        # Last resort: basic audio
        if audio_file is None:
            audio_file, source = create_basic_audio(text)
        
        if audio_file:
            message = f"""
            <div class="status-success">
                <strong>βœ… Speech Generated!</strong><br>
                Source: {source} β€’ Characters: {len(text)}<br>
                Speed: {speed_val}x
            </div>
            """
            return audio_file, message
        else:
            return None, """
            <div class="status-info">
                <strong>❌ Failed to generate</strong><br>
                Please try different text
            </div>
            """
    
    def clear_all():
        return "", None, """
        <div class="status-info">
            <strong>Cleared</strong><br>
            Ready for new text input
        </div>
        """
    
    # Connect buttons
    generate_btn.click(
        process_text,
        [text_input, speed],
        [audio_output, status]
    )
    
    clear_btn.click(
        clear_all,
        [],
        [text_input, audio_output, status]
    )

# Launch the app
if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True,
        quiet=True
    )