Jiangxz01 commited on
Commit
bd4b0d1
·
verified ·
1 Parent(s): 805d359

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +376 -87
app.py CHANGED
@@ -1,87 +1,376 @@
1
- # -*- coding: utf-8 -*-
2
- # 財政部財政資訊中心 江信宗
3
-
4
- import gradio as gr
5
- import openai
6
- import os
7
-
8
- MODEL = "Meta-Llama-3.1-405B-Instruct"
9
-
10
- def create_client(api_key=None):
11
- if api_key:
12
- openai.api_key = api_key
13
- else:
14
- openai.api_key = os.getenv("YOUR_API_TOKEN")
15
- return openai.OpenAI(api_key=openai.api_key, base_url="https://api.sambanova.ai/v1")
16
-
17
- def generate_response(input_text):
18
- system_prompt = """你的任務是將提供的輸入文字轉換為一個引人入勝、訊息豐富且專業的Podcast對話。輸入文字可能會比較混亂或結構不完整,因為它可能來自不同來源,如PDF檔案或文字檔等。不要擔心格式問題或任何不相關的訊息;你的目標是提取可以在Podcast中討論的關鍵點、識別重要定義,並突出有趣的事實。
19
-
20
- 以下是你將要處理的輸入文字:
21
- <input_text>
22
- {input_text}
23
- </input_text>
24
-
25
- 首先,仔細閱讀輸入文字,找出主要話題、關鍵點,以及任何有趣的事實或軼事。思考如何將這些訊息以一種有趣且吸引人的方式呈現出來,適合高質量的音訊Podcast。
26
-
27
- <scratchpad>
28
- 頭腦風暴一些創造性的方法來討論你在輸入文字中識別出的主要話題、關鍵點及任何有趣的事實或軼事。可以考慮使用類比、講故事技巧或假設情境來讓內容對聽眾更加貼近和有趣。
29
-
30
- 請記住,你的Podcast應當易於普通聽眾理解,所以避免使用過多的專業術語或假設聽眾對該話題已有瞭解。如有必要,請思考如何用簡單的術語簡要解釋任何複雜的概念。
31
-
32
- 利用你的想像力填補輸入文字中的任何空白,或者想出一些值得探討與發人深省的問題,以供Podcast討論。目標是創造一個訊息豐富且娛樂性強的對話,因此可以在你的方法上大膽自由發揮創意。
33
-
34
- 將你的頭腦風暴想法和Podcast對話的粗略大綱寫在這裡。確保記錄下你希望在結尾重申的主要見解和要點。
35
- </scratchpad>
36
-
37
- 現在你已經進行了頭腦風暴並建立了一個粗略的大綱,是時候撰寫實際的Podcast對話了。目標是主持人(speaker1)與嘉賓(speaker2)之間自然、對話式的交流。融入你在頭腦風暴中得出的最佳想法,並確保將任何複雜話題以易於理解的方式解釋清楚。
38
- - The podcast should have 2 speakers.
39
- - Use english names for the speakers.
40
- - The podcast should be long.
41
- - The podcast should be interesting, lively, and engaging, and hook the listener from the start.
42
- - The script must be in JSON format.
43
- Follow this example structure:
44
- ```
45
- {
46
- "speaker1": "歡迎收聽財資歐北共Podcast,我是主持人XXX,今天我們邀請到XX專家XXX,百忙之中來上我們節目",
47
- "speaker2": "大家好,我是XXX,很榮幸能來跟大家一起聊聊",
48
- "speaker1": "今天我們將探討一個非常有趣的話題……",
49
- "speaker2": "沒錯,這個話題確實讓人著迷,讓我們先從……開始說起吧……",
50
- …………
51
- "speaker1": "謝謝嘉賓的分享,歡迎訂閱來許願Podcast節目喔,我們下次再見"
52
- }
53
- ```
54
-
55
- <podcast_dialogue>
56
- 根據你在頭腦風暴階段提出的關鍵點和創造性想法,撰寫你的引人入勝、訊息豐富的Podcast對話。採用對話式的語氣,並包括任何必要的上下文或解釋,使內容對一般聽眾而言容易理解。使用虛構的主持人和嘉賓名字,以營造更吸引人和身臨其境的聆聽體驗。不要包括像[主持人]或[嘉賓]這樣的括號預留位置。設計你的輸出內容以供直接朗讀——它將直接轉換為音訊。
57
-
58
- 確保對話儘可能詳細、完整,同時保持在主題之內並維持吸引人的流暢性。目標是使用你的全部輸出容量,建立儘可能長的Podcast節目,同時以有趣的方式傳遞輸入文字中的關鍵訊息。
59
-
60
- 在對話結束時,讓主持人和嘉賓自然總結他們討論中的主要見解和要點。這應當是對話的隨機部分,以自然隨意而非明顯的總結——目的是在結束前最後一次以自然流暢的方式強化核心思想。最終以感謝詞結束。
61
- </podcast_dialogue>
62
- """
63
- client = create_client()
64
- response = client.chat.completions.create(
65
- model=MODEL,
66
- messages=[
67
- {"role": "system", "content": system_prompt},
68
- {"role": "user", "content": input_text}
69
- ],
70
- temperature=1
71
- )
72
- return response.choices[0].message.content
73
-
74
- with gr.Blocks(theme=gr.themes.Monochrome()) as iface:
75
- gr.Markdown("# 🎙️ Generated Podcast Audio. Deployed by 江信宗")
76
-
77
- input_text = gr.Textbox(label="請輸入您的文字")
78
- output_text = gr.Textbox(label="生成的結果")
79
-
80
- generate_button = gr.Button("生成")
81
- generate_button.click(fn=generate_response, inputs=input_text, outputs=output_text)
82
-
83
- if __name__ == "__main__":
84
- if "SPACE_ID" in os.environ:
85
- iface.launch()
86
- else:
87
- iface.launch(share=True, show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {
62
+ "speaker": 2,
63
+ "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?"
64
+ },
65
+ {
66
+ "speaker": 1,
67
+ "line": "That's a question worth pondering."
68
+ },
69
+ {
70
+ "speaker": 2,
71
+ "line": "It certainly is and on that note, we'll wrap up this deep dive. Thanks for listening, everyone."
72
+ },
73
+ {
74
+ "speaker": 1,
75
+ "line": "Peace."
76
+ }
77
+ ]
78
+ }
79
+ """
80
+
81
+ # 根據使用者選擇的語言設定指令
82
+ if language == "Auto Detect":
83
+ language_instruction = "- The podcast MUST be in the same language as the user input."
84
+ else:
85
+ language_instruction = f"- The podcast MUST be in {language} language"
86
+
87
+ # 設定系統提示,指導AI如何生成Podcast指令碼
88
+ system_prompt = f"""
89
+ You are a professional podcast generator. Your task is to generate a professional podcast script based on the user input.
90
+ {language_instruction}
91
+ - The podcast should have 2 speakers.
92
+ - The podcast should be long.
93
+ - Do not use names for the speakers.
94
+ - The podcast should be interesting, lively, and engaging, and hook the listener from the start.
95
+ - 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.
96
+ - The script must be in JSON format.
97
+ Follow this example structure carefully:
98
+ {example}
99
+ """
100
+
101
+ # 設定使用者提示,包含使用者輸入的內容
102
+ user_prompt = f"Please generate a podcast script based on the following user input:\n{prompt}"
103
+
104
+ # 配置 SambaNova API client
105
+ if api_key:
106
+ openai.api_key = api_key
107
+ else:
108
+ openai.api_key = os.getenv("YOUR_API_TOKEN")
109
+ client = openai.OpenAI(
110
+ api_key=openai.api_key,
111
+ base_url="https://api.sambanova.ai/v1",
112
+ )
113
+
114
+ # 嘗試生成內容
115
+ try:
116
+ response = client.chat.completions.create(
117
+ model='Meta-Llama-3.1-405B-Instruct',
118
+ messages=[
119
+ {"role": "system", "content": system_prompt},
120
+ {"role": "user", "content": user_prompt}
121
+ ],
122
+ temperature=1,
123
+ max_tokens=4096
124
+ )
125
+ generated_text = response.choices[0].message.content
126
+ except Exception as e:
127
+ # 處理可能的錯誤
128
+ if "API key not valid" in str(e):
129
+ raise gr.Error("Invalid API key. Please provide a valid SambaNova API key.")
130
+ elif "rate limit" in str(e).lower():
131
+ raise gr.Error("Rate limit exceeded for the API key. Please try again later or provide your own SambaNova API key.")
132
+ else:
133
+ raise gr.Error(f"Failed to generate podcast script: {e}")
134
+
135
+ # 列印生成的Podcast指令碼
136
+ print(f"Generated podcast script:\n{generated_text}")
137
+
138
+ # 返回解析後的JSON資料
139
+ return json.loads(generated_text)
140
+
141
+ async def tts_generate(self, text: str, speaker: int, speaker1: str, speaker2: str) -> str:
142
+ """
143
+ 非同步生成文字轉語音音訊檔案。
144
+
145
+ 引數:
146
+ text (str): 要轉換爲語音的文字內容。
147
+ speaker (int): 說話者的編號(1 或 2)。
148
+ speaker1 (str): 第一位說話者的語音設定。
149
+ speaker2 (str): 第二位說話者的語音設定。
150
+
151
+ 返回:
152
+ str: 生成的臨時音訊檔案的檔名。
153
+
154
+ 此方法使用 Edge TTS 將文字轉換爲語音,並將結果儲存爲臨時音訊檔案。
155
+ 根據指定的說話者編號選擇相應的語音設定。
156
+ """
157
+ # 根據說話者選擇語音
158
+ voice = speaker1 if speaker == 1 else speaker2
159
+ # 建立語音合成對象
160
+ speech = edge_tts.Communicate(text, voice)
161
+
162
+ # 生成臨時檔名
163
+ temp_filename = f"temp_{uuid.uuid4()}.wav"
164
+ try:
165
+ # 儲存語音檔案
166
+ await speech.save(temp_filename)
167
+ return temp_filename
168
+ except Exception as e:
169
+ # 如果出錯,刪除臨時檔案並丟擲異常
170
+ if os.path.exists(temp_filename):
171
+ os.remove(temp_filename)
172
+ raise e
173
+
174
+ async def combine_audio_files(self, audio_files: List[str]) -> str:
175
+ """
176
+ 非同步合併音訊檔案。
177
+
178
+ 引數:
179
+ audio_files (List[str]): 包含音訊檔案路徑的列表。
180
+
181
+ 返回:
182
+ str: 合併後的音訊檔案的檔名。
183
+ """
184
+ # 建立空的音訊段
185
+ combined_audio = AudioSegment.empty()
186
+ # 遍歷所有音訊檔案並合併
187
+ for audio_file in audio_files:
188
+ combined_audio += AudioSegment.from_file(audio_file)
189
+ os.remove(audio_file) # 清理臨時檔案
190
+
191
+ # 生成輸出文件名
192
+ output_filename = f"output_{uuid.uuid4()}.wav"
193
+ # 匯出合併後的音訊
194
+ combined_audio.export(output_filename, format="wav")
195
+ return output_filename
196
+
197
+ async def generate_podcast(self, input_text: str, language: str, speaker1: str, speaker2: str, api_key: str) -> str:
198
+ """
199
+ 非同步生成Podcast音訊檔案。
200
+
201
+ 引數:
202
+ input_text (str): 用於生成Podcast指令碼的輸入文字。
203
+ language (str): Podcast使用的語言。
204
+ speaker1 (str): 第一位說話者的語音設定。
205
+ speaker2 (str): 第二位說話者的語音設定。
206
+ api_key (str): 用於訪問 Gemini AI 服務的 API 金鑰。
207
+
208
+ 返回:
209
+ str: 生成的Podcast音訊檔案的檔名。
210
+
211
+ 此方法執行以下步驟:
212
+ 1. 使用 generate_script 方法生成Podcast劇本。
213
+ 2. 使用 tts_generate 方法爲每個對話行生成音訊檔案。
214
+ 3. 使用 combine_audio_files 方法將所有音訊檔案合併爲一個完整的Podcast。
215
+
216
+ 整個過程是非同步的,以提高效率。方法還會記錄並顯示每個步驟的執行時間。
217
+ """
218
+ # 生成Podcast劇本
219
+ gr.Info("Generating podcast script...")
220
+ start_time = time.time()
221
+ podcast_json = await self.generate_script(input_text, language, api_key)
222
+ end_time = time.time()
223
+ gr.Info(f"Successfully generated podcast script in {(end_time - start_time):.2f} seconds!")
224
+
225
+ # 生成Podcast音訊檔案
226
+ gr.Info("Generating podcast audio files...")
227
+ start_time = time.time()
228
+ audio_files = await asyncio.gather(*[self.tts_generate(item['line'], item['speaker'], speaker1, speaker2) for item in podcast_json['podcast']])
229
+ end_time = time.time()
230
+ gr.Info(f"Successfully generated podcast audio files in {(end_time - start_time):.2f} seconds!")
231
+
232
+ # 合併音訊檔案
233
+ combined_audio = await self.combine_audio_files(audio_files)
234
+ return combined_audio
235
+
236
+ class TextExtractor:
237
+ @staticmethod
238
+ async def extract_from_pdf(file_path: str) -> str:
239
+ # 從PDF檔案中提取文字
240
+ async with aiofiles.open(file_path, 'rb') as file:
241
+ content = await file.read()
242
+ pdf_reader = pypdf.PdfReader(io.BytesIO(content))
243
+ return "\n\n".join(page.extract_text() for page in pdf_reader.pages if page.extract_text())
244
+
245
+ @staticmethod
246
+ async def extract_from_txt(file_path: str) -> str:
247
+ # 從TXT檔案中提取文字
248
+ async with aiofiles.open(file_path, 'r') as file:
249
+ return await file.read()
250
+
251
+ @classmethod
252
+ async def extract_text(cls, file_path: str) -> str:
253
+ # 根據檔案型別選擇適當的提取方法
254
+ _, file_extension = os.path.splitext(file_path)
255
+ if file_extension.lower() == '.pdf':
256
+ return await cls.extract_from_pdf(file_path)
257
+ elif file_extension.lower() == '.txt':
258
+ return await cls.extract_from_txt(file_path)
259
+ else:
260
+ raise gr.Error(f"Unsupported file type: {file_extension}")
261
+
262
+ async def process_input(input_text: str, input_file, language: str, speaker1: str, speaker2: str, api_key: str = "") -> str:
263
+ """
264
+ 處理輸入並生成Podcast的非同步函式。
265
+
266
+ 引數:
267
+ input_text (str): 使用者輸入的文字內容。
268
+ input_file: 使用者上傳的檔案(可以是 PDF 或 TXT)。
269
+ language (str): 選擇的語言。
270
+ speaker1 (str): 第一位說話者的語音選擇。
271
+ speaker2 (str): 第二位說話者的語音選擇。
272
+ api_key (str): 用於生成 AI 的 API 金鑰,預設爲空字串。
273
+
274
+ 返回:
275
+ str: 生成的Podcast音訊檔案路徑。
276
+
277
+ 此函式協調整個Podcast生成過程,包括文字提取、指令碼生成和音訊合成。
278
+ 它處理不同的輸入型別(文字或檔案),並使用指定的語音和語言設定來建立最終的Podcast。
279
+ """
280
+ # 開始生成Podcast
281
+ gr.Info("Starting podcast generation...")
282
+ start_time = time.time()
283
+
284
+ # 定義語音名稱對映
285
+ voice_names = {
286
+ "Andrew - English (United States)": "en-US-AndrewMultilingualNeural",
287
+ "Ava - English (United States)": "en-US-AvaMultilingualNeural",
288
+ "Brian - English (United States)": "en-US-BrianMultilingualNeural",
289
+ "Emma - English (United States)": "en-US-EmmaMultilingualNeural",
290
+ "Florian - German (Germany)": "de-DE-FlorianMultilingualNeural",
291
+ "Seraphina - German (Germany)": "de-DE-SeraphinaMultilingualNeural",
292
+ "Remy - French (France)": "fr-FR-RemyMultilingualNeural",
293
+ "Vivienne - French (France)": "fr-FR-VivienneMultilingualNeural"
294
+ }
295
+
296
+ # 獲取實際的語音名稱
297
+ speaker1 = voice_names[speaker1]
298
+ speaker2 = voice_names[speaker2]
299
+
300
+ # 如果提供了輸入檔案,則從檔案中提取文字
301
+ if input_file:
302
+ input_text = await TextExtractor.extract_text(input_file.name)
303
+
304
+ # 如果沒有提供API金鑰,則使用環境變數中的金鑰
305
+ if not api_key:
306
+ api_key = os.getenv("Your_API_KEY")
307
+
308
+ # 建立PodcastGenerator實例並生成Podcast
309
+ podcast_generator = PodcastGenerator()
310
+ podcast = await podcast_generator.generate_podcast(input_text, language, speaker1, speaker2, api_key)
311
+
312
+ # 計算總耗時並顯示資訊
313
+ end_time = time.time()
314
+ gr.Info(f"Successfully generated podcast in {(end_time - start_time):.2f} seconds!")
315
+
316
+ return podcast
317
+
318
+ # 定義Gradio介面
319
+ iface = gr.Interface(
320
+ fn=process_input,
321
+ inputs=[
322
+ gr.Textbox(label="Input Text"),
323
+ gr.File(label="Or Upload a PDF or TXT file"),
324
+ gr.Dropdown(label="Language", choices=[
325
+ "Auto Detect",
326
+ "Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Azerbaijani",
327
+ "Bahasa Indonesian", "Bangla", "Basque", "Bengali", "Bosnian", "Bulgarian",
328
+ "Burmese", "Catalan", "Chinese Cantonese", "Chinese Mandarin",
329
+ "Chinese Taiwanese", "Croatian", "Czech", "Danish", "Dutch", "English",
330
+ "Estonian", "Filipino", "Finnish", "French", "Galician", "Georgian",
331
+ "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Icelandic", "Irish",
332
+ "Italian", "Japanese", "Javanese", "Kannada", "Kazakh", "Khmer", "Korean",
333
+ "Lao", "Latvian", "Lithuanian", "Macedonian", "Malay", "Malayalam",
334
+ "Maltese", "Mongolian", "Nepali", "Norwegian Bokmål", "Pashto", "Persian",
335
+ "Polish", "Portuguese", "Romanian", "Russian", "Serbian", "Sinhala",
336
+ "Slovak", "Slovene", "Somali", "Spanish", "Sundanese", "Swahili",
337
+ "Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian", "Urdu",
338
+ "Uzbek", "Vietnamese", "Welsh", "Zulu"
339
+ ],
340
+ value="Auto Detect"),
341
+ gr.Dropdown(label="Speaker 1 Voice", choices=[
342
+ "Andrew - English (United States)",
343
+ "Ava - English (United States)",
344
+ "Brian - English (United States)",
345
+ "Emma - English (United States)",
346
+ "Florian - German (Germany)",
347
+ "Seraphina - German (Germany)",
348
+ "Remy - French (France)",
349
+ "Vivienne - French (France)"
350
+ ],
351
+ value="Andrew - English (United States)"),
352
+ gr.Dropdown(label="Speaker 2 Voice", choices=[
353
+ "Andrew - English (United States)",
354
+ "Ava - English (United States)",
355
+ "Brian - English (United States)",
356
+ "Emma - English (United States)",
357
+ "Florian - German (Germany)",
358
+ "Seraphina - German (Germany)",
359
+ "Remy - French (France)",
360
+ "Vivienne - French (France)"
361
+ ],
362
+ value="Ava - English (United States)"),
363
+ gr.Textbox(label="Your Gemini API Key (Optional) - In case you are getting rate limited"),
364
+ ],
365
+ outputs=[
366
+ gr.Audio(label="Generated Podcast Audio")
367
+ ],
368
+ title="🎙️ PodcastGen 🎙️",
369
+ description="Generate a 2-speaker podcast from text input or documents!",
370
+ allow_flagging="never"
371
+ )
372
+
373
+ if __name__ == "__main__":
374
+ iface.launch()
375
+
376
+