saq1b commited on
Commit
3fd29b8
·
verified ·
1 Parent(s): 52c9fac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +604 -632
app.py CHANGED
@@ -1,633 +1,605 @@
1
- import streamlit as st
2
- from pydub import AudioSegment
3
- from google import genai
4
- from google.genai import types
5
- import json
6
- import uuid
7
- import edge_tts
8
- import asyncio
9
- import aiofiles
10
- import os
11
- import time
12
- import mimetypes
13
- from typing import List, Dict
14
-
15
- # Constants
16
- MAX_FILE_SIZE_MB = 20
17
- MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
18
-
19
- class PodcastGenerator:
20
- def __init__(self):
21
- pass
22
-
23
- async def generate_script(self, prompt: str, language: str, api_key: str, file_obj=None, progress=None) -> Dict:
24
- example = """
25
- {
26
- "topic": "AGI",
27
- "podcast": [
28
- {
29
- "speaker": 2,
30
- "line": "So, AGI, huh? Seems like everyone's talking about it these days."
31
- },
32
- {
33
- "speaker": 1,
34
- "line": "Yeah, it's definitely having a moment, isn't it?"
35
- },
36
- {
37
- "speaker": 2,
38
- "line": "It is and for good reason, right? I mean, you've been digging into this stuff, listening to the podcasts and everything. What really stood out to you? What got you hooked?"
39
- },
40
- {
41
- "speaker": 1,
42
- "line": "Honestly, it's the sheer scale of what AGI could do. We're talking about potentially reshaping well everything."
43
- },
44
- {
45
- "speaker": 2,
46
- "line": "No kidding, but let's be real. Sometimes it feels like every other headline is either hyping AGI up as this technological utopia or painting it as our inevitable robot overlords."
47
- },
48
- {
49
- "speaker": 1,
50
- "line": "It's easy to get lost in the noise, for sure."
51
- },
52
- {
53
- "speaker": 2,
54
- "line": "Exactly. So how about we try to cut through some of that, shall we?"
55
- },
56
- {
57
- "speaker": 1,
58
- "line": "Sounds like a plan."
59
- },
60
- {
61
- "speaker": 2,
62
- "line": "Okay, so first things first, AGI, what is it really? And I don't just mean some dictionary definition, we're talking about something way bigger than just a super smart computer, right?"
63
- },
64
- {
65
- "speaker": 1,
66
- "line": "Right, it's not just about more processing power or better algorithms, it's about a fundamental shift in how we think about intelligence itself."
67
- },
68
- {
69
- "speaker": 2,
70
- "line": "So like, instead of programming a machine for a specific task, we're talking about creating something that can learn and adapt like we do."
71
- },
72
- {
73
- "speaker": 1,
74
- "line": "Exactly, think of it this way: Right now, we've got AI that can beat a grandmaster at chess but ask that same AI to, say, write a poem or compose a symphony. No chance."
75
- },
76
- {
77
- "speaker": 2,
78
- "line": "Okay, I see. So, AGI is about bridging that gap, creating something that can move between those different realms of knowledge seamlessly."
79
- },
80
- {
81
- "speaker": 1,
82
- "line": "Precisely. It's about replicating that uniquely human ability to learn something new and apply that knowledge in completely different contexts and that's a tall order, let me tell you."
83
- },
84
- {
85
- "speaker": 2,
86
- "line": "I bet. I mean, think about how much we still don't even understand about our own brains."
87
- },
88
- {
89
- "speaker": 1,
90
- "line": "That's exactly it. We're essentially trying to reverse-engineer something we don't fully comprehend."
91
- },
92
- {
93
- "speaker": 2,
94
- "line": "And how are researchers even approaching that? What are some of the big ideas out there?"
95
- },
96
- {
97
- "speaker": 1,
98
- "line": "Well, there are a few different schools of thought. One is this idea of neuromorphic computing where they're literally trying to build computer chips that mimic the structure and function of the human brain."
99
- },
100
- {
101
- "speaker": 2,
102
- "line": "Wow, so like actually replicating the physical architecture of the brain. That's wild."
103
- },
104
- {
105
- "speaker": 1,
106
- "line": "It's pretty mind-blowing stuff and then you've got folks working on something called whole brain emulation."
107
- },
108
- {
109
- "speaker": 2,
110
- "line": "Okay, and what's that all about?"
111
- },
112
- {
113
- "speaker": 1,
114
- "line": "The basic idea there is to create a complete digital copy of a human brain down to the last neuron and synapse and run it on a sufficiently powerful computer simulation."
115
- },
116
- {
117
- "speaker": 2,
118
- "line": "Hold on, a digital copy of an entire brain, that sounds like something straight out of science fiction."
119
- },
120
- {
121
- "speaker": 1,
122
- "line": "It does, doesn't it? But it gives you an idea of the kind of ambition we're talking about here and the truth is we're still a long way off from truly achieving AGI, no matter which approach you look at."
123
- },
124
- {
125
- "speaker": 2,
126
- "line": "That makes sense but it's still exciting to think about the possibilities, even if they're a ways off."
127
- },
128
- {
129
- "speaker": 1,
130
- "line": "Absolutely and those possibilities are what really get people fired up about AGI, right? Yeah."
131
- },
132
- {
133
- "speaker": 2,
134
- "line": "For sure. In fact, I remember you mentioning something in that podcast about AGI's potential to revolutionize scientific research. Something about supercharging breakthroughs."
135
- },
136
- {
137
- "speaker": 1,
138
- "line": "Oh, absolutely. Imagine an AI that doesn't just crunch numbers but actually understands scientific data the way a human researcher does. We're talking about potential breakthroughs in everything from medicine and healthcare to material science and climate change."
139
- },
140
- {
141
- "speaker": 2,
142
- "line": "It's like giving scientists this incredibly powerful new tool to tackle some of the biggest challenges we face."
143
- },
144
- {
145
- "speaker": 1,
146
- "line": "Exactly, it could be a total game changer."
147
- },
148
- {
149
- "speaker": 2,
150
- "line": "Okay, but let's be real, every coin has two sides. What about the potential downsides of AGI? Because it can't all be sunshine and roses, right?"
151
- },
152
- {
153
- "speaker": 1,
154
- "line": "Right, there are definitely valid concerns. Probably the biggest one is the impact on the job market. As AGI gets more sophisticated, there's a real chance it could automate a lot of jobs that are currently done by humans."
155
- },
156
- {
157
- "speaker": 2,
158
- "line": "So we're not just talking about robots taking over factories but potentially things like, what, legal work, analysis, even creative fields?"
159
- },
160
- {
161
- "speaker": 1,
162
- "line": "Potentially, yes. And that raises a whole host of questions about what happens to those workers, how we retrain them, how we ensure that the benefits of AGI are shared equitably."
163
- },
164
- {
165
- "speaker": 2,
166
- "line": "Right, because it's not just about the technology itself, but how we choose to integrate it into society."
167
- },
168
- {
169
- "speaker": 1,
170
- "line": "Absolutely. We need to be having these conversations now about ethics, about regulation, about how to make sure AGI is developed and deployed responsibly."
171
- },
172
- {
173
- "speaker": 2,
174
- "line": "So it's less about preventing some kind of sci-fi robot apocalypse and more about making sure we're steering this technology in the right direction from the get-go."
175
- },
176
- {
177
- "speaker": 1,
178
- "line": "Exactly, AGI has the potential to be incredibly beneficial, but it's not going to magically solve all our problems. It's on us to make sure we're using it for good."
179
- },
180
- {
181
- "speaker": 2,
182
- "line": "It's like you said earlier, it's about shaping the future of intelligence."
183
- },
184
- {
185
- "speaker": 1,
186
- "line": "I like that. It really is."
187
- },
188
- {
189
- "speaker": 2,
190
- "line": "And honestly, that's a responsibility that extends beyond just the researchers and the policymakers."
191
- },
192
- {
193
- "speaker": 1,
194
- "line": "100%"
195
- },
196
- {
197
- "speaker": 2,
198
- "line": "So to everyone listening out there I'll leave you with this. As AGI continues to develop, what role do you want to play in shaping its future?"
199
- },
200
- {
201
- "speaker": 1,
202
- "line": "That's a question worth pondering."
203
- },
204
- {
205
- "speaker": 2,
206
- "line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
207
- },
208
- {
209
- "speaker": 1,
210
- "line": "Peace."
211
- }
212
- ]
213
- }
214
- """
215
-
216
- if language == "Auto Detect":
217
- language_instruction = "- The podcast MUST be in the same language as the user input."
218
- else:
219
- language_instruction = f"- The podcast MUST be in {language} language"
220
-
221
- system_prompt = f"""
222
- You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input.
223
- {language_instruction}
224
- - The podcast should have 2 speakers.
225
- - The podcast should be long.
226
- - Do not use names for the speakers.
227
- - The podcast should be interesting, lively, and engaging, and hook the listener from the start.
228
- - The input text might be disorganized or unformatted, originating from sources like PDFs or text files. Ignore any formatting inconsistencies or irrelevant details; your task is to distill the essential points, identify key definitions, and highlight intriguing facts that would be suitable for discussion in a podcast.
229
- - The script must be in JSON format.
230
- Follow this example structure:
231
- {example}
232
- """
233
- user_prompt = ""
234
- if prompt and file_obj:
235
- user_prompt = f"Please generate a podcast script based on the uploaded file following user input:\n{prompt}"
236
- elif prompt:
237
- user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
238
- else:
239
- user_prompt = "Please generate a podcast script based on the uploaded file."
240
-
241
- messages = []
242
-
243
- # If file is provided, add it to the messages
244
- if file_obj:
245
- file_data = await self._read_file_bytes(file_obj)
246
- mime_type = self._get_mime_type(file_obj.name)
247
-
248
- messages.append(
249
- types.Content(
250
- role="user",
251
- parts=[
252
- types.Part.from_bytes(
253
- data=file_data,
254
- mime_type=mime_type,
255
- )
256
- ],
257
- )
258
- )
259
-
260
- # Add text prompt
261
- messages.append(
262
- types.Content(
263
- role="user",
264
- parts=[
265
- types.Part.from_text(text=user_prompt)
266
- ],
267
- )
268
- )
269
-
270
- client = genai.Client(api_key=api_key)
271
-
272
- safety_settings = [
273
- {
274
- "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
275
- "threshold": "BLOCK_NONE"
276
- },
277
- {
278
- "category": "HARM_CATEGORY_HARASSMENT",
279
- "threshold": "BLOCK_NONE"
280
- },
281
- {
282
- "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
283
- "threshold": "BLOCK_NONE"
284
- },
285
- {
286
- "category": "HARM_CATEGORY_HATE_SPEECH",
287
- "threshold": "BLOCK_NONE"
288
- }
289
- ]
290
-
291
- try:
292
- if progress:
293
- progress.progress(0.3, "Generating podcast script...")
294
-
295
- # Add timeout to the API call
296
- response = await asyncio.wait_for(
297
- client.aio.models.generate_content(
298
- model="gemini-2.0-flash",
299
- contents=messages,
300
- config=types.GenerateContentConfig(
301
- temperature=1,
302
- response_mime_type="application/json",
303
- safety_settings=[
304
- types.SafetySetting(
305
- category=safety_setting["category"],
306
- threshold=safety_setting["threshold"]
307
- ) for safety_setting in safety_settings
308
- ],
309
- system_instruction=system_prompt
310
- )
311
- ),
312
- timeout=60 # 60 seconds timeout
313
- )
314
- except asyncio.TimeoutError:
315
- raise Exception("The script generation request timed out. Please try again later.")
316
- except Exception as e:
317
- if "API key not valid" in str(e):
318
- raise Exception("Invalid API key. Please provide a valid Gemini API key.")
319
- elif "rate limit" in str(e).lower():
320
- raise Exception("Rate limit exceeded for the API key. Please try again later or provide your own Gemini API key.")
321
- else:
322
- raise Exception(f"Failed to generate podcast script: {e}")
323
-
324
- print(f"Generated podcast script:\n{response.text}")
325
-
326
- if progress:
327
- progress.progress(0.4, "Script generated successfully!")
328
-
329
- return json.loads(response.text)
330
-
331
- async def _read_file_bytes(self, file_obj) -> bytes:
332
- """Read file bytes from a file object"""
333
- # Check file size before reading
334
- file_size = os.path.getsize(file_obj.name)
335
- if file_size > MAX_FILE_SIZE_BYTES:
336
- raise Exception(f"File size exceeds the {MAX_FILE_SIZE_MB}MB limit. Please upload a smaller file.")
337
-
338
- async with aiofiles.open(file_obj.name, 'rb') as f:
339
- return await f.read()
340
-
341
- def _get_mime_type(self, filename: str) -> str:
342
- """Determine MIME type based on file extension"""
343
- ext = os.path.splitext(filename)[1].lower()
344
- if ext == '.pdf':
345
- return "application/pdf"
346
- elif ext == '.txt':
347
- return "text/plain"
348
- else:
349
- # Fallback to the default mime type detector
350
- mime_type, _ = mimetypes.guess_type(filename)
351
- return mime_type or "application/octet-stream"
352
-
353
- async def tts_generate(self, text: str, speaker: int, speaker1: str, speaker2: str) -> str:
354
- voice = speaker1 if speaker == 1 else speaker2
355
- speech = edge_tts.Communicate(text, voice)
356
-
357
- temp_filename = f"temp_{uuid.uuid4()}.wav"
358
- try:
359
- # Add timeout to TTS generation
360
- await asyncio.wait_for(speech.save(temp_filename), timeout=30) # 30 seconds timeout
361
- return temp_filename
362
- except asyncio.TimeoutError:
363
- if os.path.exists(temp_filename):
364
- os.remove(temp_filename)
365
- raise Exception("Text-to-speech generation timed out. Please try with a shorter text.")
366
- except Exception as e:
367
- if os.path.exists(temp_filename):
368
- os.remove(temp_filename)
369
- raise e
370
-
371
- async def combine_audio_files(self, audio_files: List[str], progress=None) -> str:
372
- if progress:
373
- progress.progress(0.9, "Combining audio files...")
374
-
375
- combined_audio = AudioSegment.empty()
376
- for audio_file in audio_files:
377
- combined_audio += AudioSegment.from_file(audio_file)
378
- os.remove(audio_file) # Clean up temporary files
379
-
380
- output_filename = f"output_{uuid.uuid4()}.wav"
381
- combined_audio.export(output_filename, format="wav")
382
-
383
- if progress:
384
- progress.progress(1.0, "Podcast generated successfully!")
385
-
386
- return output_filename
387
-
388
- async def generate_podcast(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
389
- try:
390
- if progress:
391
- progress.progress(0.1, "Starting podcast generation...")
392
-
393
- # Set overall timeout for the entire process
394
- return await asyncio.wait_for(
395
- self._generate_podcast_internal(input_text, language, speaker1, speaker2, api_key, file_obj, progress),
396
- timeout=600 # 10 minutes total timeout
397
- )
398
- except asyncio.TimeoutError:
399
- raise Exception("The podcast generation process timed out. Please try with shorter text or try again later.")
400
- except Exception as e:
401
- raise Exception(f"Error generating podcast: {str(e)}")
402
-
403
- async def _generate_podcast_internal(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
404
- if progress:
405
- progress.progress(0.2, "Generating podcast script...")
406
-
407
- podcast_json = await self.generate_script(input_text, language, api_key, file_obj, progress)
408
-
409
- if progress:
410
- progress.progress(0.5, "Converting text to speech...")
411
-
412
- # Process TTS in batches for concurrent processing
413
- audio_files = []
414
- total_lines = len(podcast_json['podcast'])
415
-
416
- # Define batch size to control concurrency
417
- batch_size = 10 # Adjust based on system resources
418
-
419
- # Process in batches
420
- for batch_start in range(0, total_lines, batch_size):
421
- batch_end = min(batch_start + batch_size, total_lines)
422
- batch = podcast_json['podcast'][batch_start:batch_end]
423
-
424
- # Create tasks for concurrent processing
425
- tts_tasks = []
426
- for item in batch:
427
- tts_task = self.tts_generate(item['line'], item['speaker'], speaker1, speaker2)
428
- tts_tasks.append(tts_task)
429
-
430
- try:
431
- # Process batch concurrently
432
- batch_results = await asyncio.gather(*tts_tasks, return_exceptions=True)
433
-
434
- # Check for exceptions and handle results
435
- for i, result in enumerate(batch_results):
436
- if isinstance(result, Exception):
437
- # Clean up any files already created
438
- for file in audio_files:
439
- if os.path.exists(file):
440
- os.remove(file)
441
- raise Exception(f"Error generating speech: {str(result)}")
442
- else:
443
- audio_files.append(result)
444
-
445
- # Update progress
446
- if progress:
447
- current_progress = 0.5 + (0.4 * (batch_end / total_lines))
448
- progress.progress(current_progress, f"Processed {batch_end}/{total_lines} speech segments...")
449
-
450
- except Exception as e:
451
- # Clean up any files already created
452
- for file in audio_files:
453
- if os.path.exists(file):
454
- os.remove(file)
455
- raise Exception(f"Error in batch TTS generation: {str(e)}")
456
-
457
- combined_audio = await self.combine_audio_files(audio_files, progress)
458
- return combined_audio
459
-
460
- async def process_input(input_text: str, input_file, language: str, speaker1: str, speaker2: str, api_key: str = "", progress=None) -> str:
461
- start_time = time.time()
462
-
463
- voice_names = {
464
- "Andrew - English (United States)": "en-US-AndrewMultilingualNeural",
465
- "Ava - English (United States)": "en-US-AvaMultilingualNeural",
466
- "Brian - English (United States)": "en-US-BrianMultilingualNeural",
467
- "Emma - English (United States)": "en-US-EmmaMultilingualNeural",
468
- "Florian - German (Germany)": "de-DE-FlorianMultilingualNeural",
469
- "Seraphina - German (Germany)": "de-DE-SeraphinaMultilingualNeural",
470
- "Remy - French (France)": "fr-FR-RemyMultilingualNeural",
471
- "Vivienne - French (France)": "fr-FR-VivienneMultilingualNeural"
472
- }
473
-
474
- speaker1 = voice_names[speaker1]
475
- speaker2 = voice_names[speaker2]
476
-
477
- try:
478
- if progress:
479
- progress.progress(0.05, "Processing input...")
480
-
481
- if not api_key:
482
- api_key = os.getenv("GENAI_API_KEY")
483
- if not api_key:
484
- raise Exception("No API key provided. Please provide a Gemini API key.")
485
-
486
- podcast_generator = PodcastGenerator()
487
- podcast = await podcast_generator.generate_podcast(input_text, language, speaker1, speaker2, api_key, input_file, progress)
488
-
489
- end_time = time.time()
490
- print(f"Total podcast generation time: {end_time - start_time:.2f} seconds")
491
- return podcast
492
-
493
- except Exception as e:
494
- # Ensure we show a user-friendly error
495
- error_msg = str(e)
496
- if "rate limit" in error_msg.lower():
497
- raise Exception("Rate limit exceeded. Please try again later or use your own API key.")
498
- elif "timeout" in error_msg.lower():
499
- raise Exception("The request timed out. This could be due to server load or the length of your input. Please try again with shorter text.")
500
- else:
501
- raise Exception(f"Error: {error_msg}")
502
-
503
- # Streamlit UI
504
- def main():
505
- st.set_page_config(page_title="PodcastGen 🎙️", page_icon="🎙️", layout="wide")
506
-
507
- st.title("PodcastGen 🎙️")
508
- st.write("Generate a 2-speaker podcast from text input or documents!")
509
-
510
- with st.sidebar:
511
- st.header("Configuration")
512
- api_key = st.text_input("Your Gemini API Key (Optional)", type="password",
513
- help="In case you are getting rate limited")
514
-
515
- language_options = [
516
- "Auto Detect",
517
- "Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
518
- "Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
519
- "Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
520
- "Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
521
- "Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
522
- "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
523
- "Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
524
- "Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
525
- "Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
526
- "Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
527
- "Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
528
- "Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
529
- "Uzbek", "Vietnamese", "Welsh", "Zulu"
530
- ]
531
- language = st.selectbox("Language", language_options, index=0)
532
-
533
- voice_options = [
534
- "Andrew - English (United States)",
535
- "Ava - English (United States)",
536
- "Brian - English (United States)",
537
- "Emma - English (United States)",
538
- "Florian - German (Germany)",
539
- "Seraphina - German (Germany)",
540
- "Remy - French (France)",
541
- "Vivienne - French (France)"
542
- ]
543
- speaker1 = st.selectbox("Speaker 1 Voice", voice_options, index=0)
544
- speaker2 = st.selectbox("Speaker 2 Voice", voice_options, index=1)
545
-
546
- col1, col2 = st.columns([2, 1])
547
-
548
- with col1:
549
- input_text = st.text_area("Input Text", height=250)
550
-
551
- with col2:
552
- uploaded_file = st.file_uploader("Or Upload a PDF or TXT file", type=["pdf", "txt"])
553
-
554
- if st.button("Generate Podcast"):
555
- if not input_text and not uploaded_file:
556
- st.error("Please provide either input text or upload a file.")
557
- return
558
-
559
- # Create a progress bar for the async operation
560
- progress_bar = st.progress(0)
561
- status_text = st.empty()
562
-
563
- # Create a progress wrapper for compatibility with the existing code
564
- class StreamlitProgress:
565
- def progress(self, value, text=None):
566
- progress_bar.progress(value)
567
- if text:
568
- status_text.text(text)
569
-
570
- try:
571
- # Prepare file if uploaded
572
- file_obj = None
573
- if uploaded_file:
574
- # Save the uploaded file to a temporary location
575
- file_path = f"temp_upload_{uuid.uuid4()}{os.path.splitext(uploaded_file.name)[1]}"
576
- with open(file_path, "wb") as f:
577
- f.write(uploaded_file.getbuffer())
578
-
579
- class FileWrapper:
580
- def __init__(self, path, name):
581
- self.name = name
582
- self.path = path
583
-
584
- @property
585
- def name(self):
586
- return self._name
587
-
588
- @name.setter
589
- def name(self, value):
590
- self._name = value
591
-
592
- file_obj = FileWrapper(file_path, uploaded_file.name)
593
- file_obj.name = file_path # Set the path as the name for proper file reading
594
-
595
- # Run the async function in a new event loop
596
- progress_wrapper = StreamlitProgress()
597
- audio_file = asyncio.run(process_input(
598
- input_text,
599
- file_obj,
600
- language,
601
- speaker1,
602
- speaker2,
603
- api_key,
604
- progress_wrapper
605
- ))
606
-
607
- # Display the audio
608
- st.subheader("Generated Podcast")
609
- st.audio(audio_file, format="audio/wav")
610
-
611
- # Provide a download button
612
- with open(audio_file, "rb") as f:
613
- audio_bytes = f.read()
614
-
615
- st.download_button(
616
- label="Download Podcast",
617
- data=audio_bytes,
618
- file_name="podcast.wav",
619
- mime="audio/wav"
620
- )
621
-
622
- # Clean up the temporary file
623
- if file_obj:
624
- try:
625
- os.remove(file_path)
626
- except:
627
- pass
628
-
629
- except Exception as e:
630
- st.error(str(e))
631
-
632
- if __name__ == "__main__":
633
  main()
 
1
+ import gradio as gr
2
+ from pydub import AudioSegment
3
+ from google import genai
4
+ from google.genai import types
5
+ import json
6
+ import uuid
7
+ import edge_tts
8
+ import asyncio
9
+ import aiofiles
10
+ import os
11
+ import time
12
+ import mimetypes
13
+ from typing import List, Dict
14
+
15
+ # Constants
16
+ MAX_FILE_SIZE_MB = 20
17
+ MAX_FILE_SIZE_BYTES = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
18
+
19
+ class PodcastGenerator:
20
+ def __init__(self):
21
+ pass
22
+
23
+ async def generate_script(self, prompt: str, language: str, api_key: str, file_obj=None, progress=None) -> Dict:
24
+ example = """
25
+ {
26
+ "topic": "AGI",
27
+ "podcast": [
28
+ {
29
+ "speaker": 2,
30
+ "line": "So, AGI, huh? Seems like everyone's talking about it these days."
31
+ },
32
+ {
33
+ "speaker": 1,
34
+ "line": "Yeah, it's definitely having a moment, isn't it?"
35
+ },
36
+ {
37
+ "speaker": 2,
38
+ "line": "It is and for good reason, right? I mean, you've been digging into this stuff, listening to the podcasts and everything. What really stood out to you? What got you hooked?"
39
+ },
40
+ {
41
+ "speaker": 1,
42
+ "line": "Honestly, it's the sheer scale of what AGI could do. We're talking about potentially reshaping well everything."
43
+ },
44
+ {
45
+ "speaker": 2,
46
+ "line": "No kidding, but let's be real. Sometimes it feels like every other headline is either hyping AGI up as this technological utopia or painting it as our inevitable robot overlords."
47
+ },
48
+ {
49
+ "speaker": 1,
50
+ "line": "It's easy to get lost in the noise, for sure."
51
+ },
52
+ {
53
+ "speaker": 2,
54
+ "line": "Exactly. So how about we try to cut through some of that, shall we?"
55
+ },
56
+ {
57
+ "speaker": 1,
58
+ "line": "Sounds like a plan."
59
+ },
60
+ {
61
+ "speaker": 2,
62
+ "line": "Okay, so first things first, AGI, what is it really? And I don't just mean some dictionary definition, we're talking about something way bigger than just a super smart computer, right?"
63
+ },
64
+ {
65
+ "speaker": 1,
66
+ "line": "Right, it's not just about more processing power or better algorithms, it's about a fundamental shift in how we think about intelligence itself."
67
+ },
68
+ {
69
+ "speaker": 2,
70
+ "line": "So like, instead of programming a machine for a specific task, we're talking about creating something that can learn and adapt like we do."
71
+ },
72
+ {
73
+ "speaker": 1,
74
+ "line": "Exactly, think of it this way: Right now, we've got AI that can beat a grandmaster at chess but ask that same AI to, say, write a poem or compose a symphony. No chance."
75
+ },
76
+ {
77
+ "speaker": 2,
78
+ "line": "Okay, I see. So, AGI is about bridging that gap, creating something that can move between those different realms of knowledge seamlessly."
79
+ },
80
+ {
81
+ "speaker": 1,
82
+ "line": "Precisely. It's about replicating that uniquely human ability to learn something new and apply that knowledge in completely different contexts and that's a tall order, let me tell you."
83
+ },
84
+ {
85
+ "speaker": 2,
86
+ "line": "I bet. I mean, think about how much we still don't even understand about our own brains."
87
+ },
88
+ {
89
+ "speaker": 1,
90
+ "line": "That's exactly it. We're essentially trying to reverse-engineer something we don't fully comprehend."
91
+ },
92
+ {
93
+ "speaker": 2,
94
+ "line": "And how are researchers even approaching that? What are some of the big ideas out there?"
95
+ },
96
+ {
97
+ "speaker": 1,
98
+ "line": "Well, there are a few different schools of thought. One is this idea of neuromorphic computing where they're literally trying to build computer chips that mimic the structure and function of the human brain."
99
+ },
100
+ {
101
+ "speaker": 2,
102
+ "line": "Wow, so like actually replicating the physical architecture of the brain. That's wild."
103
+ },
104
+ {
105
+ "speaker": 1,
106
+ "line": "It's pretty mind-blowing stuff and then you've got folks working on something called whole brain emulation."
107
+ },
108
+ {
109
+ "speaker": 2,
110
+ "line": "Okay, and what's that all about?"
111
+ },
112
+ {
113
+ "speaker": 1,
114
+ "line": "The basic idea there is to create a complete digital copy of a human brain down to the last neuron and synapse and run it on a sufficiently powerful computer simulation."
115
+ },
116
+ {
117
+ "speaker": 2,
118
+ "line": "Hold on, a digital copy of an entire brain, that sounds like something straight out of science fiction."
119
+ },
120
+ {
121
+ "speaker": 1,
122
+ "line": "It does, doesn't it? But it gives you an idea of the kind of ambition we're talking about here and the truth is we're still a long way off from truly achieving AGI, no matter which approach you look at."
123
+ },
124
+ {
125
+ "speaker": 2,
126
+ "line": "That makes sense but it's still exciting to think about the possibilities, even if they're a ways off."
127
+ },
128
+ {
129
+ "speaker": 1,
130
+ "line": "Absolutely and those possibilities are what really get people fired up about AGI, right? Yeah."
131
+ },
132
+ {
133
+ "speaker": 2,
134
+ "line": "For sure. In fact, I remember you mentioning something in that podcast about AGI's potential to revolutionize scientific research. Something about supercharging breakthroughs."
135
+ },
136
+ {
137
+ "speaker": 1,
138
+ "line": "Oh, absolutely. Imagine an AI that doesn't just crunch numbers but actually understands scientific data the way a human researcher does. We're talking about potential breakthroughs in everything from medicine and healthcare to material science and climate change."
139
+ },
140
+ {
141
+ "speaker": 2,
142
+ "line": "It's like giving scientists this incredibly powerful new tool to tackle some of the biggest challenges we face."
143
+ },
144
+ {
145
+ "speaker": 1,
146
+ "line": "Exactly, it could be a total game changer."
147
+ },
148
+ {
149
+ "speaker": 2,
150
+ "line": "Okay, but let's be real, every coin has two sides. What about the potential downsides of AGI? Because it can't all be sunshine and roses, right?"
151
+ },
152
+ {
153
+ "speaker": 1,
154
+ "line": "Right, there are definitely valid concerns. Probably the biggest one is the impact on the job market. As AGI gets more sophisticated, there's a real chance it could automate a lot of jobs that are currently done by humans."
155
+ },
156
+ {
157
+ "speaker": 2,
158
+ "line": "So we're not just talking about robots taking over factories but potentially things like, what, legal work, analysis, even creative fields?"
159
+ },
160
+ {
161
+ "speaker": 1,
162
+ "line": "Potentially, yes. And that raises a whole host of questions about what happens to those workers, how we retrain them, how we ensure that the benefits of AGI are shared equitably."
163
+ },
164
+ {
165
+ "speaker": 2,
166
+ "line": "Right, because it's not just about the technology itself, but how we choose to integrate it into society."
167
+ },
168
+ {
169
+ "speaker": 1,
170
+ "line": "Absolutely. We need to be having these conversations now about ethics, about regulation, about how to make sure AGI is developed and deployed responsibly."
171
+ },
172
+ {
173
+ "speaker": 2,
174
+ "line": "So it's less about preventing some kind of sci-fi robot apocalypse and more about making sure we're steering this technology in the right direction from the get-go."
175
+ },
176
+ {
177
+ "speaker": 1,
178
+ "line": "Exactly, AGI has the potential to be incredibly beneficial, but it's not going to magically solve all our problems. It's on us to make sure we're using it for good."
179
+ },
180
+ {
181
+ "speaker": 2,
182
+ "line": "It's like you said earlier, it's about shaping the future of intelligence."
183
+ },
184
+ {
185
+ "speaker": 1,
186
+ "line": "I like that. It really is."
187
+ },
188
+ {
189
+ "speaker": 2,
190
+ "line": "And honestly, that's a responsibility that extends beyond just the researchers and the policymakers."
191
+ },
192
+ {
193
+ "speaker": 1,
194
+ "line": "100%"
195
+ },
196
+ {
197
+ "speaker": 2,
198
+ "line": "So to everyone listening out there I'll leave you with this. As AGI continues to develop, what role do you want to play in shaping its future?"
199
+ },
200
+ {
201
+ "speaker": 1,
202
+ "line": "That's a question worth pondering."
203
+ },
204
+ {
205
+ "speaker": 2,
206
+ "line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
207
+ },
208
+ {
209
+ "speaker": 1,
210
+ "line": "Peace."
211
+ }
212
+ ]
213
+ }
214
+ """
215
+
216
+ if language == "Auto Detect":
217
+ language_instruction = "- The podcast MUST be in the same language as the user input."
218
+ else:
219
+ language_instruction = f"- The podcast MUST be in {language} language"
220
+
221
+ system_prompt = f"""
222
+ You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input.
223
+ {language_instruction}
224
+ - The podcast should have 2 speakers.
225
+ - The podcast should be long.
226
+ - Do not use names for the speakers.
227
+ - The podcast should be interesting, lively, and engaging, and hook the listener from the start.
228
+ - The input text might be disorganized or unformatted, originating from sources like PDFs or text files. Ignore any formatting inconsistencies or irrelevant details; your task is to distill the essential points, identify key definitions, and highlight intriguing facts that would be suitable for discussion in a podcast.
229
+ - The script must be in JSON format.
230
+ Follow this example structure:
231
+ {example}
232
+ """
233
+ user_prompt = ""
234
+ if prompt and file_obj:
235
+ user_prompt = f"Please generate a podcast script based on the uploaded file following user input:\n{prompt}"
236
+ elif prompt:
237
+ user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
238
+ else:
239
+ user_prompt = "Please generate a podcast script based on the uploaded file."
240
+
241
+ messages = []
242
+
243
+ # If file is provided, add it to the messages
244
+ if file_obj:
245
+ file_data = await self._read_file_bytes(file_obj)
246
+ mime_type = self._get_mime_type(file_obj.name)
247
+
248
+ messages.append(
249
+ types.Content(
250
+ role="user",
251
+ parts=[
252
+ types.Part.from_bytes(
253
+ data=file_data,
254
+ mime_type=mime_type,
255
+ )
256
+ ],
257
+ )
258
+ )
259
+
260
+ # Add text prompt
261
+ messages.append(
262
+ types.Content(
263
+ role="user",
264
+ parts=[
265
+ types.Part.from_text(text=user_prompt)
266
+ ],
267
+ )
268
+ )
269
+
270
+ client = genai.Client(api_key=api_key)
271
+
272
+ safety_settings = [
273
+ {
274
+ "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
275
+ "threshold": "BLOCK_NONE"
276
+ },
277
+ {
278
+ "category": "HARM_CATEGORY_HARASSMENT",
279
+ "threshold": "BLOCK_NONE"
280
+ },
281
+ {
282
+ "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
283
+ "threshold": "BLOCK_NONE"
284
+ },
285
+ {
286
+ "category": "HARM_CATEGORY_HATE_SPEECH",
287
+ "threshold": "BLOCK_NONE"
288
+ }
289
+ ]
290
+
291
+ try:
292
+ if progress:
293
+ progress(0.3, "Generating podcast script...")
294
+
295
+ # Add timeout to the API call
296
+ response = await asyncio.wait_for(
297
+ client.aio.models.generate_content(
298
+ model="gemini-2.0-flash",
299
+ contents=messages,
300
+ config=types.GenerateContentConfig(
301
+ temperature=1,
302
+ response_mime_type="application/json",
303
+ safety_settings=[
304
+ types.SafetySetting(
305
+ category=safety_setting["category"],
306
+ threshold=safety_setting["threshold"]
307
+ ) for safety_setting in safety_settings
308
+ ],
309
+ system_instruction=system_prompt
310
+ )
311
+ ),
312
+ timeout=60 # 60 seconds timeout
313
+ )
314
+ except asyncio.TimeoutError:
315
+ raise Exception("The script generation request timed out. Please try again later.")
316
+ except Exception as e:
317
+ if "API key not valid" in str(e):
318
+ raise Exception("Invalid API key. Please provide a valid Gemini API key.")
319
+ elif "rate limit" in str(e).lower():
320
+ raise Exception("Rate limit exceeded for the API key. Please try again later or provide your own Gemini API key.")
321
+ else:
322
+ raise Exception(f"Failed to generate podcast script: {e}")
323
+
324
+ print(f"Generated podcast script:\n{response.text}")
325
+
326
+ if progress:
327
+ progress(0.4, "Script generated successfully!")
328
+
329
+ return json.loads(response.text)
330
+
331
+ async def _read_file_bytes(self, file_obj) -> bytes:
332
+ """Read file bytes from a file object"""
333
+ # Check file size before reading
334
+ if hasattr(file_obj, 'size'):
335
+ file_size = file_obj.size
336
+ else:
337
+ file_size = os.path.getsize(file_obj.name)
338
+
339
+ if file_size > MAX_FILE_SIZE_BYTES:
340
+ raise Exception(f"File size exceeds the {MAX_FILE_SIZE_MB}MB limit. Please upload a smaller file.")
341
+
342
+ if hasattr(file_obj, 'read'):
343
+ return file_obj.read()
344
+ else:
345
+ async with aiofiles.open(file_obj.name, 'rb') as f:
346
+ return await f.read()
347
+
348
+ def _get_mime_type(self, filename: str) -> str:
349
+ """Determine MIME type based on file extension"""
350
+ ext = os.path.splitext(filename)[1].lower()
351
+ if ext == '.pdf':
352
+ return "application/pdf"
353
+ elif ext == '.txt':
354
+ return "text/plain"
355
+ else:
356
+ # Fallback to the default mime type detector
357
+ mime_type, _ = mimetypes.guess_type(filename)
358
+ return mime_type or "application/octet-stream"
359
+
360
+ async def tts_generate(self, text: str, speaker: int, speaker1: str, speaker2: str) -> str:
361
+ voice = speaker1 if speaker == 1 else speaker2
362
+ speech = edge_tts.Communicate(text, voice)
363
+
364
+ temp_filename = f"temp_{uuid.uuid4()}.wav"
365
+ try:
366
+ # Add timeout to TTS generation
367
+ await asyncio.wait_for(speech.save(temp_filename), timeout=30) # 30 seconds timeout
368
+ return temp_filename
369
+ except asyncio.TimeoutError:
370
+ if os.path.exists(temp_filename):
371
+ os.remove(temp_filename)
372
+ raise Exception("Text-to-speech generation timed out. Please try with a shorter text.")
373
+ except Exception as e:
374
+ if os.path.exists(temp_filename):
375
+ os.remove(temp_filename)
376
+ raise e
377
+
378
+ async def combine_audio_files(self, audio_files: List[str], progress=None) -> str:
379
+ if progress:
380
+ progress(0.9, "Combining audio files...")
381
+
382
+ combined_audio = AudioSegment.empty()
383
+ for audio_file in audio_files:
384
+ combined_audio += AudioSegment.from_file(audio_file)
385
+ os.remove(audio_file) # Clean up temporary files
386
+
387
+ output_filename = f"output_{uuid.uuid4()}.wav"
388
+ combined_audio.export(output_filename, format="wav")
389
+
390
+ if progress:
391
+ progress(1.0, "Podcast generated successfully!")
392
+
393
+ return output_filename
394
+
395
+ async def generate_podcast(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
396
+ try:
397
+ if progress:
398
+ progress(0.1, "Starting podcast generation...")
399
+
400
+ # Set overall timeout for the entire process
401
+ return await asyncio.wait_for(
402
+ self._generate_podcast_internal(input_text, language, speaker1, speaker2, api_key, file_obj, progress),
403
+ timeout=600 # 10 minutes total timeout
404
+ )
405
+ except asyncio.TimeoutError:
406
+ raise Exception("The podcast generation process timed out. Please try with shorter text or try again later.")
407
+ except Exception as e:
408
+ raise Exception(f"Error generating podcast: {str(e)}")
409
+
410
+ async def _generate_podcast_internal(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str, file_obj=None, progress=None) -> str:
411
+ if progress:
412
+ progress(0.2, "Generating podcast script...")
413
+
414
+ podcast_json = await self.generate_script(input_text, language, api_key, file_obj, progress)
415
+
416
+ if progress:
417
+ progress(0.5, "Converting text to speech...")
418
+
419
+ # Process TTS in batches for concurrent processing
420
+ audio_files = []
421
+ total_lines = len(podcast_json['podcast'])
422
+
423
+ # Define batch size to control concurrency
424
+ batch_size = 10 # Adjust based on system resources
425
+
426
+ # Process in batches
427
+ for batch_start in range(0, total_lines, batch_size):
428
+ batch_end = min(batch_start + batch_size, total_lines)
429
+ batch = podcast_json['podcast'][batch_start:batch_end]
430
+
431
+ # Create tasks for concurrent processing
432
+ tts_tasks = []
433
+ for item in batch:
434
+ tts_task = self.tts_generate(item['line'], item['speaker'], speaker1, speaker2)
435
+ tts_tasks.append(tts_task)
436
+
437
+ try:
438
+ # Process batch concurrently
439
+ batch_results = await asyncio.gather(*tts_tasks, return_exceptions=True)
440
+
441
+ # Check for exceptions and handle results
442
+ for i, result in enumerate(batch_results):
443
+ if isinstance(result, Exception):
444
+ # Clean up any files already created
445
+ for file in audio_files:
446
+ if os.path.exists(file):
447
+ os.remove(file)
448
+ raise Exception(f"Error generating speech: {str(result)}")
449
+ else:
450
+ audio_files.append(result)
451
+
452
+ # Update progress
453
+ if progress:
454
+ current_progress = 0.5 + (0.4 * (batch_end / total_lines))
455
+ progress(current_progress, f"Processed {batch_end}/{total_lines} speech segments...")
456
+
457
+ except Exception as e:
458
+ # Clean up any files already created
459
+ for file in audio_files:
460
+ if os.path.exists(file):
461
+ os.remove(file)
462
+ raise Exception(f"Error in batch TTS generation: {str(e)}")
463
+
464
+ combined_audio = await self.combine_audio_files(audio_files, progress)
465
+ return combined_audio
466
+
467
+ async def process_input(input_text: str, input_file, language: str, speaker1: str, speaker2: str, api_key: str = "", progress=None) -> str:
468
+ start_time = time.time()
469
+
470
+ voice_names = {
471
+ "Andrew - English (United States)": "en-US-AndrewMultilingualNeural",
472
+ "Ava - English (United States)": "en-US-AvaMultilingualNeural",
473
+ "Brian - English (United States)": "en-US-BrianMultilingualNeural",
474
+ "Emma - English (United States)": "en-US-EmmaMultilingualNeural",
475
+ "Florian - German (Germany)": "de-DE-FlorianMultilingualNeural",
476
+ "Seraphina - German (Germany)": "de-DE-SeraphinaMultilingualNeural",
477
+ "Remy - French (France)": "fr-FR-RemyMultilingualNeural",
478
+ "Vivienne - French (France)": "fr-FR-VivienneMultilingualNeural"
479
+ }
480
+
481
+ speaker1 = voice_names[speaker1]
482
+ speaker2 = voice_names[speaker2]
483
+
484
+ try:
485
+ if progress:
486
+ progress(0.05, "Processing input...")
487
+
488
+ if not api_key:
489
+ api_key = os.getenv("GENAI_API_KEY")
490
+ if not api_key:
491
+ raise Exception("No API key provided. Please provide a Gemini API key.")
492
+
493
+ podcast_generator = PodcastGenerator()
494
+ podcast = await podcast_generator.generate_podcast(input_text, language, speaker1, speaker2, api_key, input_file, progress)
495
+
496
+ end_time = time.time()
497
+ print(f"Total podcast generation time: {end_time - start_time:.2f} seconds")
498
+ return podcast
499
+
500
+ except Exception as e:
501
+ # Ensure we show a user-friendly error
502
+ error_msg = str(e)
503
+ if "rate limit" in error_msg.lower():
504
+ raise Exception("Rate limit exceeded. Please try again later or use your own API key.")
505
+ elif "timeout" in error_msg.lower():
506
+ raise Exception("The request timed out. This could be due to server load or the length of your input. Please try again with shorter text.")
507
+ else:
508
+ raise Exception(f"Error: {error_msg}")
509
+
510
+ # Gradio UI
511
+ def generate_podcast_gradio(input_text, input_file, language, speaker1, speaker2, api_key, progress=gr.Progress()):
512
+ try:
513
+ # Handle the file if uploaded
514
+ file_obj = None
515
+ if input_file is not None:
516
+ file_obj = input_file
517
+
518
+ # Use the progress function from Gradio
519
+ def progress_callback(value, text):
520
+ progress(value, text)
521
+
522
+ # Run the async function in the event loop
523
+ result = asyncio.run(process_input(
524
+ input_text,
525
+ file_obj,
526
+ language,
527
+ speaker1,
528
+ speaker2,
529
+ api_key,
530
+ progress_callback
531
+ ))
532
+
533
+ return result, None # Return audio file and no error
534
+ except Exception as e:
535
+ error_message = str(e)
536
+ return None, error_message # Return no audio file and error message
537
+
538
+ def main():
539
+ # Define language options
540
+ language_options = [
541
+ "Auto Detect",
542
+ "Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
543
+ "Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
544
+ "Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
545
+ "Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
546
+ "Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
547
+ "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
548
+ "Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
549
+ "Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
550
+ "Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
551
+ "Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
552
+ "Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
553
+ "Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
554
+ "Uzbek", "Vietnamese", "Welsh", "Zulu"
555
+ ]
556
+
557
+ # Define voice options
558
+ voice_options = [
559
+ "Andrew - English (United States)",
560
+ "Ava - English (United States)",
561
+ "Brian - English (United States)",
562
+ "Emma - English (United States)",
563
+ "Florian - German (Germany)",
564
+ "Seraphina - German (Germany)",
565
+ "Remy - French (France)",
566
+ "Vivienne - French (France)"
567
+ ]
568
+
569
+ # Create Gradio interface
570
+ with gr.Blocks(title="PodcastGen 🎙️") as demo:
571
+ gr.Markdown("# PodcastGen 🎙️")
572
+ gr.Markdown("Generate a 2-speaker podcast from text input or documents!")
573
+
574
+ with gr.Row():
575
+ with gr.Column(scale=2):
576
+ input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text for podcast generation...")
577
+
578
+ with gr.Column(scale=1):
579
+ input_file = gr.File(label="Or Upload a PDF or TXT file", file_types=["pdf", "txt"])
580
+
581
+ with gr.Row():
582
+ with gr.Column():
583
+ api_key = gr.Textbox(label="Your Gemini API Key (Optional)", placeholder="Enter API key here if you're getting rate limited", type="password")
584
+ language = gr.Dropdown(label="Language", choices=language_options, value="Auto Detect")
585
+
586
+ with gr.Column():
587
+ speaker1 = gr.Dropdown(label="Speaker 1 Voice", choices=voice_options, value="Andrew - English (United States)")
588
+ speaker2 = gr.Dropdown(label="Speaker 2 Voice", choices=voice_options, value="Ava - English (United States)")
589
+
590
+ generate_btn = gr.Button("Generate Podcast", variant="primary")
591
+
592
+ with gr.Row():
593
+ output_audio = gr.Audio(label="Generated Podcast", type="filepath", format="wav")
594
+ error_output = gr.Textbox(label="Error (if any)", visible=True)
595
+
596
+ generate_btn.click(
597
+ fn=generate_podcast_gradio,
598
+ inputs=[input_text, input_file, language, speaker1, speaker2, api_key],
599
+ outputs=[output_audio, error_output]
600
+ )
601
+
602
+ demo.launch()
603
+
604
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
605
  main()