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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from pydub import AudioSegment
|
3 |
+
import google.generativeai as genai
|
4 |
+
from google.generativeai.types import HarmCategory, HarmBlockThreshold
|
5 |
+
import json
|
6 |
+
import uuid
|
7 |
+
import io
|
8 |
+
import edge_tts
|
9 |
+
import asyncio
|
10 |
+
import aiofiles
|
11 |
+
import pypdf
|
12 |
+
import os
|
13 |
+
import time
|
14 |
+
from typing import List, Dict, Tuple
|
15 |
+
import openai
|
16 |
+
|
17 |
+
class PodcastGenerator:
|
18 |
+
def __init__(self):
|
19 |
+
pass
|
20 |
+
|
21 |
+
async def generate_script(self, prompt: str, language: str, api_key: str) -> Dict:
|
22 |
+
"""
|
23 |
+
非同步生成基於給定提示和語言的Podcast劇本。
|
24 |
+
|
25 |
+
引數:
|
26 |
+
prompt (str): 用於生成Podcast劇本的使用者輸入文字。
|
27 |
+
language (str): Podcast指劇本所需的語言。
|
28 |
+
api_key (str): 用於訪問 SambaNova API 服務的 API 金鑰。
|
29 |
+
|
30 |
+
返回:
|
31 |
+
Dict: 包含以 JSON 格式生成Podcast劇本的字典。
|
32 |
+
|
33 |
+
異常:
|
34 |
+
gr.Error: 如果 API 金鑰或速率限制出現問題。
|
35 |
+
|
36 |
+
此方法使用 SambaNova API 根據使用者的輸入生成Podcast劇本。
|
37 |
+
它處理語言選擇,使用適當的配置設定 AI 模型,並處理生成的響應。
|
38 |
+
"""
|
39 |
+
# 定義一個示例JSON結構,用於指導AI生成類似格式的Podcast劇本
|
40 |
+
example = """
|
41 |
+
{
|
42 |
+
"topic": "AGI",
|
43 |
+
"podcast": [
|
44 |
+
{
|
45 |
+
"speaker": 2,
|
46 |
+
"line": "So, AGI, huh? Seems like everyone's talking about it these days."
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"speaker": 1,
|
50 |
+
"line": "Yeah, it's definitely having a moment, isn't it?"
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"speaker": 2,
|
54 |
+
"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?"
|
55 |
+
},
|
56 |
+
{
|
57 |
+
"speaker": 1,
|
58 |
+
"line": "Honestly, it's the sheer scale of what AGI could do. We're talking about potentially reshaping well everything."
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"speaker": 2,
|
62 |
+
"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."
|
63 |
+
},
|
64 |
+
{
|
65 |
+
"speaker": 1,
|
66 |
+
"line": "It's easy to get lost in the noise, for sure."
|
67 |
+
},
|
68 |
+
{
|
69 |
+
"speaker": 2,
|
70 |
+
"line": "Exactly. So how about we try to cut through some of that, shall we?"
|
71 |
+
},
|
72 |
+
{
|
73 |
+
"speaker": 1,
|
74 |
+
"line": "Sounds like a plan."
|
75 |
+
},
|
76 |
+
{
|
77 |
+
"speaker": 2,
|
78 |
+
"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?"
|
79 |
+
},
|
80 |
+
{
|
81 |
+
"speaker": 1,
|
82 |
+
"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."
|
83 |
+
},
|
84 |
+
{
|
85 |
+
"speaker": 2,
|
86 |
+
"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."
|
87 |
+
},
|
88 |
+
{
|
89 |
+
"speaker": 1,
|
90 |
+
"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."
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"speaker": 2,
|
94 |
+
"line": "Okay, I see. So, AGI is about bridging that gap, creating something that can move between those different realms of knowledge seamlessly."
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"speaker": 1,
|
98 |
+
"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."
|
99 |
+
},
|
100 |
+
{
|
101 |
+
"speaker": 2,
|
102 |
+
"line": "I bet. I mean, think about how much we still don't even understand about our own brains."
|
103 |
+
},
|
104 |
+
{
|
105 |
+
"speaker": 1,
|
106 |
+
"line": "That's exactly it. We're essentially trying to reverse-engineer something we don't fully comprehend."
|
107 |
+
},
|
108 |
+
{
|
109 |
+
"speaker": 2,
|
110 |
+
"line": "And how are researchers even approaching that? What are some of the big ideas out there?"
|
111 |
+
},
|
112 |
+
{
|
113 |
+
"speaker": 1,
|
114 |
+
"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."
|
115 |
+
},
|
116 |
+
{
|
117 |
+
"speaker": 2,
|
118 |
+
"line": "Wow, so like actually replicating the physical architecture of the brain. That's wild."
|
119 |
+
},
|
120 |
+
{
|
121 |
+
"speaker": 1,
|
122 |
+
"line": "It's pretty mind-blowing stuff and then you've got folks working on something called whole brain emulation."
|
123 |
+
},
|
124 |
+
{
|
125 |
+
"speaker": 2,
|
126 |
+
"line": "Okay, and what's that all about?"
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"speaker": 1,
|
130 |
+
"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."
|
131 |
+
},
|
132 |
+
{
|
133 |
+
"speaker": 2,
|
134 |
+
"line": "Hold on, a digital copy of an entire brain, that sounds like something straight out of science fiction."
|
135 |
+
},
|
136 |
+
{
|
137 |
+
"speaker": 1,
|
138 |
+
"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."
|
139 |
+
},
|
140 |
+
{
|
141 |
+
"speaker": 2,
|
142 |
+
"line": "That makes sense but it's still exciting to think about the possibilities, even if they're a ways off."
|
143 |
+
},
|
144 |
+
{
|
145 |
+
"speaker": 1,
|
146 |
+
"line": "Absolutely and those possibilities are what really get people fired up about AGI, right? Yeah."
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"speaker": 2,
|
150 |
+
"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."
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"speaker": 1,
|
154 |
+
"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."
|
155 |
+
},
|
156 |
+
{
|
157 |
+
"speaker": 2,
|
158 |
+
"line": "It's like giving scientists this incredibly powerful new tool to tackle some of the biggest challenges we face."
|
159 |
+
},
|
160 |
+
{
|
161 |
+
"speaker": 1,
|
162 |
+
"line": "Exactly, it could be a total game changer."
|
163 |
+
},
|
164 |
+
{
|
165 |
+
"speaker": 2,
|
166 |
+
"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?"
|
167 |
+
},
|
168 |
+
{
|
169 |
+
"speaker": 1,
|
170 |
+
"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."
|
171 |
+
},
|
172 |
+
{
|
173 |
+
"speaker": 2,
|
174 |
+
"line": "So we're not just talking about robots taking over factories but potentially things like, what, legal work, analysis, even creative fields?"
|
175 |
+
},
|
176 |
+
{
|
177 |
+
"speaker": 1,
|
178 |
+
"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."
|
179 |
+
},
|
180 |
+
{
|
181 |
+
"speaker": 2,
|
182 |
+
"line": "Right, because it's not just about the technology itself, but how we choose to integrate it into society."
|
183 |
+
},
|
184 |
+
{
|
185 |
+
"speaker": 1,
|
186 |
+
"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."
|
187 |
+
},
|
188 |
+
{
|
189 |
+
"speaker": 2,
|
190 |
+
"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."
|
191 |
+
},
|
192 |
+
{
|
193 |
+
"speaker": 1,
|
194 |
+
"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."
|
195 |
+
},
|
196 |
+
{
|
197 |
+
"speaker": 2,
|
198 |
+
"line": "It's like you said earlier, it's about shaping the future of intelligence."
|
199 |
+
},
|
200 |
+
{
|
201 |
+
"speaker": 1,
|
202 |
+
"line": "I like that. It really is."
|
203 |
+
},
|
204 |
+
{
|
205 |
+
"speaker": 2,
|
206 |
+
"line": "And honestly, that's a responsibility that extends beyond just the researchers and the policymakers."
|
207 |
+
},
|
208 |
+
{
|
209 |
+
"speaker": 1,
|
210 |
+
"line": "100%"
|
211 |
+
},
|
212 |
+
{
|
213 |
+
"speaker": 2,
|
214 |
+
"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?"
|
215 |
+
},
|
216 |
+
{
|
217 |
+
"speaker": 1,
|
218 |
+
"line": "That's a question worth pondering."
|
219 |
+
},
|
220 |
+
{
|
221 |
+
"speaker": 2,
|
222 |
+
"line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
|
223 |
+
},
|
224 |
+
{
|
225 |
+
"speaker": 1,
|
226 |
+
"line": "Peace."
|
227 |
+
}
|
228 |
+
]
|
229 |
+
}
|
230 |
+
"""
|
231 |
+
|
232 |
+
# 根據使用者選擇的語言設定指令
|
233 |
+
if language == "Auto Detect":
|
234 |
+
language_instruction = "- The podcast MUST be in the same language as the user input."
|
235 |
+
else:
|
236 |
+
language_instruction = f"- The podcast MUST be in {language} language"
|
237 |
+
|
238 |
+
# 設定系統提示,指導AI如何生成Podcast指令碼
|
239 |
+
system_prompt = f"""
|
240 |
+
You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input.
|
241 |
+
{language_instruction}
|
242 |
+
- The podcast should have 2 speakers.
|
243 |
+
- The podcast should be long.
|
244 |
+
- Do not use names for the speakers.
|
245 |
+
- The podcast should be interesting, lively, and engaging, and hook the listener from the start.
|
246 |
+
- 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.
|
247 |
+
- The script must be in JSON format.
|
248 |
+
Follow this example structure carefully:
|
249 |
+
{example}
|
250 |
+
"""
|
251 |
+
|
252 |
+
# 設定使用者提示,包含使用者輸入的內容
|
253 |
+
user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
|
254 |
+
|
255 |
+
# 配置 SambaNova API client
|
256 |
+
if api_key:
|
257 |
+
openai.api_key = api_key
|
258 |
+
else:
|
259 |
+
openai.api_key = os.getenv("YOUR_API_TOKEN")
|
260 |
+
client = openai.OpenAI(
|
261 |
+
api_key=openai.api_key,
|
262 |
+
base_url="https://api.sambanova.ai/v1",
|
263 |
+
)
|
264 |
+
|
265 |
+
# 嘗試生成內容
|
266 |
+
try:
|
267 |
+
response = client.chat.completions.create(
|
268 |
+
model='Meta-Llama-3.1-405B-Instruct',
|
269 |
+
messages=[
|
270 |
+
{"role": "system", "content": system_prompt},
|
271 |
+
{"role": "user", "content": user_prompt}
|
272 |
+
],
|
273 |
+
temperature=0.7,
|
274 |
+
max_tokens=8192
|
275 |
+
)
|
276 |
+
generated_text = response.choices[0].message.content
|
277 |
+
except Exception as e:
|
278 |
+
# 處理可能的錯誤
|
279 |
+
if "API key not valid" in str(e):
|
280 |
+
raise gr.Error("Invalid API key. Please provide a valid SambaNova API key.")
|
281 |
+
elif "rate limit" in str(e).lower():
|
282 |
+
raise gr.Error("Rate limit exceeded for the API key. Please try again later or provide your own SambaNova API key.")
|
283 |
+
else:
|
284 |
+
raise gr.Error(f"Failed to generate podcast script: {e}")
|
285 |
+
|
286 |
+
# 列印生成的Podcast指令碼
|
287 |
+
print(f"Generated podcast script:\n{generated_text}")
|
288 |
+
|
289 |
+
# 返回解析後的JSON資料
|
290 |
+
return json.loads(generated_text)
|
291 |
+
|
292 |
+
async def tts_generate(self, text: str, speaker: int, speaker1: str, speaker2: str) -> str:
|
293 |
+
"""
|
294 |
+
非同步生成文字轉語音音訊檔案。
|
295 |
+
|
296 |
+
引數:
|
297 |
+
text (str): 要轉換爲語音的文字內容。
|
298 |
+
speaker (int): 說話者的編號(1 或 2)。
|
299 |
+
speaker1 (str): 第一位說話者的語音設定。
|
300 |
+
speaker2 (str): 第二位說話者的語音設定。
|
301 |
+
|
302 |
+
返回:
|
303 |
+
str: 生成的臨時音訊檔案的檔名。
|
304 |
+
|
305 |
+
此方法使用 Edge TTS 將文字轉換爲語音,並將結果儲存爲臨時音訊檔案。
|
306 |
+
根據指定的說話者編號選擇相應的語音設定。
|
307 |
+
"""
|
308 |
+
# 根據說話者選擇語音
|
309 |
+
voice = speaker1 if speaker == 1 else speaker2
|
310 |
+
# 建立語音合成對象
|
311 |
+
speech = edge_tts.Communicate(text, voice)
|
312 |
+
|
313 |
+
# 生成臨時檔名
|
314 |
+
temp_filename = f"temp_{uuid.uuid4()}.wav"
|
315 |
+
try:
|
316 |
+
# 儲存語音檔案
|
317 |
+
await speech.save(temp_filename)
|
318 |
+
return temp_filename
|
319 |
+
except Exception as e:
|
320 |
+
# 如果出錯,刪除臨時檔案並丟擲異常
|
321 |
+
if os.path.exists(temp_filename):
|
322 |
+
os.remove(temp_filename)
|
323 |
+
raise e
|
324 |
+
|
325 |
+
async def combine_audio_files(self, audio_files: List[str]) -> str:
|
326 |
+
"""
|
327 |
+
非同步合併音訊檔案。
|
328 |
+
|
329 |
+
引數:
|
330 |
+
audio_files (List[str]): 包含音訊檔案路徑的列表。
|
331 |
+
|
332 |
+
返回:
|
333 |
+
str: 合併後的音訊檔案的檔名。
|
334 |
+
"""
|
335 |
+
# 建立空的音訊段
|
336 |
+
combined_audio = AudioSegment.empty()
|
337 |
+
# 遍歷所有音訊檔案並合併
|
338 |
+
for audio_file in audio_files:
|
339 |
+
combined_audio += AudioSegment.from_file(audio_file)
|
340 |
+
os.remove(audio_file) # 清理臨時檔案
|
341 |
+
|
342 |
+
# 生成輸出文件名
|
343 |
+
output_filename = f"output_{uuid.uuid4()}.wav"
|
344 |
+
# 匯出合併後的音訊
|
345 |
+
combined_audio.export(output_filename, format="wav")
|
346 |
+
return output_filename
|
347 |
+
|
348 |
+
async def generate_podcast(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str) -> str:
|
349 |
+
"""
|
350 |
+
非同步生成Podcast音訊檔案。
|
351 |
+
|
352 |
+
引數:
|
353 |
+
input_text (str): 用於生成Podcast指令碼的輸入文字。
|
354 |
+
language (str): Podcast使用的語言。
|
355 |
+
speaker1 (str): 第一位說話者的語音設定。
|
356 |
+
speaker2 (str): 第二位說話者的語音設定。
|
357 |
+
api_key (str): 用於訪問 Gemini AI 服務的 API 金鑰。
|
358 |
+
|
359 |
+
返回:
|
360 |
+
str: 生成的Podcast音訊檔案的檔名。
|
361 |
+
|
362 |
+
此方法執行以下步驟:
|
363 |
+
1. 使用 generate_script 方法生成Podcast劇本。
|
364 |
+
2. 使用 tts_generate 方法爲每個對話行生成音訊檔案。
|
365 |
+
3. 使用 combine_audio_files 方法將所有音訊檔案合併爲一個完整的Podcast。
|
366 |
+
|
367 |
+
整個過程是非同步的,以提高效率。方法還會記錄並顯示每個步驟的執行時間。
|
368 |
+
"""
|
369 |
+
# 生成Podcast劇本
|
370 |
+
gr.Info("Generating podcast script...")
|
371 |
+
start_time = time.time()
|
372 |
+
podcast_json = await self.generate_script(input_text, language, api_key)
|
373 |
+
end_time = time.time()
|
374 |
+
gr.Info(f"Successfully generated podcast script in {(end_time - start_time):.2f} seconds!")
|
375 |
+
|
376 |
+
# 生成Podcast音訊檔案
|
377 |
+
gr.Info("Generating podcast audio files...")
|
378 |
+
start_time = time.time()
|
379 |
+
audio_files = await asyncio.gather(*[self.tts_generate(item['line'], item['speaker'], speaker1, speaker2) for item in podcast_json['podcast']])
|
380 |
+
end_time = time.time()
|
381 |
+
gr.Info(f"Successfully generated podcast audio files in {(end_time - start_time):.2f} seconds!")
|
382 |
+
|
383 |
+
# 合併音訊檔案
|
384 |
+
combined_audio = await self.combine_audio_files(audio_files)
|
385 |
+
return combined_audio
|
386 |
+
|
387 |
+
class TextExtractor:
|
388 |
+
@staticmethod
|
389 |
+
async def extract_from_pdf(file_path: str) -> str:
|
390 |
+
# 從PDF檔案中提取文字
|
391 |
+
async with aiofiles.open(file_path, 'rb') as file:
|
392 |
+
content = await file.read()
|
393 |
+
pdf_reader = pypdf.PdfReader(io.BytesIO(content))
|
394 |
+
return "\n\n".join(page.extract_text() for page in pdf_reader.pages if page.extract_text())
|
395 |
+
|
396 |
+
@staticmethod
|
397 |
+
async def extract_from_txt(file_path: str) -> str:
|
398 |
+
# 從TXT檔案中提取文字
|
399 |
+
async with aiofiles.open(file_path, 'r') as file:
|
400 |
+
return await file.read()
|
401 |
+
|
402 |
+
@classmethod
|
403 |
+
async def extract_text(cls, file_path: str) -> str:
|
404 |
+
# 根據檔案型別選擇適當的提取方法
|
405 |
+
_, file_extension = os.path.splitext(file_path)
|
406 |
+
if file_extension.lower() == '.pdf':
|
407 |
+
return await cls.extract_from_pdf(file_path)
|
408 |
+
elif file_extension.lower() == '.txt':
|
409 |
+
return await cls.extract_from_txt(file_path)
|
410 |
+
else:
|
411 |
+
raise gr.Error(f"Unsupported file type: {file_extension}")
|
412 |
+
|
413 |
+
async def process_input(input_text: str, input_file, language: str, speaker1: str, speaker2: str, api_key: str = "") -> str:
|
414 |
+
"""
|
415 |
+
處理輸入並生成Podcast的非同步函式。
|
416 |
+
|
417 |
+
引數:
|
418 |
+
input_text (str): 使用者輸入的文字內容。
|
419 |
+
input_file: 使用者上傳的檔案(可以是 PDF 或 TXT)。
|
420 |
+
language (str): 選擇的語言。
|
421 |
+
speaker1 (str): 第一位說話者的語音選擇。
|
422 |
+
speaker2 (str): 第二位說話者的語音選擇。
|
423 |
+
api_key (str): 用於生成 AI 的 API 金鑰,預設爲空字串。
|
424 |
+
|
425 |
+
返回:
|
426 |
+
str: 生成的Podcast音訊檔案路徑。
|
427 |
+
|
428 |
+
此函式協調整個Podcast生成過程,包括文字提取、指令碼生成和音訊合成。
|
429 |
+
它處理不同的輸入型別(文字或檔案),並使用指定的語音和語言設定來建立最終的Podcast。
|
430 |
+
"""
|
431 |
+
# 開始生成Podcast
|
432 |
+
gr.Info("Starting podcast generation...")
|
433 |
+
start_time = time.time()
|
434 |
+
|
435 |
+
# 定義語音名稱對映
|
436 |
+
voice_names = {
|
437 |
+
"Andrew - English (United States)": "en-US-AndrewMultilingualNeural",
|
438 |
+
"Ava - English (United States)": "en-US-AvaMultilingualNeural",
|
439 |
+
"Brian - English (United States)": "en-US-BrianMultilingualNeural",
|
440 |
+
"Emma - English (United States)": "en-US-EmmaMultilingualNeural",
|
441 |
+
"Florian - German (Germany)": "de-DE-FlorianMultilingualNeural",
|
442 |
+
"Seraphina - German (Germany)": "de-DE-SeraphinaMultilingualNeural",
|
443 |
+
"Remy - French (France)": "fr-FR-RemyMultilingualNeural",
|
444 |
+
"Vivienne - French (France)": "fr-FR-VivienneMultilingualNeural"
|
445 |
+
}
|
446 |
+
|
447 |
+
# 獲取實際的語音名稱
|
448 |
+
speaker1 = voice_names[speaker1]
|
449 |
+
speaker2 = voice_names[speaker2]
|
450 |
+
|
451 |
+
# 如果提供了輸入檔案,則從檔案中提取文字
|
452 |
+
if input_file:
|
453 |
+
input_text = await TextExtractor.extract_text(input_file.name)
|
454 |
+
|
455 |
+
# 如果沒有提供API金鑰,則使用環境變數中的金鑰
|
456 |
+
if not api_key:
|
457 |
+
api_key = os.getenv("Your_API_KEY")
|
458 |
+
|
459 |
+
# 建立PodcastGenerator實例並生成Podcast
|
460 |
+
podcast_generator = PodcastGenerator()
|
461 |
+
podcast = await podcast_generator.generate_podcast(input_text, language, speaker1, speaker2, api_key)
|
462 |
+
|
463 |
+
# 計算總耗時並顯示資訊
|
464 |
+
end_time = time.time()
|
465 |
+
gr.Info(f"Successfully generated podcast in {(end_time - start_time):.2f} seconds!")
|
466 |
+
|
467 |
+
return podcast
|
468 |
+
|
469 |
+
# 定義Gradio介面
|
470 |
+
iface = gr.Interface(
|
471 |
+
fn=process_input,
|
472 |
+
inputs=[
|
473 |
+
gr.Textbox(label="Input Text"),
|
474 |
+
gr.File(label="Or Upload a PDF or TXT file"),
|
475 |
+
gr.Dropdown(label="Language", choices=[
|
476 |
+
"Auto Detect",
|
477 |
+
"Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
|
478 |
+
"Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
|
479 |
+
"Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
|
480 |
+
"Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
|
481 |
+
"Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
|
482 |
+
"German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
|
483 |
+
"Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
|
484 |
+
"Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
|
485 |
+
"Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
|
486 |
+
"Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
|
487 |
+
"Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
|
488 |
+
"Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
|
489 |
+
"Uzbek", "Vietnamese", "Welsh", "Zulu"
|
490 |
+
],
|
491 |
+
value="Auto Detect"),
|
492 |
+
gr.Dropdown(label="Speaker 1 Voice", choices=[
|
493 |
+
"Andrew - English (United States)",
|
494 |
+
"Ava - English (United States)",
|
495 |
+
"Brian - English (United States)",
|
496 |
+
"Emma - English (United States)",
|
497 |
+
"Florian - German (Germany)",
|
498 |
+
"Seraphina - German (Germany)",
|
499 |
+
"Remy - French (France)",
|
500 |
+
"Vivienne - French (France)"
|
501 |
+
],
|
502 |
+
value="Andrew - English (United States)"),
|
503 |
+
gr.Dropdown(label="Speaker 2 Voice", choices=[
|
504 |
+
"Andrew - English (United States)",
|
505 |
+
"Ava - English (United States)",
|
506 |
+
"Brian - English (United States)",
|
507 |
+
"Emma - English (United States)",
|
508 |
+
"Florian - German (Germany)",
|
509 |
+
"Seraphina - German (Germany)",
|
510 |
+
"Remy - French (France)",
|
511 |
+
"Vivienne - French (France)"
|
512 |
+
],
|
513 |
+
value="Ava - English (United States)"),
|
514 |
+
gr.Textbox(label="Your Gemini API Key (Optional) - In case you are getting rate limited"),
|
515 |
+
],
|
516 |
+
outputs=[
|
517 |
+
gr.Audio(label="Generated Podcast Audio")
|
518 |
+
],
|
519 |
+
title="🎙️ PodcastGen 🎙️",
|
520 |
+
description="Generate a 2-speaker podcast from text input or documents!",
|
521 |
+
allow_flagging="never"
|
522 |
+
)
|
523 |
+
|
524 |
+
if __name__ == "__main__":
|
525 |
+
iface.launch()
|
526 |
+
|
527 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
gradio-client
|
3 |
+
openai
|
4 |
+
pydub
|
5 |
+
google-generativeai
|
6 |
+
pypdf
|
7 |
+
edge_tts
|