baconnier commited on
Commit
b57d4bf
·
verified ·
1 Parent(s): 10d0be8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -56
app.py CHANGED
@@ -7,16 +7,16 @@ from huggingface_hub import snapshot_download
7
  from dotenv import load_dotenv
8
  load_dotenv()
9
 
10
- # Check if CUDA is available
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
12
 
13
- print("Loading SNAC model...")
14
  snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
15
  snac_model = snac_model.to(device)
16
 
17
  model_name = "canopylabs/3b-fr-ft-research_release"
18
 
19
- # Download only model config and safetensors
20
  snapshot_download(
21
  repo_id=model_name,
22
  allow_patterns=[
@@ -41,24 +41,24 @@ snapshot_download(
41
  model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
42
  model.to(device)
43
  tokenizer = AutoTokenizer.from_pretrained(model_name)
44
- print(f"Orpheus model loaded to {device}")
45
 
46
- # Process text prompt
47
  def process_prompt(prompt, voice, tokenizer, device):
48
  prompt = f"{voice}: {prompt}"
49
  input_ids = tokenizer(prompt, return_tensors="pt").input_ids
50
 
51
- start_token = torch.tensor([[128259]], dtype=torch.int64) # Start of human
52
- end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # End of text, End of human
53
 
54
- modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Text EOT EOH
55
 
56
- # No padding needed for single input
57
  attention_mask = torch.ones_like(modified_input_ids)
58
 
59
  return modified_input_ids.to(device), attention_mask.to(device)
60
 
61
- # Parse output tokens to audio
62
  def parse_output(generated_ids):
63
  token_to_find = 128257
64
  token_to_remove = 128258
@@ -84,11 +84,11 @@ def parse_output(generated_ids):
84
  trimmed_row = [t - 128266 for t in trimmed_row]
85
  code_lists.append(trimmed_row)
86
 
87
- return code_lists[0] # Return just the first one for single sample
88
 
89
- # Redistribute codes for audio generation
90
  def redistribute_codes(code_list, snac_model):
91
- device = next(snac_model.parameters()).device # Get the device of SNAC model
92
 
93
  layer_1 = []
94
  layer_2 = []
@@ -102,7 +102,7 @@ def redistribute_codes(code_list, snac_model):
102
  layer_3.append(code_list[7*i+5]-(5*4096))
103
  layer_3.append(code_list[7*i+6]-(6*4096))
104
 
105
- # Move tensors to the same device as the SNAC model
106
  codes = [
107
  torch.tensor(layer_1, device=device).unsqueeze(0),
108
  torch.tensor(layer_2, device=device).unsqueeze(0),
@@ -110,19 +110,19 @@ def redistribute_codes(code_list, snac_model):
110
  ]
111
 
112
  audio_hat = snac_model.decode(codes)
113
- return audio_hat.detach().squeeze().cpu().numpy() # Always return CPU numpy array
114
 
115
- # Main generation function
116
  @spaces.GPU()
117
  def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
118
  if not text.strip():
119
  return None
120
 
121
  try:
122
- progress(0.1, "Processing text...")
123
  input_ids, attention_mask = process_prompt(text, voice, tokenizer, device)
124
 
125
- progress(0.3, "Generating speech tokens...")
126
  with torch.no_grad():
127
  generated_ids = model.generate(
128
  input_ids=input_ids,
@@ -136,89 +136,89 @@ def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new
136
  eos_token_id=128258,
137
  )
138
 
139
- progress(0.6, "Processing speech tokens...")
140
  code_list = parse_output(generated_ids)
141
 
142
- progress(0.8, "Converting to audio...")
143
  audio_samples = redistribute_codes(code_list, snac_model)
144
 
145
- return (24000, audio_samples) # Return sample rate and audio
146
  except Exception as e:
147
- print(f"Error generating speech: {e}")
148
  return None
149
 
150
- # Examples for the UI
151
  examples = [
152
- ["Hey there my name is Tara, <chuckle> and I'm a speech generation model that can sound like a person.", "tara", 0.6, 0.95, 1.1, 1200],
153
- ["I've also been taught to understand and produce paralinguistic things <sigh> like sighing, or <laugh> laughing, or <yawn> yawning!", "dan", 0.7, 0.95, 1.1, 1200],
154
- ["I live in San Francisco, and have, uhm let's see, 3 billion 7 hundred ... <gasp> well, lets just say a lot of parameters.", "leah", 0.6, 0.9, 1.2, 1200],
155
- ["Sometimes when I talk too much, I need to <cough> excuse myself. <sniffle> The weather has been quite cold lately.", "leo", 0.65, 0.9, 1.1, 1200],
156
- ["Public speaking can be challenging. <groan> But with enough practice, anyone can become better at it.", "jess", 0.7, 0.95, 1.1, 1200],
157
- ["The hike was exhausting but the view from the top was absolutely breathtaking! <sigh> It was totally worth it.", "mia", 0.65, 0.9, 1.15, 1200],
158
- ["Did you hear that joke? <laugh> I couldn't stop laughing when I first heard it. <chuckle> It's still funny.", "zac", 0.7, 0.95, 1.1, 1200],
159
- ["After running the marathon, I was so tired <yawn> and needed a long rest. <sigh> But I felt accomplished.", "zoe", 0.6, 0.95, 1.1, 1200]
160
  ]
161
 
162
- # Available voices
163
  VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]
164
 
165
- # Available Emotive Tags
166
  EMOTIVE_TAGS = ["`<laugh>`", "`<chuckle>`", "`<sigh>`", "`<cough>`", "`<sniffle>`", "`<groan>`", "`<yawn>`", "`<gasp>`"]
167
 
168
- # Create Gradio interface
169
  with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
170
  gr.Markdown(f"""
171
  # 🎵 [Orpheus French Text-to-Speech](https://github.com/canopyai/Orpheus-TTS)
172
- Enter your text below and hear it converted to natural-sounding speech with the Orpheus TTS model.
173
 
174
- ## Tips for better prompts:
175
- - Add paralinguistic elements like {", ".join(EMOTIVE_TAGS)} or `uhm` for more human-like speech.
176
- - Longer text prompts generally work better than very short phrases
177
- - Increasing `repetition_penalty` and `temperature` makes the model speak faster.
178
  """)
179
  with gr.Row():
180
  with gr.Column(scale=3):
181
  text_input = gr.Textbox(
182
- label="Text to speak",
183
- placeholder="Enter your text here...",
184
  lines=5
185
  )
186
  voice = gr.Dropdown(
187
  choices=VOICES,
188
  value="tara",
189
- label="Voice"
190
  )
191
 
192
- with gr.Accordion("Advanced Settings", open=False):
193
  temperature = gr.Slider(
194
  minimum=0.1, maximum=1.5, value=0.6, step=0.05,
195
- label="Temperature",
196
- info="Higher values (0.7-1.0) create more expressive but less stable speech"
197
  )
198
  top_p = gr.Slider(
199
  minimum=0.1, maximum=1.0, value=0.95, step=0.05,
200
  label="Top P",
201
- info="Nucleus sampling threshold"
202
  )
203
  repetition_penalty = gr.Slider(
204
  minimum=1.0, maximum=2.0, value=1.1, step=0.05,
205
- label="Repetition Penalty",
206
- info="Higher values discourage repetitive patterns"
207
  )
208
  max_new_tokens = gr.Slider(
209
  minimum=100, maximum=2000, value=1200, step=100,
210
- label="Max Length",
211
- info="Maximum length of generated audio (in tokens)"
212
  )
213
 
214
  with gr.Row():
215
- submit_btn = gr.Button("Generate Speech", variant="primary")
216
- clear_btn = gr.Button("Clear")
217
 
218
  with gr.Column(scale=2):
219
- audio_output = gr.Audio(label="Generated Speech", type="numpy")
220
 
221
- # Set up examples
222
  gr.Examples(
223
  examples=examples,
224
  inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
@@ -227,7 +227,7 @@ with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
227
  cache_examples=True,
228
  )
229
 
230
- # Set up event handlers
231
  submit_btn.click(
232
  fn=generate_speech,
233
  inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
@@ -240,6 +240,6 @@ with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
240
  outputs=[text_input, audio_output]
241
  )
242
 
243
- # Launch the app
244
  if __name__ == "__main__":
245
  demo.queue().launch(share=False, ssr_mode=False)
 
7
  from dotenv import load_dotenv
8
  load_dotenv()
9
 
10
+ # Vérifier si CUDA est disponible
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
12
 
13
+ print("Chargement du modèle SNAC...")
14
  snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
15
  snac_model = snac_model.to(device)
16
 
17
  model_name = "canopylabs/3b-fr-ft-research_release"
18
 
19
+ # Télécharger uniquement la configuration du modèle et les safetensors
20
  snapshot_download(
21
  repo_id=model_name,
22
  allow_patterns=[
 
41
  model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
42
  model.to(device)
43
  tokenizer = AutoTokenizer.from_pretrained(model_name)
44
+ print(f"Modèle Orpheus chargé sur {device}")
45
 
46
+ # Traiter le texte d'entrée
47
  def process_prompt(prompt, voice, tokenizer, device):
48
  prompt = f"{voice}: {prompt}"
49
  input_ids = tokenizer(prompt, return_tensors="pt").input_ids
50
 
51
+ start_token = torch.tensor([[128259]], dtype=torch.int64) # Début humain
52
+ end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # Fin du texte, Fin humain
53
 
54
+ modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Texte EOT EOH
55
 
56
+ # Pas besoin de padding pour une seule entrée
57
  attention_mask = torch.ones_like(modified_input_ids)
58
 
59
  return modified_input_ids.to(device), attention_mask.to(device)
60
 
61
+ # Analyser les tokens de sortie en audio
62
  def parse_output(generated_ids):
63
  token_to_find = 128257
64
  token_to_remove = 128258
 
84
  trimmed_row = [t - 128266 for t in trimmed_row]
85
  code_lists.append(trimmed_row)
86
 
87
+ return code_lists[0] # Retourner uniquement le premier pour un seul échantillon
88
 
89
+ # Redistribuer les codes pour la génération audio
90
  def redistribute_codes(code_list, snac_model):
91
+ device = next(snac_model.parameters()).device # Obtenir le périphérique du modèle SNAC
92
 
93
  layer_1 = []
94
  layer_2 = []
 
102
  layer_3.append(code_list[7*i+5]-(5*4096))
103
  layer_3.append(code_list[7*i+6]-(6*4096))
104
 
105
+ # Déplacer les tenseurs vers le même périphérique que le modèle SNAC
106
  codes = [
107
  torch.tensor(layer_1, device=device).unsqueeze(0),
108
  torch.tensor(layer_2, device=device).unsqueeze(0),
 
110
  ]
111
 
112
  audio_hat = snac_model.decode(codes)
113
+ return audio_hat.detach().squeeze().cpu().numpy() # Toujours retourner un tableau numpy CPU
114
 
115
+ # Fonction principale de génération
116
  @spaces.GPU()
117
  def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
118
  if not text.strip():
119
  return None
120
 
121
  try:
122
+ progress(0.1, "Traitement du texte...")
123
  input_ids, attention_mask = process_prompt(text, voice, tokenizer, device)
124
 
125
+ progress(0.3, "Génération des tokens de parole...")
126
  with torch.no_grad():
127
  generated_ids = model.generate(
128
  input_ids=input_ids,
 
136
  eos_token_id=128258,
137
  )
138
 
139
+ progress(0.6, "Traitement des tokens de parole...")
140
  code_list = parse_output(generated_ids)
141
 
142
+ progress(0.8, "Conversion en audio...")
143
  audio_samples = redistribute_codes(code_list, snac_model)
144
 
145
+ return (24000, audio_samples) # Retourner le taux d'échantillonnage et l'audio
146
  except Exception as e:
147
+ print(f"Erreur lors de la génération de la parole: {e}")
148
  return None
149
 
150
+ # Exemples pour l'interface utilisateur
151
  examples = [
152
+ ["Bonjour, je m'appelle Tara, <chuckle> et je suis un modèle de génération de parole qui peut ressembler à une personne.", "tara", 0.6, 0.95, 1.1, 1200],
153
+ ["On m'a aussi appris à comprendre et à produire des éléments paralinguistiques <sigh> comme soupirer, ou <laugh> rire, ou <yawn> bâiller !", "dan", 0.7, 0.95, 1.1, 1200],
154
+ ["J'habite à San Francisco, et j'ai, euh voyons voir, 3 milliards 7 cents... <gasp> bon, disons simplement beaucoup de paramètres.", "leah", 0.6, 0.9, 1.2, 1200],
155
+ ["Parfois, quand je parle trop, j'ai besoin de <cough> m'excuser. <sniffle> Le temps a été assez froid dernièrement.", "leo", 0.65, 0.9, 1.1, 1200],
156
+ ["Parler en public peut être difficile. <groan> Mais avec suffisamment de pratique, n'importe qui peut s'améliorer.", "jess", 0.7, 0.95, 1.1, 1200],
157
+ ["La randonnée était épuisante mais la vue depuis le sommet était absolument à couper le souffle ! <sigh> Ça valait totalement le coup.", "mia", 0.65, 0.9, 1.15, 1200],
158
+ ["Tu as entendu cette blague ? <laugh> Je n'ai pas pu m'arrêter de rire quand je l'ai entendue pour la première fois. <chuckle> C'est toujours drôle.", "zac", 0.7, 0.95, 1.1, 1200],
159
+ ["Après avoir couru le marathon, j'étais tellement fatigué <yawn> et j'avais besoin d'un long repos. <sigh> Mais je me sentais accompli.", "zoe", 0.6, 0.95, 1.1, 1200]
160
  ]
161
 
162
+ # Voix disponibles
163
  VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]
164
 
165
+ # Balises émotives disponibles
166
  EMOTIVE_TAGS = ["`<laugh>`", "`<chuckle>`", "`<sigh>`", "`<cough>`", "`<sniffle>`", "`<groan>`", "`<yawn>`", "`<gasp>`"]
167
 
168
+ # Créer l'interface Gradio
169
  with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
170
  gr.Markdown(f"""
171
  # 🎵 [Orpheus French Text-to-Speech](https://github.com/canopyai/Orpheus-TTS)
172
+ Saisissez votre texte ci-dessous et écoutez-le transformé en parole naturelle avec le modèle Orpheus TTS.
173
 
174
+ ## Conseils pour de meilleurs résultats:
175
+ - Ajoutez des éléments paralinguistiques comme {", ".join(EMOTIVE_TAGS)} ou `euh` pour une parole plus humaine.
176
+ - Les textes plus longs fonctionnent généralement mieux que les phrases très courtes
177
+ - Augmenter `repetition_penalty` et `temperature` fait parler le modèle plus rapidement.
178
  """)
179
  with gr.Row():
180
  with gr.Column(scale=3):
181
  text_input = gr.Textbox(
182
+ label="Texte à prononcer",
183
+ placeholder="Entrez votre texte ici...",
184
  lines=5
185
  )
186
  voice = gr.Dropdown(
187
  choices=VOICES,
188
  value="tara",
189
+ label="Voix"
190
  )
191
 
192
+ with gr.Accordion("Paramètres avancés", open=False):
193
  temperature = gr.Slider(
194
  minimum=0.1, maximum=1.5, value=0.6, step=0.05,
195
+ label="Température",
196
+ info="Des valeurs plus élevées (0.7-1.0) créent une parole plus expressive mais moins stable"
197
  )
198
  top_p = gr.Slider(
199
  minimum=0.1, maximum=1.0, value=0.95, step=0.05,
200
  label="Top P",
201
+ info="Seuil d'échantillonnage du noyau"
202
  )
203
  repetition_penalty = gr.Slider(
204
  minimum=1.0, maximum=2.0, value=1.1, step=0.05,
205
+ label="Pénalité de répétition",
206
+ info="Des valeurs plus élevées découragent les motifs répétitifs"
207
  )
208
  max_new_tokens = gr.Slider(
209
  minimum=100, maximum=2000, value=1200, step=100,
210
+ label="Longueur maximale",
211
+ info="Longueur maximale de l'audio généré (en tokens)"
212
  )
213
 
214
  with gr.Row():
215
+ submit_btn = gr.Button("Générer la parole", variant="primary")
216
+ clear_btn = gr.Button("Effacer")
217
 
218
  with gr.Column(scale=2):
219
+ audio_output = gr.Audio(label="Parole générée", type="numpy")
220
 
221
+ # Configuration des exemples
222
  gr.Examples(
223
  examples=examples,
224
  inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
 
227
  cache_examples=True,
228
  )
229
 
230
+ # Configuration des gestionnaires d'événements
231
  submit_btn.click(
232
  fn=generate_speech,
233
  inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
 
240
  outputs=[text_input, audio_output]
241
  )
242
 
243
+ # Lancer l'application
244
  if __name__ == "__main__":
245
  demo.queue().launch(share=False, ssr_mode=False)