Shifterr commited on
Commit
4fdf3ce
·
verified ·
1 Parent(s): 479b63b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -44
app.py CHANGED
@@ -1,88 +1,146 @@
1
  import gradio as gr
2
  from TTS.api import TTS
3
  import os
4
- import numpy as np
5
- import scipy.io.wavfile
6
 
7
- # 1. Load Model
8
- device = "cuda" if os.environ.get("CUDA_VISIBLE_DEVICES") else "cpu"
 
 
 
 
 
9
  print(f"Loading XTTS v2 on {device}...")
10
 
11
  try:
12
- tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=(device == "cuda"))
 
13
  except Exception as e:
14
  print(f"Error loading model: {e}")
15
  tts = None
16
 
17
- def clone_voice(text, audio_data):
18
  """
19
- audio_data comes in as a tuple: (sample_rate, numpy_array)
20
- We must manually save it to a WAV file for XTTS to read.
 
 
 
 
 
 
 
21
  """
22
  print(f"--- NEW REQUEST ---")
23
-
24
- if audio_data is None:
25
- return None, "Error: No audio provided. Please record or upload."
26
-
27
- # Unpack the raw audio data from Gradio
28
- sample_rate, audio_array = audio_data
29
- print(f"Received Audio: Rate={sample_rate}, Shape={audio_array.shape}")
30
 
31
  if not tts:
32
- return None, "Error: Model failed to load."
 
 
 
33
 
34
- # 2. MANUALLY SAVE THE WAV FILE
35
- # This bypasses the 'filepath=None' bug by doing it ourselves.
36
- temp_wav_path = "temp_reference.wav"
37
  output_path = "output.wav"
38
 
39
  try:
40
- scipy.io.wavfile.write(temp_wav_path, sample_rate, audio_array)
41
- print(f"Saved reference audio to {temp_wav_path}")
42
- except Exception as e:
43
- return None, f"Error saving file: {e}"
44
-
45
- try:
46
- # Generate audio using our manually saved file
47
  tts.tts_to_file(
48
  text=text,
49
  file_path=output_path,
50
- speaker_wav=temp_wav_path,
51
- language="en"
 
 
 
52
  )
53
- return output_path, "Success"
54
 
55
  except Exception as e:
56
- print(f"CRASH: {e}")
57
- return None, f"Error: {str(e)}"
 
58
 
59
  # 3. UI Setup
60
- with gr.Blocks() as demo:
61
- gr.Markdown("# PLOT Voice Engine (Numpy Mode)")
 
 
 
 
 
 
 
 
 
 
62
 
63
  with gr.Row():
64
- with gr.Column():
65
- text_input = gr.Textbox(label="Text to Speak", value="This is a test of the cloning system.")
 
 
 
 
 
66
 
67
- # THE FIX: Restore gr.Audio but use type="numpy"
68
- # This brings back the Microphone + Upload UI
69
  audio_input = gr.Audio(
70
  label="Reference Voice (Record or Upload)",
71
- type="numpy", # <--- Receives raw data, not a path
72
  sources=["microphone", "upload"]
73
  )
74
 
75
- submit_btn = gr.Button("Generate Voice", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
- with gr.Column():
78
- audio_output = gr.Audio(label="Result")
79
- status_output = gr.Textbox(label="Status")
 
80
 
81
  submit_btn.click(
82
  fn=clone_voice,
83
- inputs=[text_input, audio_input],
 
 
 
 
 
 
 
84
  outputs=[audio_output, status_output]
85
  )
86
 
87
  if __name__ == "__main__":
88
- demo.launch(ssr_mode=False)
 
1
  import gradio as gr
2
  from TTS.api import TTS
3
  import os
4
+ import torch
 
5
 
6
+ # 1. Environment & License Agreement
7
+ # XTTS requires agreeing to the terms.
8
+ os.environ["COQUI_TOS_AGREED"] = "1"
9
+
10
+ # 2. Load Model
11
+ # Check if CUDA is available
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
  print(f"Loading XTTS v2 on {device}...")
14
 
15
  try:
16
+ # Load the model with gpu support if available
17
+ tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device)
18
  except Exception as e:
19
  print(f"Error loading model: {e}")
20
  tts = None
21
 
22
+ def clone_voice(text, audio_filepath, language, speed, temperature, repetition_penalty):
23
  """
24
+ Generate speech using XTTS v2.
25
+
26
+ Args:
27
+ text: The text to speak.
28
+ audio_filepath: Path to the reference audio (wav/mp3/etc).
29
+ language: Language code (e.g., "en").
30
+ speed: Speed factor (default 1.0).
31
+ temperature: Sampling temperature (lower = more deterministic).
32
+ repetition_penalty: Penalty to avoid loops.
33
  """
34
  print(f"--- NEW REQUEST ---")
35
+ print(f"Text: {text[:50]}...")
36
+ print(f"Reference: {audio_filepath}")
37
+ print(f"Params: Speed={speed}, Temp={temperature}, Rep={repetition_penalty}")
 
 
 
 
38
 
39
  if not tts:
40
+ return None, "Error: Model failed to load at startup."
41
+
42
+ if not audio_filepath:
43
+ return None, "Error: No audio file provided. Please record or upload a voice sample."
44
 
 
 
 
45
  output_path = "output.wav"
46
 
47
  try:
48
+ # XTTS generation
 
 
 
 
 
 
49
  tts.tts_to_file(
50
  text=text,
51
  file_path=output_path,
52
+ speaker_wav=audio_filepath,
53
+ language=language,
54
+ speed=speed,
55
+ temperature=temperature,
56
+ repetition_penalty=repetition_penalty
57
  )
58
+ return output_path, f"Success! Generated on {device}."
59
 
60
  except Exception as e:
61
+ error_msg = str(e)
62
+ print(f"GENERATION ERROR: {error_msg}")
63
+ return None, f"Error: {error_msg}"
64
 
65
  # 3. UI Setup
66
+ # Defined languages for XTTS v2
67
+ LANGUAGES = [
68
+ "en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "ko", "hu"
69
+ ]
70
+
71
+ with gr.Blocks(title="PLOT Voice Engine Pro") as demo:
72
+ gr.Markdown(
73
+ """
74
+ # 🎙️ PLOT Voice Engine (XTTS v2)
75
+ **Advanced Voice Cloning** - improved stability and control.
76
+ """
77
+ )
78
 
79
  with gr.Row():
80
+ with gr.Column(scale=1):
81
+ # Input Section
82
+ text_input = gr.Textbox(
83
+ label="Text to Speak",
84
+ value="Hello! This is a test of the enhanced voice cloning system.",
85
+ lines=3
86
+ )
87
 
88
+ # Using 'filepath' handles un/packing of audio automatically
 
89
  audio_input = gr.Audio(
90
  label="Reference Voice (Record or Upload)",
91
+ type="filepath", # <--- Crucial fix: let Gradio handle files
92
  sources=["microphone", "upload"]
93
  )
94
 
95
+ with gr.Accordion("Advanced Settings", open=True):
96
+ language_dropdown = gr.Dropdown(
97
+ label="Language",
98
+ choices=LANGUAGES,
99
+ value="en"
100
+ )
101
+ speed_slider = gr.Slider(
102
+ label="Speed",
103
+ minimum=0.5,
104
+ maximum=2.0,
105
+ value=1.0,
106
+ step=0.1
107
+ )
108
+ temp_slider = gr.Slider(
109
+ label="Temperature (Stability)",
110
+ minimum=0.01,
111
+ maximum=1.0,
112
+ value=0.75,
113
+ step=0.05,
114
+ info="Lower = more stable, Higher = more expressive."
115
+ )
116
+ rep_slider = gr.Slider(
117
+ label="Repetition Penalty",
118
+ minimum=1.0,
119
+ maximum=10.0,
120
+ value=5.0,
121
+ step=0.1,
122
+ info="Increase if the model repeats itself."
123
+ )
124
+
125
+ submit_btn = gr.Button("🚀 Generate Voice", variant="primary", size="lg")
126
 
127
+ with gr.Column(scale=1):
128
+ # Output Section
129
+ audio_output = gr.Audio(label="Generated Audio", type="filepath", interactive=False)
130
+ status_output = gr.Textbox(label="Status Log", interactive=False)
131
 
132
  submit_btn.click(
133
  fn=clone_voice,
134
+ inputs=[
135
+ text_input,
136
+ audio_input,
137
+ language_dropdown,
138
+ speed_slider,
139
+ temp_slider,
140
+ rep_slider
141
+ ],
142
  outputs=[audio_output, status_output]
143
  )
144
 
145
  if __name__ == "__main__":
146
+ demo.launch(ssr_mode=False)