bluenevus commited on
Commit
9901299
·
verified ·
1 Parent(s): 112f5f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +622 -1
app.py CHANGED
@@ -126,6 +126,285 @@ def detect_silence(audio, threshold=0.01, min_silence_len=1000):
126
  silent_regions.append((silent_start, len(audio)))
127
  return silent_regions
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  # Combined callback
130
  @callback(
131
  Output("script-output", "value"),
@@ -154,7 +433,6 @@ def detect_silence(audio, threshold=0.01, min_silence_len=1000):
154
  State("advanced-settings", "is_open"),
155
  prevent_initial_call=True
156
  )
157
- @spaces.GPU()
158
  def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_settings_clicks, clear_clicks,
159
  host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts,
160
  script_output, voice1, voice2, temperature, top_p, repetition_penalty, max_new_tokens, is_advanced_open):
@@ -300,6 +578,349 @@ def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_se
300
 
301
  return dash.no_update, dash.no_update, dash.no_update, dash.no_update
302
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
  # Run the app
304
  if __name__ == '__main__':
305
  print("Starting the Dash application...")
 
126
  silent_regions.append((silent_start, len(audio)))
127
  return silent_regions
128
 
129
+ Welcome to Python Dash! I'm your specialized AI assistant for creating efficient Dash by Plotly applications on Hugging Face Spaces. I generate minimal, precise code for AI and ML projects.
130
+
131
+ Getting Started:
132
+
133
+ Describe your Dash by Plotly app's core functionality for huggingface spaces
134
+ I will always provide you the entire script for app.py and requirement.txt
135
+ When troubleshooting I will only fix the affected code and not make any other changes
136
+ this is my code. get rid of the duplicate call backs by putting it into a single function and return me the entire app.py without any other modifications
137
+
138
+ import dash from dash import dcc, html, Input, Output, State, callback import dash_bootstrap_components as dbc import base64 import io import os from snac import SNAC import torch from transformers import AutoModelForCausalLM, AutoTokenizer import google.generativeai as genai import re import logging import numpy as np from pydub import AudioSegment from docx import Document import PyPDF2 import spaces
139
+
140
+ Initialize logging
141
+ logging.basicConfig(level=logging.INFO) logger = logging.getLogger(name)
142
+
143
+ Initialize device
144
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
145
+
146
+ Load models
147
+ print("Loading SNAC model...") snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz") snac_model = snac_model.to(device)
148
+
149
+ model_name = "canopylabs/orpheus-3b-0.1-ft" model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16) model.to(device) tokenizer = AutoTokenizer.from_pretrained(model_name) print(f"Orpheus model loaded to {device}")
150
+
151
+ Available voices and emotive tags
152
+ VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"] EMOTIVE_TAGS = ["<laugh>", "<chuckle>", "<sigh>", "<cough>", "<sniffle>", "<groan>", "<yawn>", "<gasp>"]
153
+
154
+ Initialize Dash app
155
+ app = dash.Dash(name, external_stylesheets=[dbc.themes.BOOTSTRAP])
156
+
157
+ Layout
158
+ app.layout = dbc.Container([ dbc.Row([ dbc.Col([ html.H1("Orpheus Text-to-Speech", className="mb-4"), dbc.Input(id="host1-name", placeholder="Enter name of first host", className="mb-2"), dbc.Input(id="host2-name", placeholder="Enter name of second host", className="mb-2"), dbc.Input(id="podcast-name", placeholder="Enter podcast name", className="mb-2"), dbc.Input(id="podcast-topic", placeholder="Enter podcast topic", className="mb-2"), dbc.Textarea(id="prompt", placeholder="Enter your text here...", rows=5, className="mb-2"), dcc.Upload( id='upload-file', children=html.Div(['Drag and Drop or ', html.A('Select a File')]), style={ 'width': '100%', 'height': '60px', 'lineHeight': '60px', 'borderWidth': '1px', 'borderStyle': 'dashed', 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px 0' }, ), dcc.Slider(id="duration", min=1, max=60, value=5, step=1, marks={1: '1', 30: '30', 60: '60'}, className="mb-2"), dbc.RadioItems( id="num-hosts", options=[{"label": i, "value": i} for i in ["1", "2"]], value="1", inline=True, className="mb-2" ), dbc.Button("Generate Podcast Script", id="generate-script-btn", color="primary", className="mb-2"), ], width=6), dbc.Col([ dbc.Textarea(id="script-output", placeholder="Generated script will appear here...", rows=10, className="mb-2"), dcc.Dropdown(id="voice1", options=[{"label": v, "value": v} for v in VOICES], value="tara", className="mb-2"), dcc.Dropdown(id="voice2", options=[{"label": v, "value": v} for v in VOICES], value="zac", className="mb-2"), dbc.Button("Generate Audio", id="generate-audio-btn", color="success", className="mb-2"), html.Div(id="audio-output"), dbc.Button("Clear", id="clear-btn", color="secondary", className="mb-2"), dbc.Collapse([ dcc.Slider(id="temperature", min=0.1, max=1.5, value=0.6, step=0.05, marks={0.1: '0.1', 0.8: '0.8', 1.5: '1.5'}, className="mb-2"), dcc.Slider(id="top-p", min=0.1, max=1.0, value=0.9, step=0.05, marks={0.1: '0.1', 0.5: '0.5', 1.0: '1.0'}, className="mb-2"), dcc.Slider(id="repetition-penalty", min=1.0, max=2.0, value=1.2, step=0.1, marks={1.0: '1.0', 1.5: '1.5', 2.0: '2.0'}, className="mb-2"), dcc.Slider(id="max-new-tokens", min=100, max=16384, value=4096, step=100, marks={100: '100', 8192: '8192', 16384: '16384'}, className="mb-2"), ], id="advanced-settings", is_open=False), dbc.Button("Advanced Settings", id="advanced-settings-toggle", color="info", className="mb-2"), ], width=6), ]), dcc.Store(id='generated-script'), dcc.Store(id='generated-audio'), ])
159
+
160
+ Callbacks
161
+ @callback( Output("script-output", "value"), Input("generate-script-btn", "n_clicks"), State("host1-name", "value"), State("host2-name", "value"), State("podcast-name", "value"), State("podcast-topic", "value"), State("prompt", "value"), State("upload-file", "contents"), State("duration", "value"), State("num-hosts", "value"), prevent_initial_call=True ) def generate_podcast_script(n_clicks, host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts): if n_clicks is None: return ""
162
+
163
+ Copy
164
+
165
+ try:
166
+ # Get the Gemini API key from Hugging Face secrets
167
+ api_key = os.environ.get("GEMINI_API_KEY")
168
+ if not api_key:
169
+ raise ValueError("Gemini API key not found in environment variables")
170
+
171
+ genai.configure(api_key=api_key)
172
+ model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
173
+
174
+ combined_content = prompt or ""
175
+
176
+ if uploaded_file:
177
+ content_type, content_string = uploaded_file.split(',')
178
+ decoded = base64.b64decode(content_string)
179
+ file_bytes = io.BytesIO(decoded)
180
+
181
+ # Try to detect the file type based on content
182
+ file_bytes.seek(0)
183
+ if file_bytes.read(4) == b'%PDF':
184
+ # It's a PDF file
185
+ file_bytes.seek(0)
186
+ pdf_reader = PyPDF2.PdfReader(file_bytes)
187
+ file_content = "\n".join([page.extract_text() for page in pdf_reader.pages])
188
+ else:
189
+ # Try as text file first
190
+ file_bytes.seek(0)
191
+ try:
192
+ file_content = file_bytes.read().decode('utf-8')
193
+ except UnicodeDecodeError:
194
+ # If it's not a text file, try as a docx
195
+ file_bytes.seek(0)
196
+ try:
197
+ doc = Document(file_bytes)
198
+ file_content = "\n".join([para.text for para in doc.paragraphs])
199
+ except:
200
+ raise ValueError("Unsupported file type or corrupted file")
201
+
202
+ combined_content += "\n" + file_content if combined_content else file_content
203
+
204
+ num_hosts = int(num_hosts) if num_hosts else 1
205
+
206
+ prompt_template = f"""
207
+ Create a podcast script for {num_hosts} {'person' if num_hosts == 1 else 'people'} discussing:
208
+ {combined_content}
209
+
210
+ Duration: {duration} minutes. Include natural speech, humor, and occasional off-topic thoughts.
211
+ Use speech fillers like um, ah. Vary emotional tone.
212
+
213
+ Format: {'Monologue' if num_hosts == 1 else 'Alternating dialogue'} without speaker labels.
214
+ Separate {'paragraphs' if num_hosts == 1 else 'lines'} with blank lines.
215
+ If the number of {num_hosts } is 1 then each paragraph will be no more than 3 sentences each
216
+ Only provide the dialog for text to speech.
217
+ Only use these emotion tags in angle brackets: <laugh>, <sigh>, <chuckle>, <cough>, <sniffle>, <groan>, <yawn>, <gasp>.
218
+ -Example: "I can't believe I stayed up all night <yawn> only to find out the meeting was canceled <groan>."
219
+ Ensure content flows naturally and stays on topic. Match the script length to {duration} minutes.
220
+ Do not include speaker labels like "jane:" or "john:" before dialogue.
221
+ The intro always includes the ({host1_name} and/or {host2_name}) if it exists and should be in the same paragraph.
222
+ The outro always includes the ({host1_name} and/or {host2_name}) if it exists and should be in the same paragraph
223
+ Do not include these types of transitions in the intro, outro or between paragraphs for example: "Intro Music fades in...". Its just dialog.
224
+ Keep each speaker's entire monologue in a single paragraph, regardless of length if the number of hosts is not 1.
225
+ Start a new paragraph only when switching to a different speaker if the number of hosts is not 1.
226
+ Maintain natural conversation flow and speech patterns within each monologue.
227
+ Use context clues or subtle references to indicate who is speaking without explicit labels if the number of hosts is not 1.
228
+ Use speaker names ({host1_name} and/or {host2_name}) sparingly, only when necessary for clarity or emphasis. Avoid starting every line with the other person's name.
229
+ Rely more on context and speech patterns to indicate who is speaking, rather than always stating names.
230
+ Use names primarily for transitions sparingly, definitely with agreements, or to draw attention to a specific point, not as a constant form of address.
231
+ {'Make sure the script is a monologue for one person.' if num_hosts == 1 else f'Ensure the dialogue alternates between two distinct voices, with {host1_name} speaking on odd-numbered lines and {host2_name} on even-numbered lines.'}
232
+ Always include intro with the speaker name and its the podcast name "{podcast_name}" in intoduce the topic of the podcast with "{podcast_topic}".
233
+ Incorporate the podcast name and topic naturally into the intro and outro, and ensure the content stays relevant to the specified topic throughout the script.
234
+ """
235
+
236
+ response = model.generate_content(prompt_template)
237
+ return re.sub(r'[^a-zA-Z0-9\s.,?!<>]', '', response.text)
238
+ except Exception as e:
239
+ logger.error(f"Error generating podcast script: {str(e)}")
240
+ return f"Error: {str(e)}"
241
+ @callback( Output("audio-output", "children"), Input("generate-audio-btn", "n_clicks"), State("script-output", "value"), State("voice1", "value"), State("voice2", "value"), State("temperature", "value"), State("top-p", "value"), State("repetition-penalty", "value"), State("max-new-tokens", "value"), State("num-hosts", "value"), prevent_initial_call=True ) @spaces.GPU() def generate_speech(n_clicks, text, voice1, voice2, temperature, top_p, repetition_penalty, max_new_tokens, num_hosts): if n_clicks is None or not text.strip(): return html.Div("No audio generated yet.")
242
+
243
+ Copy
244
+
245
+ try:
246
+ paragraphs = text.split('\n\n') # Split by double newline
247
+ audio_samples = []
248
+
249
+ for i, paragraph in enumerate(paragraphs):
250
+ if not paragraph.strip():
251
+ continue
252
+
253
+ voice = voice1 if num_hosts == "1" or i % 2 == 0 else voice2
254
+
255
+ input_ids, attention_mask = process_prompt(paragraph, voice, tokenizer, device)
256
+
257
+ with torch.no_grad():
258
+ generated_ids = model.generate(
259
+ input_ids,
260
+ attention_mask=attention_mask,
261
+ do_sample=True,
262
+ temperature=temperature,
263
+ top_p=top_p,
264
+ repetition_penalty=repetition_penalty,
265
+ max_new_tokens=max_new_tokens,
266
+ num_return_sequences=1,
267
+ eos_token_id=128258,
268
+ )
269
+
270
+ code_list = parse_output(generated_ids)
271
+ paragraph_audio = redistribute_codes(code_list, snac_model)
272
+
273
+ silences = detect_silence(paragraph_audio)
274
+ if silences:
275
+ paragraph_audio = paragraph_audio[:silences[-1][1]]
276
+
277
+ audio_samples.append(paragraph_audio)
278
+
279
+ final_audio = np.concatenate(audio_samples)
280
+ final_audio = np.int16(final_audio / np.max(np.abs(final_audio)) * 32767)
281
+
282
+ # Convert to base64 for audio playback
283
+ audio_base64 = base64.b64encode(final_audio.tobytes()).decode('utf-8')
284
+ src = f"data:audio/wav;base64,{audio_base64}"
285
+
286
+ return html.Audio(src=src, controls=True)
287
+ except Exception as e:
288
+ logger.error(f"Error generating speech: {str(e)}")
289
+ return html.Div(f"Error generating audio: {str(e)}")
290
+ @callback( Output("advanced-settings", "is_open"), Input("advanced-settings-toggle", "n_clicks"), State("advanced-settings", "is_open"), ) def toggle_advanced_settings(n_clicks, is_open): if n_clicks: return not is_open return is_open
291
+
292
+ @callback( Output("prompt", "value"), Output("script-output", "value"), Output("audio-output", "children"), Input("clear-btn", "n_clicks"), ) def clear_outputs(n_clicks): if n_clicks: return "", "", html.Div("No audio generated yet.") return dash.no_update, dash.no_update, dash.no_update
293
+
294
+ Run the app
295
+ if name == 'main': print("Starting the Dash application...") app.run(debug=True, host='0.0.0.0', port=7860) print("Dash application has finished running.")
296
+
297
+ Chain of thought:
298
+
299
+ Analyze the current code structure
300
+ Identify the duplicate callbacks
301
+ Combine the callbacks into a single function
302
+ Ensure all inputs and outputs are properly handled
303
+ Maintain the existing functionality
304
+ Update the layout to reflect the changes
305
+ Verify that no other modifications are made
306
+ Now, let's implement these changes:
307
+
308
+ python
309
+ Copy
310
+
311
+ import dash
312
+ from dash import dcc, html, Input, Output, State, callback
313
+ import dash_bootstrap_components as dbc
314
+ import base64
315
+ import io
316
+ import os
317
+ from snac import SNAC
318
+ import torch
319
+ from transformers import AutoModelForCausalLM, AutoTokenizer
320
+ import google.generativeai as genai
321
+ import re
322
+ import logging
323
+ import numpy as np
324
+ from pydub import AudioSegment
325
+ from docx import Document
326
+ import PyPDF2
327
+ import spaces
328
+
329
+ # Initialize logging
330
+ logging.basicConfig(level=logging.INFO)
331
+ logger = logging.getLogger(__name__)
332
+
333
+ # Initialize device
334
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
335
+
336
+ # Load models
337
+ print("Loading SNAC model...")
338
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
339
+ snac_model = snac_model.to(device)
340
+
341
+ model_name = "canopylabs/orpheus-3b-0.1-ft"
342
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
343
+ model.to(device)
344
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
345
+ print(f"Orpheus model loaded to {device}")
346
+
347
+ # Available voices and emotive tags
348
+ VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]
349
+ EMOTIVE_TAGS = ["`<laugh>`", "`<chuckle>`", "`<sigh>`", "`<cough>`", "`<sniffle>`", "`<groan>`", "`<yawn>`", "`<gasp>`"]
350
+
351
+ # Initialize Dash app
352
+ app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
353
+
354
+ # Layout
355
+ app.layout = dbc.Container([
356
+ dbc.Row([
357
+ dbc.Col([
358
+ html.H1("Orpheus Text-to-Speech", className="mb-4"),
359
+ dbc.Input(id="host1-name", placeholder="Enter name of first host", className="mb-2"),
360
+ dbc.Input(id="host2-name", placeholder="Enter name of second host", className="mb-2"),
361
+ dbc.Input(id="podcast-name", placeholder="Enter podcast name", className="mb-2"),
362
+ dbc.Input(id="podcast-topic", placeholder="Enter podcast topic", className="mb-2"),
363
+ dbc.Textarea(id="prompt", placeholder="Enter your text here...", rows=5, className="mb-2"),
364
+ dcc.Upload(
365
+ id='upload-file',
366
+ children=html.Div(['Drag and Drop or ', html.A('Select a File')]),
367
+ style={
368
+ 'width': '100%',
369
+ 'height': '60px',
370
+ 'lineHeight': '60px',
371
+ 'borderWidth': '1px',
372
+ 'borderStyle': 'dashed',
373
+ 'borderRadius': '5px',
374
+ 'textAlign': 'center',
375
+ 'margin': '10px 0'
376
+ },
377
+ ),
378
+ dcc.Slider(id="duration", min=1, max=60, value=5, step=1, marks={1: '1', 30: '30', 60: '60'}, className="mb-2"),
379
+ dbc.RadioItems(
380
+ id="num-hosts",
381
+ options=[{"label": i, "value": i} for i in ["1", "2"]],
382
+ value="1",
383
+ inline=True,
384
+ className="mb-2"
385
+ ),
386
+ dbc.Button("Generate Podcast Script", id="generate-script-btn", color="primary", className="mb-2"),
387
+ ], width=6),
388
+ dbc.Col([
389
+ dbc.Textarea(id="script-output", placeholder="Generated script will appear here...", rows=10, className="mb-2"),
390
+ dcc.Dropdown(id="voice1", options=[{"label": v, "value": v} for v in VOICES], value="tara", className="mb-2"),
391
+ dcc.Dropdown(id="voice2", options=[{"label": v, "value": v} for v in VOICES], value="zac", className="mb-2"),
392
+ dbc.Button("Generate Audio", id="generate-audio-btn", color="success", className="mb-2"),
393
+ html.Div(id="audio-output"),
394
+ dbc.Button("Clear", id="clear-btn", color="secondary", className="mb-2"),
395
+ dbc.Collapse([
396
+ dcc.Slider(id="temperature", min=0.1, max=1.5, value=0.6, step=0.05, marks={0.1: '0.1', 0.8: '0.8', 1.5: '1.5'}, className="mb-2"),
397
+ dcc.Slider(id="top-p", min=0.1, max=1.0, value=0.9, step=0.05, marks={0.1: '0.1', 0.5: '0.5', 1.0: '1.0'}, className="mb-2"),
398
+ dcc.Slider(id="repetition-penalty", min=1.0, max=2.0, value=1.2, step=0.1, marks={1.0: '1.0', 1.5: '1.5', 2.0: '2.0'}, className="mb-2"),
399
+ dcc.Slider(id="max-new-tokens", min=100, max=16384, value=4096, step=100, marks={100: '100', 8192: '8192', 16384: '16384'}, className="mb-2"),
400
+ ], id="advanced-settings", is_open=False),
401
+ dbc.Button("Advanced Settings", id="advanced-settings-toggle", color="info", className="mb-2"),
402
+ ], width=6),
403
+ ]),
404
+ dcc.Store(id='generated-script'),
405
+ dcc.Store(id='generated-audio'),
406
+ ])
407
+
408
  # Combined callback
409
  @callback(
410
  Output("script-output", "value"),
 
433
  State("advanced-settings", "is_open"),
434
  prevent_initial_call=True
435
  )
 
436
  def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_settings_clicks, clear_clicks,
437
  host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts,
438
  script_output, voice1, voice2, temperature, top_p, repetition_penalty, max_new_tokens, is_advanced_open):
 
578
 
579
  return dash.no_update, dash.no_update, dash.no_update, dash.no_update
580
 
581
+ # Run the app
582
+ if __name__ == '__main__':
583
+ print("Starting the Dash
584
+ where do I put this? @spaces.GPU
585
+
586
+ To properly implement the @spaces.GPU() decorator in your Dash application, you should place it directly above the function that requires GPU acceleration. In this case, you would add it above the combined_callback function. Here's how you should modify your code:
587
+
588
+ python
589
+ Copy
590
+
591
+ # ... (previous code remains unchanged)
592
+
593
+ # Combined callback
594
+ @callback(
595
+ Output("script-output", "value"),
596
+ Output("audio-output", "children"),
597
+ Output("advanced-settings", "is_open"),
598
+ Output("prompt", "value"),
599
+ Input("generate-script-btn", "n_clicks"),
600
+ Input("generate-audio-btn", "n_clicks"),
601
+ Input("advanced-settings-toggle", "n_clicks"),
602
+ Input("clear-btn", "n_clicks"),
603
+ State("host1-name", "value"),
604
+ State("host2-name", "value"),
605
+ State("podcast-name", "value"),
606
+ State("podcast-topic", "value"),
607
+ State("prompt", "value"),
608
+ State("upload-file", "contents"),
609
+ State("duration", "value"),
610
+ State("num-hosts", "value"),
611
+ State("script-output", "value"),
612
+ State("voice1", "value"),
613
+ State("voice2", "value"),
614
+ State("temperature", "value"),
615
+ State("top-p", "value"),
616
+ State("repetition-penalty", "value"),
617
+ State("max-new-tokens", "value"),
618
+ State("advanced-settings", "is_open"),
619
+ prevent_initial_call=True
620
+ )
621
+ @spaces.GPU()
622
+ def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_settings_clicks, clear_clicks,
623
+ host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts,
624
+ script_output, voice1, voice2, temperature, top
625
+ ERROR:main:Error generating speech: name 'process_prompt' is not defined
626
+
627
+ I apologize for the oversight. The error you're encountering is due to the process_prompt function not being defined in the code. This function is likely used for processing the input text before generating speech. Let's add the missing function and any other necessary functions to resolve this error. Here's how we can modify the code:
628
+
629
+ First, we need to add the process_prompt function.
630
+ We should also add the parse_output, redistribute_codes, and detect_silence functions, which are used in the audio generation process.
631
+ Add these functions just before the combined_callback function:
632
+
633
+ python
634
+ Copy
635
+
636
+ def process_prompt(text, voice, tokenizer, device):
637
+ prompt = f"{voice}: {text}"
638
+ inputs = tokenizer(prompt, return_tensors="pt")
639
+ input_ids = inputs["input_ids"].to(device)
640
+ attention_mask = inputs["attention_mask"].to(device)
641
+ return input_ids, attention_mask
642
+
643
+ def parse_output(generated_ids):
644
+ decoded = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
645
+ code_list = [int(code) for code in decoded.split() if code.isdigit()]
646
+ return code_list
647
+
648
+ def redistribute_codes(code_list, snac_model):
649
+ audio = snac_model.codes_to_audio(torch.tensor(code_list).unsqueeze(0).to(device))
650
+ return audio.cpu().numpy().flatten()
651
+
652
+ def detect_silence(audio, threshold=0.01, min_silence_len=1000):
653
+ is_silent = np.abs(audio) < threshold
654
+ silent_regions = []
655
+ silent_start = None
656
+ for i, silent in enumerate(is_silent):
657
+ if silent and silent_start is None:
658
+ silent_start = i
659
+ elif not silent and silent_start is not None:
660
+ if i - silent_start >= min_silence_len:
661
+ silent_regions.append((silent_start, i))
662
+ silent_start = None
663
+ if silent_start is not None and len(audio) - silent_start >= min_silence_len:
664
+ silent_regions.append((silent_start, len(audio)))
665
+ return silent_regions
666
+
667
+ # Combined callback
668
+ @callback(
669
+ Output("script-output", "value"),
670
+ Output("audio-output", "children"),
671
+ Output("advanced-settings", "is_open"),
672
+ Output("prompt", "value"),
673
+ Input("generate-script-btn", "n_clicks"),
674
+ Input("generate-audio-btn", "n_clicks"),
675
+ Input("advanced-settings-toggle", "n_clicks"),
676
+ Input("clear-btn", "n_clicks"),
677
+ State("host1-name", "value"),
678
+ State("host2-name", "value"),
679
+ State("podcast-name", "value"),
680
+ State("podcast-topic", "value"),
681
+ State("prompt", "value"),
682
+ State("upload-file", "contents"),
683
+ State("duration", "value"),
684
+ State("num-hosts", "value"),
685
+ State("script-output", "value"),
686
+ State("voice1", "value"),
687
+ State("voice2", "value"),
688
+ State("temperature", "value"),
689
+ State("top-p", "value"),
690
+ State("repetition-penalty", "value"),
691
+ State("max-new-tokens", "value"),
692
+ State("advanced-settings", "is_open"),
693
+ prevent_initial_call=True
694
+ )
695
+ @spaces.GPU()
696
+ def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_settings_clicks, clear_clicks,
697
+ host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts,
698
+ script_output, voice1, voice2, temperature, top_p, repetition_penalty, max_new_tokens, is_advanced_open):
699
+ # ... (rest of the function remains unchanged)
700
+ These additions should resolve the "name 'process_prompt' is not defined" error and provide the necessary functions for audio generation. Make sure to place these function definitions before the combined_callback function in your code.
701
+
702
+ its stuck here
703
+
704
+ Using a ZeroGPU function outside of Gradio caching or request might block the app
705
+
706
+ INFO:httpx:HTTP Request: POST http://device-api.zero/allow?allowToken=765a43b283841841a6b484887de0c56c84ab4e8219e7ff2632ad6cf3e92d2012&pid=1580 "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST http://device-api.zero/release?allowToken=765a43b283841841a6b484887de0c56c84ab4e8219e7ff2632ad6cf3e92d2012&fail=false "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST http://device-api.zero/schedule?cgroupPath=%2Fkubepods.slice%2Fkubepods-burstable.slice%2Fkubepods-burstable-pod3cd9482c_d34a_484d_9434_ad8483b9ee4c.slice%2Fcri-containerd-b9a000519f1ed8024a1915b093625f1ac9c2cad6b0700f31850608b8c61a7aa5.scope&taskId=140413719708576&enableQueue=true&tokenVersion=2 "HTTP/1.1 200 OK" INFO:httpx:HTTP Request: POST http://device-api.zero/release?allowToken=70d732fbc3156877cb6179fc0e7b1115e19291613f08e53f594be5b684eb4f9c&fail=false "HTTP/1.1 200 OK"
707
+
708
+ no audio download
709
+
710
+ I'll just attache a gpu to it like a t4
711
+
712
+ Based on the context provided, it seems you're encountering issues with GPU allocation and audio generation in your Dash application. Let's address these problems step by step:
713
+
714
+ GPU Allocation Issue: The error message suggests that you're using a ZeroGPU function outside of the intended context, which could be blocking the app. This is likely related to the @spaces.GPU() decorator we added earlier.
715
+
716
+ Audio Download Problem: You mentioned there's no audio download, which could be related to how the audio is being generated or served.
717
+
718
+ To address these issues, let's make the following modifications:
719
+
720
+ Remove the @spaces.GPU() decorator from the combined_callback function. Instead, we'll use it more specifically within the audio generation part.
721
+
722
+ Split the audio generation into a separate function and apply the @spaces.GPU() decorator there.
723
+
724
+ Ensure the audio is properly generated and served for download.
725
+
726
+ Here's how you can modify your code:
727
+
728
+ python
729
+ Copy
730
+
731
+ import spaces
732
+
733
+ # ... (other imports and setup code)
734
+
735
+ @spaces.GPU()
736
+ def generate_audio(script_output, voice1, voice2, num_hosts, temperature, top_p, repetition_penalty, max_new_tokens):
737
+ try:
738
+ paragraphs = script_output.split('\n\n') # Split by double newline
739
+ audio_samples = []
740
+
741
+ for i, paragraph in enumerate(paragraphs):
742
+ if not paragraph.strip():
743
+ continue
744
+
745
+ voice = voice1 if num_hosts == "1" or i % 2 == 0 else voice2
746
+
747
+ input_ids, attention_mask = process_prompt(paragraph, voice, tokenizer, device)
748
+
749
+ with torch.no_grad():
750
+ generated_ids = model.generate(
751
+ input_ids,
752
+ attention_mask=attention_mask,
753
+ do_sample=True,
754
+ temperature=temperature,
755
+ top_p=top_p,
756
+ repetition_penalty=repetition_penalty,
757
+ max_new_tokens=max_new_tokens,
758
+ num_return_sequences=1,
759
+ eos_token_id=128258,
760
+ )
761
+
762
+ code_list = parse_output(generated_ids)
763
+ paragraph_audio = redistribute_codes(code_list, snac_model)
764
+
765
+ silences = detect_silence(paragraph_audio)
766
+ if silences:
767
+ paragraph_audio = paragraph_audio[:silences[-1][1]]
768
+
769
+ audio_samples.append(paragraph_audio)
770
+
771
+ final_audio = np.concatenate(audio_samples)
772
+ final_audio = np.int16(final_audio / np.max(np.abs(final_audio)) * 32767)
773
+
774
+ return final_audio
775
+ except Exception as e:
776
+ logger.error(f"Error generating speech: {str(e)}")
777
+ return None
778
+
779
+ # Combined callback
780
+ @callback(
781
+ Output("script-output", "value"),
782
+ Output("audio-output", "children"),
783
+ Output("advanced-settings", "is_open"),
784
+ Output("prompt", "value"),
785
+ Input("generate-script-btn", "n_clicks"),
786
+ Input("generate-audio-btn", "n_clicks"),
787
+ Input("advanced-settings-toggle", "n_clicks"),
788
+ Input("clear-btn", "n_clicks"),
789
+ State("host1-name", "value"),
790
+ State("host2-name", "value"),
791
+ State("podcast-name", "value"),
792
+ State("podcast-topic", "value"),
793
+ State("prompt", "value"),
794
+ State("upload-file", "contents"),
795
+ State("duration", "value"),
796
+ State("num-hosts", "value"),
797
+ State("script-output", "value"),
798
+ State("voice1", "value"),
799
+ State("voice2", "value"),
800
+ State("temperature", "value"),
801
+ State("top-p", "value"),
802
+ State("repetition-penalty", "value"),
803
+ State("max-new-tokens", "value"),
804
+ State("advanced-settings", "is_open"),
805
+ prevent_initial_call=True
806
+ )
807
+ def combined_callback(generate_script_clicks, generate_audio_clicks, advanced_settings_clicks, clear_clicks,
808
+ host1_name, host2_name, podcast_name, podcast_topic, prompt, uploaded_file, duration, num_hosts,
809
+ script_output, voice1, voice2, temperature, top_p, repetition_penalty, max_new_tokens, is_advanced_open):
810
+ ctx = dash.callback_context
811
+ if not ctx.triggered:
812
+ return dash.no_update, dash.no_update, dash.no_update, dash.no_update
813
+
814
+ trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
815
+
816
+ if trigger_id == "generate-script-btn":
817
+ try:
818
+ # Get the Gemini API key from Hugging Face secrets
819
+ api_key = os.environ.get("GEMINI_API_KEY")
820
+ if not api_key:
821
+ raise ValueError("Gemini API key not found in environment variables")
822
+
823
+ genai.configure(api_key=api_key)
824
+ model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
825
+
826
+ combined_content = prompt or ""
827
+
828
+ if uploaded_file:
829
+ content_type, content_string = uploaded_file.split(',')
830
+ decoded = base64.b64decode(content_string)
831
+ file_bytes = io.BytesIO(decoded)
832
+
833
+ # Try to detect the file type based on content
834
+ file_bytes.seek(0)
835
+ if file_bytes.read(4) == b'%PDF':
836
+ # It's a PDF file
837
+ file_bytes.seek(0)
838
+ pdf_reader = PyPDF2.PdfReader(file_bytes)
839
+ file_content = "\n".join([page.extract_text() for page in pdf_reader.pages])
840
+ else:
841
+ # Try as text file first
842
+ file_bytes.seek(0)
843
+ try:
844
+ file_content = file_bytes.read().decode('utf-8')
845
+ except UnicodeDecodeError:
846
+ # If it's not a text file, try as a docx
847
+ file_bytes.seek(0)
848
+ try:
849
+ doc = Document(file_bytes)
850
+ file_content = "\n".join([para.text for para in doc.paragraphs])
851
+ except:
852
+ raise ValueError("Unsupported file type or corrupted file")
853
+
854
+ combined_content += "\n" + file_content if combined_content else file_content
855
+
856
+ num_hosts = int(num_hosts) if num_hosts else 1
857
+
858
+ prompt_template = f"""
859
+ Create a podcast script for {num_hosts} {'person' if num_hosts == 1 else 'people'} discussing:
860
+ {combined_content}
861
+
862
+ Duration: {duration} minutes. Include natural speech, humor, and occasional off-topic thoughts.
863
+ Use speech fillers like um, ah. Vary emotional tone.
864
+
865
+ Format: {'Monologue' if num_hosts == 1 else 'Alternating dialogue'} without speaker labels.
866
+ Separate {'paragraphs' if num_hosts == 1 else 'lines'} with blank lines.
867
+ If the number of {num_hosts } is 1 then each paragraph will be no more than 3 sentences each
868
+ Only provide the dialog for text to speech.
869
+ Only use these emotion tags in angle brackets: <laugh>, <sigh>, <chuckle>, <cough>, <sniffle>, <groan>, <yawn>, <gasp>.
870
+ -Example: "I can't believe I stayed up all night <yawn> only to find out the meeting was canceled <groan>."
871
+ Ensure content flows naturally and stays on topic. Match the script length to {duration} minutes.
872
+ Do not include speaker labels like "jane:" or "john:" before dialogue.
873
+ The intro always includes the ({host1_name} and/or {host2_name}) if it exists and should be in the same paragraph.
874
+ The outro always includes the ({host1_name} and/or {host2_name}) if it exists and should be in the same paragraph
875
+ Do not include these types of transitions in the intro, outro or between paragraphs for example: "Intro Music fades in...". Its just dialog.
876
+ Keep each speaker's entire monologue in a single paragraph, regardless of length if the number of hosts is not 1.
877
+ Start a new paragraph only when switching to a different speaker if the number of hosts is not 1.
878
+ Maintain natural conversation flow and speech patterns within each monologue.
879
+ Use context clues or subtle references to indicate who is speaking without explicit labels if the number of hosts is not 1.
880
+ Use speaker names ({host1_name} and/or {host2_name}) sparingly, only when necessary for clarity or emphasis. Avoid starting every line with the other person's name.
881
+ Rely more on context and speech patterns to indicate who is speaking, rather than always stating names.
882
+ Use names primarily for transitions sparingly, definitely with agreements, or to draw attention to a specific point, not as a constant form of address.
883
+ {'Make sure the script is a monologue for one person.' if num_hosts == 1 else f'Ensure the dialogue alternates between two distinct voices, with {host1_name} speaking on odd-numbered lines and {host2_name} on even-numbered lines.'}
884
+ Always include intro with the speaker name and its the podcast name "{podcast_name}" in intoduce the topic of the podcast with "{podcast_topic}".
885
+ Incorporate the podcast name and topic naturally into the intro and outro, and ensure the content stays relevant to the specified topic throughout the script.
886
+ """
887
+
888
+ response = model.generate_content(prompt_template)
889
+ return re.sub(r'[^a-zA-Z0-9\s.,?!<>]', '', response.text), dash.no_update, dash.no_update, dash.no_update
890
+ except Exception as e:
891
+ logger.error(f"Error generating podcast script: {str(e)}")
892
+ return f"Error: {str(e)}", dash.no_update, dash.no_update, dash.no_update
893
+
894
+ elif trigger_id == "generate-audio-btn":
895
+ if not script_output.strip():
896
+ return dash.no_update, html.Div("No audio generated yet."), dash.no_update, dash.no_update
897
+
898
+ final_audio = generate_audio(script_output, voice1, voice2, num_hosts, temperature, top_p, repetition_penalty, max_new_tokens)
899
+
900
+ if final_audio is not None:
901
+ # Convert to base64 for audio playback
902
+ audio_base64 = base64.b64encode(final_audio.tobytes()).decode('utf-8')
903
+ src = f"data:audio/wav;base64,{audio_base64}"
904
+
905
+ # Create a download link for the audio
906
+ download_link = html.A("Download Audio", href=src, download="generated_audio.wav")
907
+
908
+ return dash.no_update, html.Div([
909
+ html.Audio(src=src, controls=True),
910
+ html.Br(),
911
+ download_link
912
+ ]), dash.no_update, dash.no_update
913
+ else:
914
+ return dash.no_update, html.Div("Error generating audio"), dash.no_update, dash.no_update
915
+
916
+ elif trigger_id == "advanced-settings-toggle":
917
+ return dash.no_update, dash.no_update, not is_advanced_open, dash.no_update
918
+
919
+ elif trigger_id == "clear-btn":
920
+ return "", html.Div("No audio generated yet."), dash.no_update, ""
921
+
922
+ return dash.no_update, dash.no_update, dash.no_update, dash.no_update
923
+
924
  # Run the app
925
  if __name__ == '__main__':
926
  print("Starting the Dash application...")