Rausda6 commited on
Commit
930b87c
·
verified ·
1 Parent(s): 84117d5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +569 -108
app.py CHANGED
@@ -1,139 +1,600 @@
1
  import gradio as gr
2
  from pydub import AudioSegment
 
 
 
 
3
  import edge_tts
4
  import asyncio
5
  import aiofiles
6
  import os
7
  import time
8
  import mimetypes
9
- import uuid
10
- import json
11
  from typing import List, Dict
12
 
13
- # Model imports
14
- import torch
15
- from transformers import AutoTokenizer, AutoModelForCausalLM, StoppingCriteria, StoppingCriteriaList
16
-
17
- # Configuration
18
- MODEL_ID = os.getenv("GEMMA_MODEL_PATH", "tabularisai/german-gemma-3-1b-it")
19
- HF_TOKEN = os.getenv("Tokentest") # Optional
20
-
21
- # Load tokenizer and model using external snippet
22
- print(f"Loading model {MODEL_ID}...")
23
- tokenizer = AutoTokenizer.from_pretrained(
24
- MODEL_ID,
25
- trust_remote_code=True,
26
- use_auth_token=HF_TOKEN
27
- )
28
- model = AutoModelForCausalLM.from_pretrained(
29
- MODEL_ID,
30
- trust_remote_code=True,
31
- use_auth_token=HF_TOKEN,
32
- torch_dtype=(torch.bfloat16 if torch.cuda.is_available() else torch.float32),
33
- device_map="auto"
34
- ).eval()
35
-
36
- # Stopping criteria tokens
37
- PAD = tokenizer.pad_token_id or tokenizer.eos_token_id
38
- EOT = tokenizer.convert_tokens_to_ids('<end_of_turn>')
39
 
40
  class PodcastGenerator:
41
- MAX_FILE_MB = 20
42
- MAX_FILE_BYTES = MAX_FILE_MB * 1024 * 1024
43
-
44
  def __init__(self):
45
  pass
46
 
47
- async def generate_script(self, prompt: str, language: str, file_obj=None, progress=None) -> Dict:
48
- example = '{"topic": "AGI", "podcast": [ ... ] }'
49
- lang_inst = (
50
- "- The podcast MUST be in the same language as the user input."
51
- if language == "Auto Detect"
52
- else f"- The podcast MUST be in {language} language"
53
- )
54
- system_prompt = (
55
- "You are a professional podcast generator. Your task is to generate a professional podcast script..."
56
- f"\n{lang_inst}\n- The podcast should have 2 speakers.\n- The podcast should be long."
57
- "\n- Do not use names for the speakers.\n- The podcast should be interesting, lively, and engaging..."
58
- "\n- The script must be in JSON format. Follow this example structure:" + example
59
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  if prompt and file_obj:
61
- user_prompt = f"Generate podcast script based on file and prompt:\n{prompt}"
62
  elif prompt:
63
- user_prompt = f"Generate podcast script based on prompt:\n{prompt}"
64
  else:
65
- user_prompt = "Generate podcast script based on uploaded file."
66
-
67
- full_prompt = system_prompt + "\n\n" + user_prompt
68
-
69
- # sync generation in executor using model.generate
70
- def gen_sync():
71
- inputs = tokenizer(full_prompt, return_tensors="pt").to(model.device)
72
- stop_crit = StoppingCriteriaList([StoppingCriteria(max_length=512)])
73
- outputs = model.generate(
74
- **inputs,
75
- max_new_tokens=512,
76
- do_sample=True,
77
- pad_token_id=PAD,
78
- eos_token_id=EOT
 
 
 
 
 
79
  )
80
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
81
 
82
- loop = asyncio.get_event_loop()
83
- text = await loop.run_in_executor(None, gen_sync)
84
- return json.loads(text)
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  async def _read_file_bytes(self, file_obj) -> bytes:
87
- size = getattr(file_obj, 'size', os.path.getsize(file_obj.name))
88
- if size > self.MAX_FILE_BYTES:
89
- raise Exception(f"File > {self.MAX_FILE_MB}MB")
90
- return file_obj.read() if hasattr(file_obj, 'read') else await aiofiles.open(file_obj.name, 'rb').read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- async def tts_generate(self, text: str, speaker: int, s1: str, s2: str) -> str:
93
- voice = s1 if speaker == 1 else s2
94
  speech = edge_tts.Communicate(text, voice)
95
- fname = f"tmp_{uuid.uuid4()}.wav"
96
- await speech.save(fname)
97
- return fname
98
-
99
- async def combine_audio_files(self, files: List[str], progress=None) -> str:
100
- combined = AudioSegment.empty()
101
- for f in files:
102
- combined += AudioSegment.from_file(f)
103
- os.remove(f)
104
- out = f"out_{uuid.uuid4()}.wav"
105
- combined.export(out, format="wav")
106
- return out
107
-
108
- async def generate_podcast(self, text: str, lang: str, sp1: str, sp2: str, file_obj=None, progress=None) -> str:
109
- pj = await self.generate_script(text, lang, file_obj, progress)
110
- parts = pj['podcast']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  audio_files = []
112
- for seg in parts:
113
- audio_files.append(await self.tts_generate(seg['line'], seg['speaker'], sp1, sp2))
114
- return await self.combine_audio_files(audio_files)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
  # Gradio UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- def run_app():
119
- langs = ["Auto Detect","German","English","French"]
120
- voices = ["Florian - German (Germany)", "Andrew - English (US)"]
121
- gen = PodcastGenerator()
122
-
123
- with gr.Blocks() as demo:
124
- inp = gr.Textbox(label="Input Text")
125
- file_u = gr.File(label="Upload PDF/TXT")
126
- lang_dd = gr.Dropdown(langs, value="Auto Detect", label="Language")
127
- sp1 = gr.Dropdown(voices, value=voices[0], label="Speaker 1")
128
- sp2 = gr.Dropdown(voices, value=voices[1], label="Speaker 2")
129
- out = gr.Audio(label="Podcast", type="filepath")
130
- btn = gr.Button("Generate")
131
- btn.click(
132
- lambda t,f,l,a,b: asyncio.run(gen.generate_podcast(t,l,a,b,f)),
133
- inputs=[inp, file_u, lang_dd, sp1, sp2],
134
- outputs=[out]
135
  )
 
136
  demo.launch()
137
 
138
- if __name__ == '__main__':
139
- run_app()
 
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
+ # Handle the file if uploaded
513
+ file_obj = None
514
+ if input_file is not None:
515
+ file_obj = input_file
516
+
517
+ # Use the progress function from Gradio
518
+ def progress_callback(value, text):
519
+ progress(value, text)
520
+
521
+ # Run the async function in the event loop
522
+ result = asyncio.run(process_input(
523
+ input_text,
524
+ file_obj,
525
+ language,
526
+ speaker1,
527
+ speaker2,
528
+ api_key,
529
+ progress_callback
530
+ ))
531
+
532
+ return result
533
+
534
+ def main():
535
+ # Define language options
536
+ language_options = [
537
+ "Auto Detect",
538
+ "Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
539
+ "Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
540
+ "Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
541
+ "Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
542
+ "Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
543
+ "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
544
+ "Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
545
+ "Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
546
+ "Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
547
+ "Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
548
+ "Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
549
+ "Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
550
+ "Uzbek", "Vietnamese", "Welsh", "Zulu"
551
+ ]
552
+
553
+ # Define voice options
554
+ voice_options = [
555
+ "Andrew - English (United States)",
556
+ "Ava - English (United States)",
557
+ "Brian - English (United States)",
558
+ "Emma - English (United States)",
559
+ "Florian - German (Germany)",
560
+ "Seraphina - German (Germany)",
561
+ "Remy - French (France)",
562
+ "Vivienne - French (France)"
563
+ ]
564
+
565
+ # Create Gradio interface
566
+ with gr.Blocks(title="PodcastGen 🎙️") as demo:
567
+ gr.Markdown("# PodcastGen 🎙️")
568
+ gr.Markdown("Generate a 2-speaker podcast from text input or documents!")
569
+
570
+ with gr.Row():
571
+ with gr.Column(scale=2):
572
+ input_text = gr.Textbox(label="Input Text", lines=10, placeholder="Enter text for podcast generation...")
573
+
574
+ with gr.Column(scale=1):
575
+ input_file = gr.File(label="Or Upload a PDF or TXT file", file_types=[".pdf", ".txt"])
576
+
577
+ with gr.Row():
578
+ with gr.Column():
579
+ api_key = gr.Textbox(label="Your Gemini API Key (Optional)", placeholder="Enter API key here if you're getting rate limited", type="password")
580
+ language = gr.Dropdown(label="Language", choices=language_options, value="Auto Detect")
581
 
582
+ with gr.Column():
583
+ speaker1 = gr.Dropdown(label="Speaker 1 Voice", choices=voice_options, value="Andrew - English (United States)")
584
+ speaker2 = gr.Dropdown(label="Speaker 2 Voice", choices=voice_options, value="Ava - English (United States)")
585
+
586
+ generate_btn = gr.Button("Generate Podcast", variant="primary")
587
+
588
+ with gr.Row():
589
+ output_audio = gr.Audio(label="Generated Podcast", type="filepath", format="wav")
590
+
591
+ generate_btn.click(
592
+ fn=generate_podcast_gradio,
593
+ inputs=[input_text, input_file, language, speaker1, speaker2, api_key],
594
+ outputs=[output_audio]
 
 
 
 
595
  )
596
+
597
  demo.launch()
598
 
599
+ if __name__ == "__main__":
600
+ main()