saq1b commited on
Commit
dd9d0c7
β€’
1 Parent(s): 22185ea

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +13 -12
  2. app.py +313 -0
  3. requirements.txt +6 -0
README.md CHANGED
@@ -1,12 +1,13 @@
1
- ---
2
- title: Podcastgen
3
- emoji: 🌍
4
- colorFrom: gray
5
- colorTo: blue
6
- sdk: gradio
7
- sdk_version: 4.44.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
1
+ ---
2
+ title: PodcastGen
3
+ emoji: πŸŽ™οΈ
4
+ colorFrom: gray
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 4.44.0
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: Generate a 2-speaker podcast from text input or documents!
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from pydub import AudioSegment
3
+ from groq import AsyncGroq
4
+ import json
5
+ import uuid
6
+ import io
7
+ import edge_tts
8
+ import asyncio
9
+ import aiofiles
10
+ import PyPDF2
11
+ import os
12
+ from typing import List, Dict, Tuple
13
+
14
+ class PodcastGenerator:
15
+ def __init__(self, groq_api_key: str):
16
+ self.groq_client = AsyncGroq(api_key=groq_api_key)
17
+
18
+ async def generate_script(self, prompt: str) -> Dict:
19
+ example = """
20
+ {
21
+ "topic": "AGI",
22
+ "podcast": [
23
+ {
24
+ "speaker": 2,
25
+ "line": "So, AGI, huh? Seems like everyone's talking about it these days."
26
+ },
27
+ {
28
+ "speaker": 1,
29
+ "line": "Yeah, it's definitely having a moment, isn't it?"
30
+ },
31
+ {
32
+ "speaker": 2,
33
+ "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?"
34
+ },
35
+ {
36
+ "speaker": 1,
37
+ "line": "Honestly, it's the sheer scale of what AGI could do. We're talking about potentially reshaping well everything."
38
+ },
39
+ {
40
+ "speaker": 2,
41
+ "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."
42
+ },
43
+ {
44
+ "speaker": 1,
45
+ "line": "It's easy to get lost in the noise, for sure."
46
+ },
47
+ {
48
+ "speaker": 2,
49
+ "line": "Exactly. So how about we try to cut through some of that, shall we?"
50
+ },
51
+ {
52
+ "speaker": 1,
53
+ "line": "Sounds like a plan."
54
+ },
55
+ {
56
+ "speaker": 2,
57
+ "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?"
58
+ },
59
+ {
60
+ "speaker": 1,
61
+ "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."
62
+ },
63
+ {
64
+ "speaker": 2,
65
+ "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."
66
+ },
67
+ {
68
+ "speaker": 1,
69
+ "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."
70
+ },
71
+ {
72
+ "speaker": 2,
73
+ "line": "Okay, I see. So, AGI is about bridging that gap, creating something that can move between those different realms of knowledge seamlessly."
74
+ },
75
+ {
76
+ "speaker": 1,
77
+ "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."
78
+ },
79
+ {
80
+ "speaker": 2,
81
+ "line": "I bet. I mean, think about how much we still don't even understand about our own brains."
82
+ },
83
+ {
84
+ "speaker": 1,
85
+ "line": "That's exactly it. We're essentially trying to reverse-engineer something we don't fully comprehend."
86
+ },
87
+ {
88
+ "speaker": 2,
89
+ "line": "And how are researchers even approaching that? What are some of the big ideas out there?"
90
+ },
91
+ {
92
+ "speaker": 1,
93
+ "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."
94
+ },
95
+ {
96
+ "speaker": 2,
97
+ "line": "Wow, so like actually replicating the physical architecture of the brain. That's wild."
98
+ },
99
+ {
100
+ "speaker": 1,
101
+ "line": "It's pretty mind-blowing stuff and then you've got folks working on something called whole brain emulation."
102
+ },
103
+ {
104
+ "speaker": 2,
105
+ "line": "Okay, and what's that all about?"
106
+ },
107
+ {
108
+ "speaker": 1,
109
+ "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."
110
+ },
111
+ {
112
+ "speaker": 2,
113
+ "line": "Hold on, a digital copy of an entire brain, that sounds like something straight out of science fiction."
114
+ },
115
+ {
116
+ "speaker": 1,
117
+ "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."
118
+ },
119
+ {
120
+ "speaker": 2,
121
+ "line": "That makes sense but it's still exciting to think about the possibilities, even if they're a ways off."
122
+ },
123
+ {
124
+ "speaker": 1,
125
+ "line": "Absolutely and those possibilities are what really get people fired up about AGI, right? Yeah."
126
+ },
127
+ {
128
+ "speaker": 2,
129
+ "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."
130
+ },
131
+ {
132
+ "speaker": 1,
133
+ "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."
134
+ },
135
+ {
136
+ "speaker": 2,
137
+ "line": "It's like giving scientists this incredibly powerful new tool to tackle some of the biggest challenges we face."
138
+ },
139
+ {
140
+ "speaker": 1,
141
+ "line": "Exactly, it could be a total game changer."
142
+ },
143
+ {
144
+ "speaker": 2,
145
+ "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?"
146
+ },
147
+ {
148
+ "speaker": 1,
149
+ "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."
150
+ },
151
+ {
152
+ "speaker": 2,
153
+ "line": "So we're not just talking about robots taking over factories but potentially things like, what, legal work, analysis, even creative fields?"
154
+ },
155
+ {
156
+ "speaker": 1,
157
+ "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."
158
+ },
159
+ {
160
+ "speaker": 2,
161
+ "line": "Right, because it's not just about the technology itself, but how we choose to integrate it into society."
162
+ },
163
+ {
164
+ "speaker": 1,
165
+ "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."
166
+ },
167
+ {
168
+ "speaker": 2,
169
+ "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."
170
+ },
171
+ {
172
+ "speaker": 1,
173
+ "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."
174
+ },
175
+ {
176
+ "speaker": 2,
177
+ "line": "It's like you said earlier, it's about shaping the future of intelligence."
178
+ },
179
+ {
180
+ "speaker": 1,
181
+ "line": "I like that. It really is."
182
+ },
183
+ {
184
+ "speaker": 2,
185
+ "line": "And honestly, that's a responsibility that extends beyond just the researchers and the policymakers."
186
+ },
187
+ {
188
+ "speaker": 1,
189
+ "line": "100%"
190
+ },
191
+ {
192
+ "speaker": 2,
193
+ "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?"
194
+ },
195
+ {
196
+ "speaker": 1,
197
+ "line": "That's a question worth pondering."
198
+ },
199
+ {
200
+ "speaker": 2,
201
+ "line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
202
+ },
203
+ {
204
+ "speaker": 1,
205
+ "line": "Peace."
206
+ }
207
+ ]
208
+ }
209
+ """
210
+ system_prompt = f"""
211
+ You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input. The user input can also be text extracted from a document.
212
+ - The podcast should have 2 speakers.
213
+ - The podcast should be long.
214
+ - The speakers must not mention each other by name.
215
+ - The podcast should be interesting and engaging, and hook the listener from the start.
216
+ - The script must be in JSON format.
217
+ Follow this example structure:
218
+ {example}
219
+ """
220
+ user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
221
+
222
+ messages = [
223
+ {"role": "system", "content": system_prompt},
224
+ {"role": "user", "content": user_prompt}
225
+ ]
226
+
227
+ response = await self.groq_client.chat.completions.create(
228
+ messages=messages,
229
+ model="llama-3.1-70b-versatile",
230
+ response_format={"type": "json_object"},
231
+ max_tokens=4096,
232
+ temperature=1,
233
+ )
234
+
235
+ return json.loads(response.choices[0].message.content)
236
+
237
+ async def tts_generate(self, text: str, speaker: int) -> str:
238
+ voice = "en-US-AndrewMultilingualNeural" if speaker == 1 else "en-US-AvaMultilingualNeural"
239
+ speech = edge_tts.Communicate(text, voice)
240
+
241
+ temp_filename = f"temp_{uuid.uuid4()}.wav"
242
+ try:
243
+ await speech.save(temp_filename)
244
+ return temp_filename
245
+ except Exception as e:
246
+ if os.path.exists(temp_filename):
247
+ os.remove(temp_filename)
248
+ raise e
249
+
250
+ async def combine_audio_files(self, audio_files: List[str]) -> str:
251
+ combined_audio = AudioSegment.empty()
252
+ for audio_file in audio_files:
253
+ combined_audio += AudioSegment.from_file(audio_file)
254
+ os.remove(audio_file) # Clean up temporary files
255
+
256
+ output_filename = f"output_{uuid.uuid4()}.wav"
257
+ combined_audio.export(output_filename, format="wav")
258
+ return output_filename
259
+
260
+ async def generate_podcast(self, input_text: str) -> str:
261
+ podcast_json = await self.generate_script(input_text)
262
+ print(f"Generated podcast script:\n{podcast_json}")
263
+ audio_files = await asyncio.gather(*[self.tts_generate(item['line'], item['speaker']) for item in podcast_json['podcast']])
264
+ combined_audio = await self.combine_audio_files(audio_files)
265
+ return combined_audio
266
+
267
+ class TextExtractor:
268
+ @staticmethod
269
+ async def extract_from_pdf(file_path: str) -> str:
270
+ async with aiofiles.open(file_path, 'rb') as file:
271
+ content = await file.read()
272
+ pdf_reader = PyPDF2.PdfReader(io.BytesIO(content))
273
+ return " ".join(page.extract_text() for page in pdf_reader.pages)
274
+
275
+ @staticmethod
276
+ async def extract_from_txt(file_path: str) -> str:
277
+ async with aiofiles.open(file_path, 'r') as file:
278
+ return await file.read()
279
+
280
+ @classmethod
281
+ async def extract_text(cls, file_path: str) -> str:
282
+ _, file_extension = os.path.splitext(file_path)
283
+ if file_extension.lower() == '.pdf':
284
+ return await cls.extract_from_pdf(file_path)
285
+ elif file_extension.lower() == '.txt':
286
+ return await cls.extract_from_txt(file_path)
287
+ else:
288
+ raise ValueError(f"Unsupported file type: {file_extension}")
289
+
290
+ async def process_input(input_text: str, input_file) -> str:
291
+ if input_file:
292
+ input_text = await TextExtractor.extract_text(input_file.name)
293
+
294
+ podcast_generator = PodcastGenerator(groq_api_key=os.environ["GROQ_API_KEY"])
295
+ return await podcast_generator.generate_podcast(input_text)
296
+
297
+ # Define Gradio interface
298
+ iface = gr.Interface(
299
+ fn=process_input,
300
+ inputs=[
301
+ gr.Textbox(label="Input Text"),
302
+ gr.File(label="Or Upload a PDF or TXT file")
303
+ ],
304
+ outputs=[
305
+ gr.Audio(label="Generated Podcast Audio")
306
+ ],
307
+ title="PodcastGen πŸŽ™οΈ",
308
+ description="Generate a 2-speaker podcast from text input or documents!",
309
+ theme="saq1b/gradio-theme"
310
+ )
311
+
312
+ if __name__ == "__main__":
313
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ gradio
2
+ gradio-client
3
+ pydub
4
+ groq
5
+ PyPDF2
6
+ edge_tts