ollieollie commited on
Commit
0b3e025
·
verified ·
1 Parent(s): 2127efd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -65
app.py CHANGED
@@ -1,90 +1,94 @@
1
  import random
2
  import numpy as np
3
  import torch
4
- from chatterbox.src.chatterbox.tts import ChatterboxTTS
5
  import gradio as gr
6
- import spaces # <<< IMPORT THIS
7
 
8
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
9
- print(f"🚀 Running on device: {DEVICE}") # Good to log this
10
-
11
- # Global model variable to load only once if not using gr.State for model object
12
- # global_model = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def set_seed(seed: int):
15
  torch.manual_seed(seed)
16
- if DEVICE == "cuda": # Only seed cuda if available
17
  torch.cuda.manual_seed(seed)
18
  torch.cuda.manual_seed_all(seed)
19
  random.seed(seed)
20
  np.random.seed(seed)
21
 
22
- # Optional: Decorate model loading if it's done on first use within a GPU function
23
- # However, it's often better to load the model once globally or manage with gr.State
24
- # and ensure the function CALLING the model is decorated.
25
-
26
- @spaces.GPU # <<< ADD THIS DECORATOR
27
- def generate(model_obj, text, audio_prompt_path, exaggeration, temperature, seed_num, cfgw):
28
- # It's better to load the model once, perhaps when the gr.State is initialized
29
- # or globally, rather than checking `model_obj is None` on every call.
30
- # For ZeroGPU, the decorated function handles the GPU context.
31
- # Let's assume model_obj is passed correctly and is already on DEVICE
32
- # or will be moved to DEVICE by ChatterboxTTS internally.
33
-
34
- if model_obj is None:
35
- print("Model is None, attempting to load...")
36
- # This load should ideally happen on DEVICE and be efficient.
37
- # If ChatterboxTTS.from_pretrained(DEVICE) is slow,
38
- # this will happen inside the GPU-allocated time.
39
- model_obj = ChatterboxTTS.from_pretrained(DEVICE)
40
- print(f"Model loaded on device: {model_obj.device if hasattr(model_obj, 'device') else 'unknown'}")
41
-
42
-
43
- if seed_num != 0:
44
- set_seed(int(seed_num))
45
-
46
- print(f"Generating audio for text: '{text}' on device: {DEVICE}")
47
- wav = model_obj.generate(
48
- text,
49
- audio_prompt_path=audio_prompt_path,
50
- exaggeration=exaggeration,
51
- temperature=temperature,
52
- cfg_weight=cfgw,
53
  )
54
  print("Audio generation complete.")
55
- # The model state is passed back out, which is correct for gr.State
56
- return (model_obj, (model_obj.sr, wav.squeeze(0).numpy()))
57
 
58
 
59
  with gr.Blocks() as demo:
60
- # To ensure model loads on app start and uses DEVICE correctly:
61
- # Pre-load the model here if you want it loaded once globally for the Space instance.
62
- # However, with gr.State(None) and loading in `generate`,
63
- # the first user hitting "Generate" will trigger the load.
64
- # This is fine if `ChatterboxTTS.from_pretrained(DEVICE)` correctly uses the GPU
65
- # within the @spaces.GPU decorated `generate` function.
66
-
67
- # For better clarity on model loading with ZeroGPU:
68
- # Consider a dedicated function for loading the model that's called to initialize gr.State,
69
- # or ensure the first call to `generate` handles it robustly within the GPU context.
70
- # The current approach of loading if model_state is None within `generate` is okay
71
- # as long as `generate` itself is decorated.
72
-
73
- model_state = gr.State(None)
74
 
75
  with gr.Row():
76
- # ... (rest of your UI code is fine) ...
77
  with gr.Column():
78
  text = gr.Textbox(value="What does the fox say?", label="Text to synthesize")
79
  ref_wav = gr.Audio(sources=["upload", "microphone"], type="filepath", label="Reference Audio File", value="https://storage.googleapis.com/chatterbox-demo-samples/prompts/wav7604828.wav")
80
  exaggeration = gr.Slider(0.25, 2, step=.05, label="Exaggeration (Neutral = 0.5, extreme values can be unstable)", value=.5)
81
  cfg_weight = gr.Slider(0.2, 1, step=.05, label="CFG/Pace", value=0.5)
82
 
83
-
84
  with gr.Accordion("More options", open=False):
85
  seed_num = gr.Number(value=0, label="Random seed (0 for random)")
86
  temp = gr.Slider(0.05, 5, step=.05, label="temperature", value=.8)
87
-
88
 
89
  run_btn = gr.Button("Generate", variant="primary")
90
 
@@ -92,22 +96,21 @@ with gr.Blocks() as demo:
92
  audio_output = gr.Audio(label="Output Audio")
93
 
94
  run_btn.click(
95
- fn=generate,
96
  inputs=[
97
- model_state,
98
  text,
99
  ref_wav,
100
  exaggeration,
 
101
  temp,
102
  seed_num,
103
  cfg_weight,
104
  ],
105
- outputs=[model_state, audio_output],
106
  )
107
 
108
- # The share=True in launch() will give a UserWarning on Spaces, it's not needed.
109
- # Hugging Face Spaces provides the public link automatically.
110
  demo.queue(
111
- max_size=50,
112
- default_concurrency_limit=1, # Good for single model instance on GPU
113
- ).launch() # Removed share=True
 
1
  import random
2
  import numpy as np
3
  import torch
4
+ from chatterbox.src.chatterbox.tts import ChatterboxTTS # Assuming this path is correct
5
  import gradio as gr
6
+ import spaces
7
 
8
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
9
+ print(f"🚀 Running on device: {DEVICE}")
10
+
11
+ # --- Global Model Initialization ---
12
+ # Load the model once when the application starts.
13
+ # This model will be accessible by the @spaces.GPU decorated function.
14
+ MODEL = None
15
+
16
+ def get_or_load_model():
17
+ global MODEL
18
+ if MODEL is None:
19
+ print("Global MODEL is None, loading...")
20
+ try:
21
+ MODEL = ChatterboxTTS.from_pretrained(DEVICE)
22
+ # Ensure model is on the correct device if not handled by from_pretrained
23
+ if DEVICE == "cuda" and hasattr(MODEL, 'to'):
24
+ MODEL.to(DEVICE)
25
+ print(f"Global MODEL loaded. Device: {DEVICE}")
26
+ if hasattr(MODEL, 'device'): # If the model object has a device attribute
27
+ print(f"Model internal device attribute: {MODEL.device}")
28
+ except Exception as e:
29
+ print(f"Error loading global model: {e}")
30
+ raise
31
+ return MODEL
32
+
33
+ # Attempt to load the model at startup.
34
+ # If this fails, the app will likely fail to start, which is informative.
35
+ try:
36
+ get_or_load_model()
37
+ except Exception as e:
38
+ # Handle critical model loading failure if necessary, or let it propagate
39
+ print(f"CRITICAL: Failed to load model on startup. Error: {e}")
40
+ # You might want to display an error in Gradio if this happens,
41
+ # but for now, a print is fine for debugging.
42
 
43
  def set_seed(seed: int):
44
  torch.manual_seed(seed)
45
+ if DEVICE == "cuda":
46
  torch.cuda.manual_seed(seed)
47
  torch.cuda.manual_seed_all(seed)
48
  random.seed(seed)
49
  np.random.seed(seed)
50
 
51
+ @spaces.GPU # Your GPU-accelerated function
52
+ def generate_tts_audio(text_input, audio_prompt_path_input, exaggeration_input, pace_input, temperature_input, seed_num_input, cfgw_input):
53
+ current_model = get_or_load_model() # Access the global model
54
+
55
+ if current_model is None:
56
+ # This should ideally not happen if startup loading was successful
57
+ # Or, it indicates an issue with the global model pattern in this specific env.
58
+ raise RuntimeError("Model could not be loaded or accessed.")
59
+
60
+ if seed_num_input != 0:
61
+ set_seed(int(seed_num_input))
62
+
63
+ print(f"Generating audio for text: '{text_input}'")
64
+ wav = current_model.generate(
65
+ text_input,
66
+ audio_prompt_path=audio_prompt_path_input,
67
+ exaggeration=exaggeration_input,
68
+ pace=pace_input,
69
+ temperature=temperature_input,
70
+ cfg_weight=cfgw_input,
 
 
 
 
 
 
 
 
 
 
 
71
  )
72
  print("Audio generation complete.")
73
+ # ONLY return pickleable data
74
+ return (current_model.sr, wav.squeeze(0).numpy())
75
 
76
 
77
  with gr.Blocks() as demo:
78
+ # No gr.State needed for the model object if it's managed globally
79
+ # and not passed back and forth.
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  with gr.Row():
 
82
  with gr.Column():
83
  text = gr.Textbox(value="What does the fox say?", label="Text to synthesize")
84
  ref_wav = gr.Audio(sources=["upload", "microphone"], type="filepath", label="Reference Audio File", value="https://storage.googleapis.com/chatterbox-demo-samples/prompts/wav7604828.wav")
85
  exaggeration = gr.Slider(0.25, 2, step=.05, label="Exaggeration (Neutral = 0.5, extreme values can be unstable)", value=.5)
86
  cfg_weight = gr.Slider(0.2, 1, step=.05, label="CFG/Pace", value=0.5)
87
 
 
88
  with gr.Accordion("More options", open=False):
89
  seed_num = gr.Number(value=0, label="Random seed (0 for random)")
90
  temp = gr.Slider(0.05, 5, step=.05, label="temperature", value=.8)
91
+ pace = gr.Slider(0.8, 1.2, step=.01, label="pace", value=1)
92
 
93
  run_btn = gr.Button("Generate", variant="primary")
94
 
 
96
  audio_output = gr.Audio(label="Output Audio")
97
 
98
  run_btn.click(
99
+ fn=generate_tts_audio, # Use the new function name
100
  inputs=[
101
+ # model_state, # Removed: model is now global
102
  text,
103
  ref_wav,
104
  exaggeration,
105
+ pace,
106
  temp,
107
  seed_num,
108
  cfg_weight,
109
  ],
110
+ outputs=[audio_output], # Only outputting the audio data
111
  )
112
 
 
 
113
  demo.queue(
114
+ max_size=50,
115
+ default_concurrency_limit=1, # Important for a single global model
116
+ ).launch() # share=True is not needed and causes a warning on Spaces