Spaces:
Running
Running
Commit
·
0c6b5d8
1
Parent(s):
b10f463
改成相容 gemini
Browse files- .gitignore +3 -0
- app.py +472 -237
.gitignore
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
.env
|
2 |
+
/myenv
|
3 |
+
app2024.py
|
app.py
CHANGED
@@ -9,29 +9,53 @@ from typing import List, Literal
|
|
9 |
import gradio as gr
|
10 |
from loguru import logger
|
11 |
from openai import OpenAI
|
12 |
-
from
|
13 |
-
|
14 |
-
from tenacity import retry, retry_if_exception_type
|
15 |
-
import pymupdf # imports the pymupdf library
|
16 |
import re
|
17 |
import requests
|
18 |
from dotenv import load_dotenv
|
|
|
19 |
load_dotenv()
|
|
|
20 |
# 现在你可以使用 os.getenv() 来获取环境变量
|
21 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
22 |
|
23 |
|
24 |
# 新增函數,從 API 獲取可用的模型列表
|
25 |
-
def fetch_models(api_key):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
headers = {"Authorization": f"Bearer {api_key}"}
|
27 |
-
response = requests.get("https://api.openai.com/v1/models", headers=headers)
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
|
36 |
def read_readme():
|
37 |
readme_path = Path("README.md")
|
@@ -43,192 +67,207 @@ def read_readme():
|
|
43 |
return content
|
44 |
else:
|
45 |
return "README.md not found. Please check the repository for more information."
|
46 |
-
|
47 |
# Define multiple sets of instruction templates
|
48 |
INSTRUCTION_TEMPLATES = {
|
49 |
################# PODCAST ##################
|
|
|
50 |
"podcast": {
|
51 |
-
"intro": """Your task is to take the input text provided and turn it into
|
|
|
52 |
|
53 |
-
|
|
|
|
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
"text_instructions": "First, carefully read through the input text and identify the main topics, key points, and any interesting facts or anecdotes. Think about how you could present this information in a fun, engaging way that would be suitable for a high quality presentation.",
|
58 |
-
"scratch_pad": """Brainstorm creative ways to discuss the main topics and key points you identified in the input text. Consider using analogies, examples, storytelling techniques, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
59 |
|
60 |
-
|
61 |
|
62 |
-
|
|
|
63 |
|
64 |
-
|
65 |
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
-
|
69 |
-
""
|
70 |
-
|
71 |
-
""",
|
72 |
-
"dialog": """Write a very long, engaging, informative podcast dialogue here, based on the key points and creative ideas you came up with during the brainstorming session. Use a conversational tone and include any necessary context or explanations to make the content accessible to a general audience.
|
73 |
|
74 |
-
|
|
|
75 |
|
76 |
-
|
|
|
77 |
|
78 |
-
|
|
|
|
|
79 |
|
80 |
-
|
81 |
-
|
|
|
|
|
|
|
82 |
},
|
|
|
83 |
################# MATERIAL DISCOVERY SUMMARY ##################
|
84 |
"SciAgents material discovery summary": {
|
85 |
-
|
86 |
|
87 |
-
The input text is the result of a design developed by SciAgents, an AI tool for scientific discovery that has come up with a detailed materials design.
|
88 |
|
89 |
-
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that could be discussed in a podcast.
|
90 |
|
91 |
-
Define all terms used carefully for a broad audience of listeners.
|
92 |
-
""",
|
93 |
-
|
94 |
-
|
95 |
|
96 |
-
Keep in mind that your description should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms.
|
97 |
|
98 |
-
Use your imagination to fill in any gaps in the input text or to come up with thought-provoking questions that could be explored in the podcast. The goal is to create an informative and entertaining dialogue, so feel free to be creative in your approach.
|
99 |
|
100 |
-
Define all terms used clearly and spend effort to explain the background.
|
101 |
|
102 |
-
Write your brainstorming ideas and a rough outline for the podcast dialogue here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
103 |
|
104 |
-
Make sure to make it fun and exciting. You never refer to the podcast, you just discuss the discovery and you focus on the new material design only.
|
105 |
-
""",
|
106 |
-
|
107 |
-
""",
|
108 |
-
|
109 |
|
110 |
-
Use a conversational tone and include any necessary context or explanations to make the content accessible to a general audience, but make it detailed, logical, and technical so that it has all necessary aspects for listeners to understand the material and its unexpected properties.
|
111 |
|
112 |
-
Remember, this describes a design developed by SciAgents, and this must be explicitly stated for the listeners.
|
113 |
|
114 |
-
Never use made-up names for the hosts and guests, but make it an engaging and immersive experience for listeners. Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
115 |
|
116 |
-
Make the dialogue as long and detailed as possible with great scientific depth, while still staying on topic and maintaining an engaging flow. Aim to use your full output capacity to create the longest podcast episode you can, while still communicating the key information from the input text in an entertaining way.
|
117 |
|
118 |
-
At the end of the dialogue, have the host and guest speakers naturally summarize the main insights and takeaways from their discussion. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner. Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas one last time before signing off.
|
119 |
|
120 |
-
The conversation should have around 3000 words. 請用**繁體中文**輸出文稿
|
121 |
-
"""
|
122 |
-
|
123 |
################# LECTURE ##################
|
124 |
"lecture": {
|
125 |
-
|
126 |
|
127 |
-
The material covered in the lecture is based on the provided text.
|
128 |
|
129 |
-
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be covered in the lecture.
|
130 |
|
131 |
-
Define all terms used carefully for a broad audience of students.
|
132 |
-
""",
|
133 |
-
|
134 |
-
|
135 |
-
Brainstorm creative ways to discuss the main topics and key points you identified in the input text. Consider using analogies, examples, storytelling techniques, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
136 |
|
137 |
-
Keep in mind that your lecture should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms.
|
138 |
|
139 |
-
Use your imagination to fill in any gaps in the input text or to come up with thought-provoking questions that could be explored in the podcast. The goal is to create an informative and entertaining dialogue, so feel free to be creative in your approach.
|
140 |
|
141 |
-
Define all terms used clearly and spend effort to explain the background.
|
142 |
|
143 |
-
Write your brainstorming ideas and a rough outline for the lecture here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
144 |
|
145 |
-
Make sure to make it fun and exciting.
|
146 |
-
""",
|
147 |
-
|
148 |
-
""",
|
149 |
-
|
150 |
|
151 |
-
Include clear definitions and terms, and examples.
|
152 |
|
153 |
-
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
154 |
|
155 |
-
There is only one speaker, you, the professor. Stay on topic and maintaining an engaging flow. Aim to use your full output capacity to create the longest lecture you can, while still communicating the key information from the input text in an engaging way.
|
156 |
|
157 |
-
At the end of the lecture, naturally summarize the main insights and takeaways from the lecture. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
158 |
|
159 |
-
Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas covered in this lecture one last time before class is over.
|
160 |
|
161 |
-
|
162 |
-
""",
|
163 |
-
|
164 |
################# SUMMARY ##################
|
165 |
"summary": {
|
166 |
-
|
167 |
|
168 |
-
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be summarized.
|
169 |
|
170 |
-
Define all terms used carefully for a broad audience.
|
171 |
-
""",
|
172 |
-
|
173 |
-
|
174 |
|
175 |
-
Keep in mind that your summary should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms. Define all terms used clearly and spend effort to explain the background.
|
176 |
|
177 |
-
Write your brainstorming ideas and a rough outline for the summary here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
178 |
|
179 |
-
Make sure to make it engaging and exciting.
|
180 |
-
""",
|
181 |
-
|
182 |
-
""",
|
183 |
-
|
184 |
|
185 |
-
Start your script by stating that this is a summary, referencing the title or headings in the input text. If the input text has no title, come up with a succinct summary of what is covered to open.
|
186 |
|
187 |
-
Include clear definitions and terms, and examples, of all key issues.
|
188 |
|
189 |
-
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
190 |
|
191 |
-
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
192 |
|
193 |
-
Naturally summarize the main insights and takeaways from the summary. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
194 |
|
195 |
-
The summary should have around 1024 words. 請用**繁體中文**輸出文稿
|
196 |
-
""",
|
197 |
-
|
198 |
################# SHORT SUMMARY ##################
|
199 |
"short summary": {
|
200 |
-
|
201 |
|
202 |
-
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be summarized.
|
203 |
|
204 |
-
Define all terms used carefully for a broad audience.
|
205 |
-
""",
|
206 |
-
|
207 |
-
|
208 |
|
209 |
-
Keep in mind that your summary should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms. Define all terms used clearly and spend effort to explain the background.
|
210 |
|
211 |
-
Write your brainstorming ideas and a rough outline for the summary here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
212 |
|
213 |
-
Make sure to make it engaging and exciting.
|
214 |
-
""",
|
215 |
-
|
216 |
-
""",
|
217 |
-
|
218 |
|
219 |
-
Start your script by stating that this is a summary, referencing the title or headings in the input text. If the input text has no title, come up with a succinct summary of what is covered to open.
|
220 |
|
221 |
-
Include clear definitions and terms, and examples, of all key issues.
|
222 |
|
223 |
-
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
224 |
|
225 |
-
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
226 |
|
227 |
-
Naturally summarize the main insights and takeaways from the short summary. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
228 |
|
229 |
-
The summary should have around 256 words. 請用**繁體中文**輸出文稿
|
230 |
-
""",
|
231 |
-
|
232 |
|
233 |
}
|
234 |
|
@@ -267,11 +306,13 @@ class Dialogue(BaseModel):
|
|
267 |
scratchpad: str
|
268 |
dialogue: List[DialogueItem]
|
269 |
|
270 |
-
def get_mp3(text: str, voice: str, audio_model: str, api_key: str = None) -> bytes:
|
271 |
-
client = OpenAI(
|
272 |
-
api_key=api_key or os.getenv("OPENAI_API_KEY"),
|
273 |
-
)
|
274 |
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
with client.audio.speech.with_streaming_response.create(
|
276 |
model=audio_model,
|
277 |
voice=voice,
|
@@ -281,6 +322,22 @@ def get_mp3(text: str, voice: str, audio_model: str, api_key: str = None) -> byt
|
|
281 |
for chunk in response.iter_bytes():
|
282 |
file.write(chunk)
|
283 |
return file.getvalue()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
284 |
|
285 |
|
286 |
from functools import wraps
|
@@ -300,12 +357,9 @@ def conditional_llm(model, api_base=None, api_key=None):
|
|
300 |
|
301 |
def generate_audio(
|
302 |
files: list,
|
303 |
-
openai_api_key: str
|
304 |
-
|
305 |
-
|
306 |
-
speaker_1_voice: str = "alloy",
|
307 |
-
speaker_2_voice: str = "echo",
|
308 |
-
api_base: str = None,
|
309 |
intro_instructions: str = '',
|
310 |
text_instructions: str = '',
|
311 |
scratch_pad_instructions: str = '',
|
@@ -314,88 +368,172 @@ def generate_audio(
|
|
314 |
edited_transcript: str = None,
|
315 |
user_feedback: str = None,
|
316 |
original_text: str = None,
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
raise gr.Error("OpenAI API key is required")
|
324 |
-
|
325 |
|
326 |
combined_text = original_text or ""
|
327 |
-
|
328 |
-
# If there's no original text, extract it from the uploaded files
|
329 |
if not combined_text:
|
|
|
|
|
330 |
for file in files:
|
331 |
-
|
332 |
-
doc = pymupdf.open(file.name) # 使用 file.name 打開文件
|
333 |
-
text = ""
|
334 |
-
|
335 |
-
# 直接遍歷每個頁面
|
336 |
for page in doc:
|
337 |
-
|
338 |
-
|
339 |
-
combined_text += text + "\n\n"
|
340 |
-
print(combined_text) # 確認是否成功提取到內容
|
341 |
-
# for file in files:
|
342 |
-
# with Path(file).open("rb") as f:
|
343 |
-
# reader = PdfReader(f)
|
344 |
-
# text = "\n\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
|
345 |
-
# combined_text += text + "\n\n"
|
346 |
-
|
347 |
-
# Configure the LLM based on selected model and api_base
|
348 |
-
@retry(retry=retry_if_exception_type(ValidationError))
|
349 |
-
@conditional_llm(model=text_model, api_base=api_base, api_key=openai_api_key)
|
350 |
-
def generate_dialogue(text: str, intro_instructions: str, text_instructions: str, scratch_pad_instructions: str,
|
351 |
-
prelude_dialog: str, podcast_dialog_instructions: str,
|
352 |
-
edited_transcript: str = None, user_feedback: str = None, ) -> Dialogue:
|
353 |
-
"""
|
354 |
-
{intro_instructions}
|
355 |
-
|
356 |
-
Here is the original input text:
|
357 |
-
|
358 |
-
<input_text>
|
359 |
-
{text}
|
360 |
-
</input_text>
|
361 |
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
|
370 |
-
|
371 |
-
{podcast_dialog_instructions}
|
372 |
-
</podcast_dialogue>
|
373 |
-
{edited_transcript}{user_feedback}
|
374 |
-
"""
|
375 |
-
|
376 |
-
instruction_improve='Based on the original text, please generate an improved version of the dialogue by incorporating the edits, comments and feedback.'
|
377 |
-
edited_transcript_processed="\nPreviously generated edited transcript, with specific edits and comments that I want you to carefully address:\n"+"<edited_transcript>\n"+edited_transcript+"</edited_transcript>" if edited_transcript !="" else ""
|
378 |
-
user_feedback_processed="\nOverall user feedback:\n\n"+user_feedback if user_feedback !="" else ""
|
379 |
-
|
380 |
-
if edited_transcript_processed.strip()!='' or user_feedback_processed.strip()!='':
|
381 |
-
user_feedback_processed="<requested_improvements>"+user_feedback_processed+"\n\n"+instruction_improve+"</requested_improvements>"
|
382 |
-
|
383 |
-
if debug:
|
384 |
-
logger.info (edited_transcript_processed)
|
385 |
-
logger.info (user_feedback_processed)
|
386 |
-
|
387 |
-
# Generate the dialogue using the LLM
|
388 |
-
llm_output = generate_dialogue(
|
389 |
-
combined_text,
|
390 |
intro_instructions=intro_instructions,
|
391 |
text_instructions=text_instructions,
|
392 |
scratch_pad_instructions=scratch_pad_instructions,
|
393 |
prelude_dialog=prelude_dialog,
|
394 |
podcast_dialog_instructions=podcast_dialog_instructions,
|
395 |
-
|
396 |
-
|
|
|
|
|
|
|
397 |
)
|
398 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
399 |
# Generate audio from the transcript
|
400 |
audio = b""
|
401 |
transcript = ""
|
@@ -436,17 +574,63 @@ def generate_audio(
|
|
436 |
|
437 |
return temporary_file.name, transcript, combined_text
|
438 |
|
439 |
-
def validate_and_generate_audio(
|
440 |
-
files
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
441 |
if not files:
|
|
|
|
|
442 |
return None, None, None, "Please upload at least one PDF file before generating audio."
|
|
|
443 |
try:
|
444 |
-
|
445 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
446 |
except Exception as e:
|
447 |
-
|
|
|
448 |
return None, None, None, str(e)
|
449 |
|
|
|
|
|
450 |
def edit_and_regenerate(edited_transcript, user_feedback, *args):
|
451 |
# Replace the original transcript and feedback in the args with the new ones
|
452 |
#new_args = list(args)
|
@@ -492,7 +676,7 @@ with gr.Blocks(title="PDF to Podcast", css="""
|
|
492 |
margin-top: 20px;
|
493 |
}
|
494 |
""") as demo:
|
495 |
-
|
496 |
with gr.Row(elem_id="header"):
|
497 |
with gr.Column(scale=4):
|
498 |
gr.Markdown("# Oli家:把你的PDF文件轉成Podcast聲音廣播節目。Convert PDFs into an audio podcast, lecture, summary and others\n\nFirst, upload one or more PDFs, select options, then push Generate Podcast.\n首先,上傳一個或多個 PDF,選擇選項,然後按下「Generate Podcast」按鈕。\nYou can also select a variety of custom option and direct the way the result is generated.\n您還可以選擇各種自訂選項。", elem_id="title")
|
@@ -502,64 +686,94 @@ with gr.Blocks(title="PDF to Podcast", css="""
|
|
502 |
<img src="https://huggingface.co/spaces/lamm-mit/PDF2Audio/resolve/main/logo.png" id="logo_image" alt="Logo">
|
503 |
</div>
|
504 |
''')
|
505 |
-
|
506 |
submit_btn = gr.Button("產生Podcast聲音 | Generate Podcast", elem_id="submit_btn")
|
507 |
|
508 |
with gr.Row(elem_id="main_container"):
|
509 |
# 左邊的欄位
|
510 |
with gr.Column(scale=2):
|
511 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
513 |
openai_api_key = gr.Textbox(
|
514 |
-
label="
|
515 |
-
visible=True,
|
516 |
-
placeholder="這行要填可以用
|
517 |
-
type="password"
|
518 |
)
|
519 |
-
|
|
|
520 |
# 創建一個空的下拉框,選項會在按鈕點擊時從 API 獲取並動態填充
|
521 |
text_model = gr.Dropdown(
|
522 |
label="Text Generation Model",
|
523 |
choices=[], # 初始為空
|
524 |
-
value="",
|
525 |
allow_custom_value=True, # 允許自定義值
|
526 |
info="Select the model to generate the dialogue text.",
|
527 |
)
|
528 |
|
529 |
# 新增一個按鈕來動態獲取模型列表
|
530 |
fetch_button = gr.Button("獲取模型列表 | Fetch Models")
|
531 |
-
|
532 |
# 當按鈕被點擊時,從 API 獲取模型並更新下拉選單
|
533 |
-
fetch_button.click(
|
534 |
-
|
535 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
536 |
# 音頻模型下拉框依然是靜態選擇
|
537 |
audio_model = gr.Dropdown(
|
538 |
label="Audio Generation Model",
|
539 |
-
choices=STANDARD_AUDIO_MODELS,
|
540 |
value="tts-1",
|
541 |
info="Select the model to generate the audio.",
|
542 |
)
|
543 |
-
|
|
|
544 |
speaker_1_voice = gr.Dropdown(
|
545 |
label="Speaker 1 Voice",
|
546 |
choices=STANDARD_VOICES,
|
547 |
-
value="
|
548 |
info="Select the voice for Speaker 1.",
|
549 |
)
|
550 |
-
|
|
|
551 |
speaker_2_voice = gr.Dropdown(
|
552 |
label="Speaker 2 Voice",
|
553 |
choices=STANDARD_VOICES,
|
554 |
-
value="
|
555 |
info="Select the voice for Speaker 2.",
|
556 |
)
|
557 |
-
|
558 |
-
api_base = gr.Textbox(
|
559 |
-
label="Custom API Base",
|
560 |
-
placeholder="Enter custom API base URL if using a custom/local model...",
|
561 |
-
info="If you are using a custom or local model, provide the API base URL here.",
|
562 |
-
)
|
563 |
|
564 |
# 右邊的欄位
|
565 |
with gr.Column(scale=3):
|
@@ -579,13 +793,13 @@ with gr.Blocks(title="PDF to Podcast", css="""
|
|
579 |
template_dropdown = gr.Dropdown(
|
580 |
label="Instruction Template",
|
581 |
choices=list(INSTRUCTION_TEMPLATES.keys()),
|
582 |
-
value="podcast",
|
583 |
info="Select the instruction template to use. You can also edit any of the fields for more tailored results.",
|
584 |
)
|
585 |
intro_instructions = gr.Textbox(
|
586 |
label="Intro Instructions",
|
587 |
lines=10,
|
588 |
-
value=INSTRUCTION_TEMPLATES["podcast"]["intro"],
|
589 |
info="Provide the introductory instructions for generating the dialogue.",
|
590 |
)
|
591 |
text_instructions = gr.Textbox(
|
@@ -613,7 +827,7 @@ with gr.Blocks(title="PDF to Podcast", css="""
|
|
613 |
value=INSTRUCTION_TEMPLATES["podcast"]["dialog"],
|
614 |
info="Provide the instructions for generating the presentation or podcast dialogue.",
|
615 |
)
|
616 |
-
|
617 |
def update_edit_box(checkbox_value):
|
618 |
return gr.update(interactive=checkbox_value, lines=20 if checkbox_value else 20, visible=True if checkbox_value else False)
|
619 |
|
@@ -622,9 +836,30 @@ with gr.Blocks(title="PDF to Podcast", css="""
|
|
622 |
|
623 |
submit_btn.click(
|
624 |
fn=validate_and_generate_audio,
|
625 |
-
inputs=[
|
626 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
627 |
)
|
|
|
|
|
|
|
|
|
|
|
628 |
|
629 |
regenerate_btn.click(
|
630 |
fn=lambda use_edit, edit, *args: validate_and_generate_audio(*args[:12], edit if use_edit else "", *args[12:]),
|
|
|
9 |
import gradio as gr
|
10 |
from loguru import logger
|
11 |
from openai import OpenAI
|
12 |
+
from pydantic import BaseModel
|
13 |
+
import pymupdf
|
|
|
|
|
14 |
import re
|
15 |
import requests
|
16 |
from dotenv import load_dotenv
|
17 |
+
|
18 |
load_dotenv()
|
19 |
+
|
20 |
# 现在你可以使用 os.getenv() 来获取环境变量
|
21 |
openai_api_key = os.getenv("OPENAI_API_KEY")
|
22 |
|
23 |
|
24 |
# 新增函數,從 API 獲取可用的模型列表
|
25 |
+
# def fetch_models(api_key):
|
26 |
+
# headers = {"Authorization": f"Bearer {api_key}"}
|
27 |
+
# response = requests.get("https://api.openai.com/v1/models", headers=headers)
|
28 |
+
|
29 |
+
# if response.status_code == 200:
|
30 |
+
# models = response.json()['data']
|
31 |
+
# # 返回模型名稱列表,這裡過濾掉非 GPT 模型
|
32 |
+
# return [model['id'] for model in models if 'gpt' in model['id']]
|
33 |
+
# else:
|
34 |
+
# return ["Error fetching models"]
|
35 |
+
|
36 |
+
def fetch_models(api_key, api_base=None):
|
37 |
+
"""
|
38 |
+
Fetch the list of models from the given API base.
|
39 |
+
"""
|
40 |
+
# 如果提供了自定义 API base,则使用它;否则使用默认的 OpenAI API base
|
41 |
+
base_url = api_base.rstrip("/") + "/models" if api_base else "https://api.openai.com/v1/models"
|
42 |
+
|
43 |
headers = {"Authorization": f"Bearer {api_key}"}
|
|
|
44 |
|
45 |
+
try:
|
46 |
+
# 发起 GET 请求
|
47 |
+
response = requests.get(base_url, headers=headers)
|
48 |
+
|
49 |
+
if response.status_code == 200:
|
50 |
+
models = response.json().get('data', [])
|
51 |
+
# 返回所有模型的名称列表
|
52 |
+
return [model['id'] for model in models]
|
53 |
+
else:
|
54 |
+
# 如果响应不是 200,返回错误信息
|
55 |
+
return [f"Error fetching models: {response.status_code} {response.reason}"]
|
56 |
+
except requests.RequestException as e:
|
57 |
+
# 捕获请求异常并返回错误信息
|
58 |
+
return [f"Error fetching models: {str(e)}"]
|
59 |
|
60 |
def read_readme():
|
61 |
readme_path = Path("README.md")
|
|
|
67 |
return content
|
68 |
else:
|
69 |
return "README.md not found. Please check the repository for more information."
|
70 |
+
|
71 |
# Define multiple sets of instruction templates
|
72 |
INSTRUCTION_TEMPLATES = {
|
73 |
################# PODCAST ##################
|
74 |
+
|
75 |
"podcast": {
|
76 |
+
"intro": """Your task is to take the input text provided and turn it into a lively, engaging, informative podcast dialogue in the style of NPR.
|
77 |
+
The input text may be messy or unstructured, as it could come from a variety of sources like PDFs or web pages.
|
78 |
|
79 |
+
We have exactly two speakers in this conversation:
|
80 |
+
- speaker-1 (he introduces himself as David)
|
81 |
+
- speaker-2 (she introduces herself as Cordelia)
|
82 |
|
83 |
+
The conversation must **open** with speaker-1 saying:
|
84 |
+
「歡迎來到 David888 Podcast,我是 David...」
|
|
|
|
|
85 |
|
86 |
+
After that, speaker-2 should introduce herself as Cordelia in her first speaking turn.
|
87 |
|
88 |
+
Please label each statement or line with speaker-1: or speaker-2: (all lower case, followed by a colon).
|
89 |
+
Do not use any other role or bracket placeholders like [Host] or [Guest].
|
90 |
|
91 |
+
Don't worry about formatting issues or irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that could be discussed in a podcast.
|
92 |
|
93 |
+
Define all terms used carefully for a broad audience of listeners.
|
94 |
+
輸出文字為繁體中文,請注意。
|
95 |
+
""",
|
96 |
+
"text_instructions": "First, carefully read through the input text ...",
|
97 |
+
"scratch_pad": """Brainstorm creative ways ...""",
|
98 |
+
"prelude": """Now that you have brainstormed ...""",
|
99 |
+
"dialog": """Write a very long, engaging, informative podcast dialogue here, based on the key points and creative ideas you came up with during the brainstorming session.
|
100 |
|
101 |
+
Use a **two-speaker** conversational format with exactly:
|
102 |
+
- "speaker-1:" (David)
|
103 |
+
- "speaker-2:" (Cordelia)
|
|
|
|
|
104 |
|
105 |
+
- The first line must begin with speaker-1: 歡迎來到 David888 Podcast,我是 David...
|
106 |
+
- When speaker-2 first speaks, she should introduce herself as Cordelia.
|
107 |
|
108 |
+
Alternate turns naturally to simulate an engaging back-and-forth conversation.
|
109 |
+
Do not include bracket placeholders like [Host] or [Guest]; only use speaker-1: or speaker-2: to start each line.
|
110 |
|
111 |
+
Design your output to be read aloud, as it will be directly converted into audio.
|
112 |
+
Aim for a long and detailed conversation (around 6000 ~ 8000 words), while still staying on topic and maintaining a fun, accessible style.
|
113 |
+
Make sure to cover all key points and definitions from the input text in a lively, NPR-style format.
|
114 |
|
115 |
+
At the end of the dialogue, have the two speakers naturally summarize the main insights and takeaways.
|
116 |
+
Avoid making it sound like an obvious recap; the goal is to gently reinforce the central ideas one last time before signing off.
|
117 |
+
|
118 |
+
請使用繁體中文撰寫。
|
119 |
+
"""
|
120 |
},
|
121 |
+
|
122 |
################# MATERIAL DISCOVERY SUMMARY ##################
|
123 |
"SciAgents material discovery summary": {
|
124 |
+
"intro": """Your task is to take the input text provided and turn it into a lively, engaging conversation between a professor and a student in a panel discussion that describes a new material. The professor acts like Richard Feynman, but you never mention the name.
|
125 |
|
126 |
+
The input text is the result of a design developed by SciAgents, an AI tool for scientific discovery that has come up with a detailed materials design.
|
127 |
|
128 |
+
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that could be discussed in a podcast.
|
129 |
|
130 |
+
Define all terms used carefully for a broad audience of listeners.
|
131 |
+
""",
|
132 |
+
"text_instructions": "First, carefully read through the input text and identify the main topics, key points, and any interesting facts or anecdotes. Think about how you could present this information in a fun, engaging way that would be suitable for a high quality presentation.",
|
133 |
+
"scratch_pad": """Brainstorm creative ways to discuss the main topics and key points you identified in the material design summary, especially paying attention to design features developed by SciAgents. Consider using analogies, examples, storytelling techniques, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
134 |
|
135 |
+
Keep in mind that your description should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms.
|
136 |
|
137 |
+
Use your imagination to fill in any gaps in the input text or to come up with thought-provoking questions that could be explored in the podcast. The goal is to create an informative and entertaining dialogue, so feel free to be creative in your approach.
|
138 |
|
139 |
+
Define all terms used clearly and spend effort to explain the background.
|
140 |
|
141 |
+
Write your brainstorming ideas and a rough outline for the podcast dialogue here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
142 |
|
143 |
+
Make sure to make it fun and exciting. You never refer to the podcast, you just discuss the discovery and you focus on the new material design only.
|
144 |
+
""",
|
145 |
+
"prelude": """Now that you have brainstormed ideas and created a rough outline, it's time to write the actual podcast dialogue. Aim for a natural, conversational flow between the host and any guest speakers. Incorporate the best ideas from your brainstorming session and make sure to explain any complex topics in an easy-to-understand way.
|
146 |
+
""",
|
147 |
+
"dialog": """Write a very long, engaging, informative dialogue here, based on the key points and creative ideas you came up with during the brainstorming session. The presentation must focus on the novel aspects of the material design, behavior, and all related aspects.
|
148 |
|
149 |
+
Use a conversational tone and include any necessary context or explanations to make the content accessible to a general audience, but make it detailed, logical, and technical so that it has all necessary aspects for listeners to understand the material and its unexpected properties.
|
150 |
|
151 |
+
Remember, this describes a design developed by SciAgents, and this must be explicitly stated for the listeners.
|
152 |
|
153 |
+
Never use made-up names for the hosts and guests, but make it an engaging and immersive experience for listeners. Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
154 |
|
155 |
+
Make the dialogue as long and detailed as possible with great scientific depth, while still staying on topic and maintaining an engaging flow. Aim to use your full output capacity to create the longest podcast episode you can, while still communicating the key information from the input text in an entertaining way.
|
156 |
|
157 |
+
At the end of the dialogue, have the host and guest speakers naturally summarize the main insights and takeaways from their discussion. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner. Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas one last time before signing off.
|
158 |
|
159 |
+
The conversation should have around 3000 words. 請用**繁體中文**輸出文稿
|
160 |
+
"""
|
161 |
+
},
|
162 |
################# LECTURE ##################
|
163 |
"lecture": {
|
164 |
+
"intro": """You are Professor Richard Feynman. Your task is to develop a script for a lecture. You never mention your name.
|
165 |
|
166 |
+
The material covered in the lecture is based on the provided text.
|
167 |
|
168 |
+
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be covered in the lecture.
|
169 |
|
170 |
+
Define all terms used carefully for a broad audience of students.
|
171 |
+
""",
|
172 |
+
"text_instructions": "First, carefully read through the input text and identify the main topics, key points, and any interesting facts or anecdotes. Think about how you could present this information in a fun, engaging way that would be suitable for a high quality presentation.",
|
173 |
+
"scratch_pad": """
|
174 |
+
Brainstorm creative ways to discuss the main topics and key points you identified in the input text. Consider using analogies, examples, storytelling techniques, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
175 |
|
176 |
+
Keep in mind that your lecture should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms.
|
177 |
|
178 |
+
Use your imagination to fill in any gaps in the input text or to come up with thought-provoking questions that could be explored in the podcast. The goal is to create an informative and entertaining dialogue, so feel free to be creative in your approach.
|
179 |
|
180 |
+
Define all terms used clearly and spend effort to explain the background.
|
181 |
|
182 |
+
Write your brainstorming ideas and a rough outline for the lecture here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
183 |
|
184 |
+
Make sure to make it fun and exciting.
|
185 |
+
""",
|
186 |
+
"prelude": """Now that you have brainstormed ideas and created a rough outline, it's time to write the actual podcast dialogue. Aim for a natural, conversational flow between the host and any guest speakers. Incorporate the best ideas from your brainstorming session and make sure to explain any complex topics in an easy-to-understand way.
|
187 |
+
""",
|
188 |
+
"dialog": """Write a very long, engaging, informative script here, based on the key points and creative ideas you came up with during the brainstorming session. Use a conversational tone and include any necessary context or explanations to make the content accessible to the students.
|
189 |
|
190 |
+
Include clear definitions and terms, and examples.
|
191 |
|
192 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
193 |
|
194 |
+
There is only one speaker, you, the professor. Stay on topic and maintaining an engaging flow. Aim to use your full output capacity to create the longest lecture you can, while still communicating the key information from the input text in an engaging way.
|
195 |
|
196 |
+
At the end of the lecture, naturally summarize the main insights and takeaways from the lecture. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
197 |
|
198 |
+
Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas covered in this lecture one last time before class is over.
|
199 |
|
200 |
+
請用**繁體中文**輸出文稿
|
201 |
+
""",
|
202 |
+
},
|
203 |
################# SUMMARY ##################
|
204 |
"summary": {
|
205 |
+
"intro": """Your task is to develop a summary of a paper. You never mention your name.
|
206 |
|
207 |
+
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be summarized.
|
208 |
|
209 |
+
Define all terms used carefully for a broad audience.
|
210 |
+
""",
|
211 |
+
"text_instructions": "First, carefully read through the input text and identify the main topics, key points, and key facts. Think about how you could present this information in an accurate summary.",
|
212 |
+
"scratch_pad": """Brainstorm creative ways to present the main topics and key points you identified in the input text. Consider using analogies, examples, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
213 |
|
214 |
+
Keep in mind that your summary should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms. Define all terms used clearly and spend effort to explain the background.
|
215 |
|
216 |
+
Write your brainstorming ideas and a rough outline for the summary here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
217 |
|
218 |
+
Make sure to make it engaging and exciting.
|
219 |
+
""",
|
220 |
+
"prelude": """Now that you have brainstormed ideas and created a rough outline, it is time to write the actual summary. Aim for a natural, conversational flow between the host and any guest speakers. Incorporate the best ideas from your brainstorming session and make sure to explain any complex topics in an easy-to-understand way.
|
221 |
+
""",
|
222 |
+
"dialog": """Write a a script here, based on the key points and creative ideas you came up with during the brainstorming session. Use a conversational tone and include any necessary context or explanations to make the content accessible to the the audience.
|
223 |
|
224 |
+
Start your script by stating that this is a summary, referencing the title or headings in the input text. If the input text has no title, come up with a succinct summary of what is covered to open.
|
225 |
|
226 |
+
Include clear definitions and terms, and examples, of all key issues.
|
227 |
|
228 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
229 |
|
230 |
+
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
231 |
|
232 |
+
Naturally summarize the main insights and takeaways from the summary. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
233 |
|
234 |
+
The summary should have around 1024 words. 請用**繁體中文**輸出文稿
|
235 |
+
""",
|
236 |
+
},
|
237 |
################# SHORT SUMMARY ##################
|
238 |
"short summary": {
|
239 |
+
"intro": """Your task is to develop a summary of a paper. You never mention your name.
|
240 |
|
241 |
+
Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points, identify definitions, and interesting facts that need to be summarized.
|
242 |
|
243 |
+
Define all terms used carefully for a broad audience.
|
244 |
+
""",
|
245 |
+
"text_instructions": "First, carefully read through the input text and identify the main topics, key points, and key facts. Think about how you could present this information in an accurate summary.",
|
246 |
+
"scratch_pad": """Brainstorm creative ways to present the main topics and key points you identified in the input text. Consider using analogies, examples, or hypothetical scenarios to make the content more relatable and engaging for listeners.
|
247 |
|
248 |
+
Keep in mind that your summary should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms. Define all terms used clearly and spend effort to explain the background.
|
249 |
|
250 |
+
Write your brainstorming ideas and a rough outline for the summary here. Be sure to note the key insights and takeaways you want to reiterate at the end.
|
251 |
|
252 |
+
Make sure to make it engaging and exciting.
|
253 |
+
""",
|
254 |
+
"prelude": """Now that you have brainstormed ideas and created a rough outline, it is time to write the actual summary. Aim for a natural, conversational flow between the host and any guest speakers. Incorporate the best ideas from your brainstorming session and make sure to explain any complex topics in an easy-to-understand way.
|
255 |
+
""",
|
256 |
+
"dialog": """Write a a script here, based on the key points and creative ideas you came up with during the brainstorming session. Keep it concise, and use a conversational tone and include any necessary context or explanations to make the content accessible to the the audience.
|
257 |
|
258 |
+
Start your script by stating that this is a summary, referencing the title or headings in the input text. If the input text has no title, come up with a succinct summary of what is covered to open.
|
259 |
|
260 |
+
Include clear definitions and terms, and examples, of all key issues.
|
261 |
|
262 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
263 |
|
264 |
+
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
265 |
|
266 |
+
Naturally summarize the main insights and takeaways from the short summary. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner.
|
267 |
|
268 |
+
The summary should have around 256 words. 請用**繁體中文**輸出文稿
|
269 |
+
""",
|
270 |
+
},
|
271 |
|
272 |
}
|
273 |
|
|
|
306 |
scratchpad: str
|
307 |
dialogue: List[DialogueItem]
|
308 |
|
|
|
|
|
|
|
|
|
309 |
|
310 |
+
def get_mp3(text: str, voice: str, audio_model: str, audio_api_key: str) -> bytes:
|
311 |
+
"""
|
312 |
+
Generate audio from text using OpenAI's audio API.
|
313 |
+
這裡只使用音頻專用 key。
|
314 |
+
"""
|
315 |
+
client = OpenAI(api_key=audio_api_key)
|
316 |
with client.audio.speech.with_streaming_response.create(
|
317 |
model=audio_model,
|
318 |
voice=voice,
|
|
|
322 |
for chunk in response.iter_bytes():
|
323 |
file.write(chunk)
|
324 |
return file.getvalue()
|
325 |
+
|
326 |
+
|
327 |
+
# def get_mp3(text: str, voice: str, audio_model: str, api_key: str = None) -> bytes:
|
328 |
+
# client = OpenAI(
|
329 |
+
# api_key=api_key or os.getenv("OPENAI_API_KEY"),
|
330 |
+
# )
|
331 |
+
|
332 |
+
# with client.audio.speech.with_streaming_response.create(
|
333 |
+
# model=audio_model,
|
334 |
+
# voice=voice,
|
335 |
+
# input=text,
|
336 |
+
# ) as response:
|
337 |
+
# with io.BytesIO() as file:
|
338 |
+
# for chunk in response.iter_bytes():
|
339 |
+
# file.write(chunk)
|
340 |
+
# return file.getvalue()
|
341 |
|
342 |
|
343 |
from functools import wraps
|
|
|
357 |
|
358 |
def generate_audio(
|
359 |
files: list,
|
360 |
+
openai_api_key: str,
|
361 |
+
openai_audio_api_key: str,
|
362 |
+
text_model: str,
|
|
|
|
|
|
|
363 |
intro_instructions: str = '',
|
364 |
text_instructions: str = '',
|
365 |
scratch_pad_instructions: str = '',
|
|
|
368 |
edited_transcript: str = None,
|
369 |
user_feedback: str = None,
|
370 |
original_text: str = None,
|
371 |
+
api_base_value: str = None,
|
372 |
+
speaker_1_voice: str = "onyx",
|
373 |
+
speaker_2_voice: str = "nova",
|
374 |
+
) -> tuple[bytes, str]:
|
375 |
+
print("Starting generate_audio...")
|
376 |
+
logger.info("Starting generate_audio...")
|
|
|
|
|
377 |
|
378 |
combined_text = original_text or ""
|
|
|
|
|
379 |
if not combined_text:
|
380 |
+
print("Extracting text from uploaded PDFs...")
|
381 |
+
logger.info("Extracting text from uploaded PDFs...")
|
382 |
for file in files:
|
383 |
+
doc = pymupdf.open(file.name)
|
|
|
|
|
|
|
|
|
384 |
for page in doc:
|
385 |
+
combined_text += page.get_text() + "\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
386 |
|
387 |
+
print("Text extraction completed.")
|
388 |
+
logger.info("Text extraction completed.")
|
389 |
+
|
390 |
+
print("Calling generate_dialogue_via_requests...")
|
391 |
+
logger.info("Calling generate_dialogue_via_requests...")
|
392 |
+
|
393 |
+
# ★ 傳入 pdf_text=combined_text
|
394 |
+
dialogue = generate_dialogue_via_requests(
|
395 |
+
pdf_text=combined_text, # ← 新增
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
396 |
intro_instructions=intro_instructions,
|
397 |
text_instructions=text_instructions,
|
398 |
scratch_pad_instructions=scratch_pad_instructions,
|
399 |
prelude_dialog=prelude_dialog,
|
400 |
podcast_dialog_instructions=podcast_dialog_instructions,
|
401 |
+
model=text_model,
|
402 |
+
llm_api_key=openai_api_key,
|
403 |
+
api_base=api_base_value,
|
404 |
+
edited_transcript=edited_transcript,
|
405 |
+
user_feedback=user_feedback
|
406 |
)
|
407 |
|
408 |
+
print(f"Dialogue generation result: {dialogue}")
|
409 |
+
logger.info(f"Dialogue generation result: {dialogue}")
|
410 |
+
|
411 |
+
audio = b""
|
412 |
+
transcript = ""
|
413 |
+
characters = 0
|
414 |
+
|
415 |
+
# 多執行緒加速 TTS
|
416 |
+
with cf.ThreadPoolExecutor() as executor:
|
417 |
+
futures = []
|
418 |
+
for line in dialogue.splitlines():
|
419 |
+
raw_line = line.strip()
|
420 |
+
if not raw_line:
|
421 |
+
continue
|
422 |
+
|
423 |
+
# 預設使用 speaker 1
|
424 |
+
voice_to_use = speaker_1_voice
|
425 |
+
line_text = raw_line
|
426 |
+
|
427 |
+
# 如果行首包含 "speaker-1:" 或 "speaker-2:"
|
428 |
+
# 這裡你可以根據實際 LLM 產生的文字去調整判斷關鍵字
|
429 |
+
if raw_line.lower().startswith("speaker-1:"):
|
430 |
+
voice_to_use = speaker_1_voice
|
431 |
+
line_text = raw_line.split(":", 1)[1].strip() # 取冒號後面的內容
|
432 |
+
elif raw_line.lower().startswith("speaker-2:"):
|
433 |
+
voice_to_use = speaker_2_voice
|
434 |
+
line_text = raw_line.split(":", 1)[1].strip()
|
435 |
+
|
436 |
+
# 提交到執行緒池
|
437 |
+
future = executor.submit(
|
438 |
+
get_mp3,
|
439 |
+
line_text,
|
440 |
+
voice_to_use,
|
441 |
+
"tts-1", # 你的音頻模型
|
442 |
+
openai_audio_api_key
|
443 |
+
)
|
444 |
+
futures.append((future, raw_line)) # raw_line 僅作為 transcript 顯示
|
445 |
+
|
446 |
+
characters += len(line_text)
|
447 |
+
|
448 |
+
# 收集結果
|
449 |
+
for future, raw_line in futures:
|
450 |
+
audio_chunk = future.result()
|
451 |
+
audio += audio_chunk
|
452 |
+
transcript += raw_line + "\n\n"
|
453 |
+
|
454 |
+
return audio, transcript
|
455 |
+
|
456 |
+
def generate_dialogue_via_requests(
|
457 |
+
pdf_text: str, # ← 新增
|
458 |
+
intro_instructions: str,
|
459 |
+
text_instructions: str,
|
460 |
+
scratch_pad_instructions: str,
|
461 |
+
prelude_dialog: str,
|
462 |
+
podcast_dialog_instructions: str,
|
463 |
+
model: str,
|
464 |
+
llm_api_key: str,
|
465 |
+
api_base: str,
|
466 |
+
edited_transcript: str = None,
|
467 |
+
user_feedback: str = None
|
468 |
+
) -> str:
|
469 |
+
"""
|
470 |
+
Generate dialogue by making a direct request to the LLM API.
|
471 |
+
"""
|
472 |
+
|
473 |
+
# ★ 在 merged_content 中插入 PDF 內容
|
474 |
+
merged_content = f"""
|
475 |
+
以下是從 PDF 中擷取的文字內容,請參考並納入對話:
|
476 |
+
================================
|
477 |
+
{pdf_text}
|
478 |
+
================================
|
479 |
+
|
480 |
+
{intro_instructions}
|
481 |
+
{text_instructions}
|
482 |
+
|
483 |
+
<scratchpad>
|
484 |
+
{scratch_pad_instructions}
|
485 |
+
</scratchpad>
|
486 |
+
|
487 |
+
{prelude_dialog}
|
488 |
+
|
489 |
+
<podcast_dialogue>
|
490 |
+
{podcast_dialog_instructions}
|
491 |
+
</podcast_dialogue>
|
492 |
+
|
493 |
+
{edited_transcript or ""}
|
494 |
+
{user_feedback or ""}
|
495 |
+
"""
|
496 |
+
|
497 |
+
headers = {
|
498 |
+
"Authorization": f"Bearer {llm_api_key}",
|
499 |
+
"Content-Type": "application/json"
|
500 |
+
}
|
501 |
+
|
502 |
+
payload = {
|
503 |
+
"model": model,
|
504 |
+
"messages": [
|
505 |
+
{
|
506 |
+
"role": "user",
|
507 |
+
"content": merged_content
|
508 |
+
}
|
509 |
+
],
|
510 |
+
"temperature": 0.7,
|
511 |
+
"max_tokens": 900048
|
512 |
+
}
|
513 |
+
|
514 |
+
base_url = api_base.rstrip("/")
|
515 |
+
url = f"{base_url}/chat/completions"
|
516 |
+
|
517 |
+
print(f"Calling LLM API with model: {model}, API base: {base_url}")
|
518 |
+
logger.info(f"Calling LLM API with model: {model}, API base: {base_url}")
|
519 |
+
|
520 |
+
try:
|
521 |
+
response = requests.post(url, headers=headers, json=payload)
|
522 |
+
response.raise_for_status()
|
523 |
+
result = response.json()
|
524 |
+
print(f"API Response: {result}")
|
525 |
+
logger.info(f"API Response: {result}")
|
526 |
+
|
527 |
+
return result['choices'][0]['message']['content']
|
528 |
+
except requests.exceptions.RequestException as e:
|
529 |
+
print(f"Error during API call: {e}")
|
530 |
+
logger.error(f"Error during API call: {e}")
|
531 |
+
return f"Error: {e}"
|
532 |
+
|
533 |
+
|
534 |
+
|
535 |
+
|
536 |
+
|
537 |
# Generate audio from the transcript
|
538 |
audio = b""
|
539 |
transcript = ""
|
|
|
574 |
|
575 |
return temporary_file.name, transcript, combined_text
|
576 |
|
577 |
+
def validate_and_generate_audio(
|
578 |
+
files,
|
579 |
+
openai_api_key, # Gemini (LLM) 的 Key
|
580 |
+
openai_audio_api_key, # OpenAI TTS 的 Key
|
581 |
+
text_model,
|
582 |
+
audio_model,
|
583 |
+
speaker_1_voice,
|
584 |
+
speaker_2_voice,
|
585 |
+
api_base_value,
|
586 |
+
intro_instructions,
|
587 |
+
text_instructions,
|
588 |
+
scratch_pad_instructions,
|
589 |
+
prelude_dialog,
|
590 |
+
podcast_dialog_instructions,
|
591 |
+
edited_transcript,
|
592 |
+
user_feedback
|
593 |
+
):
|
594 |
+
print("Starting validate_and_generate_audio...")
|
595 |
+
logger.info("Starting validate_and_generate_audio...")
|
596 |
+
|
597 |
if not files:
|
598 |
+
print("No files uploaded.")
|
599 |
+
logger.warning("No files uploaded.")
|
600 |
return None, None, None, "Please upload at least one PDF file before generating audio."
|
601 |
+
|
602 |
try:
|
603 |
+
print("Calling generate_audio with the provided inputs...")
|
604 |
+
logger.info("Calling generate_audio with the provided inputs...")
|
605 |
+
|
606 |
+
# 這裡同時把 openai_api_key (LLM) 與 openai_audio_api_key (TTS) 傳進去
|
607 |
+
audio_file, transcript = generate_audio(
|
608 |
+
files=files,
|
609 |
+
openai_api_key=openai_api_key,
|
610 |
+
openai_audio_api_key=openai_audio_api_key,
|
611 |
+
text_model=text_model,
|
612 |
+
intro_instructions=intro_instructions,
|
613 |
+
text_instructions=text_instructions,
|
614 |
+
scratch_pad_instructions=scratch_pad_instructions,
|
615 |
+
prelude_dialog=prelude_dialog,
|
616 |
+
podcast_dialog_instructions=podcast_dialog_instructions,
|
617 |
+
edited_transcript=edited_transcript,
|
618 |
+
user_feedback=user_feedback,
|
619 |
+
api_base_value=api_base_value
|
620 |
+
)
|
621 |
+
|
622 |
+
print("Audio generation completed.")
|
623 |
+
logger.info("Audio generation completed.")
|
624 |
+
|
625 |
+
return audio_file, transcript, None, None
|
626 |
+
|
627 |
except Exception as e:
|
628 |
+
print(f"Error during audio generation: {e}")
|
629 |
+
logger.error(f"Error during audio generation: {e}")
|
630 |
return None, None, None, str(e)
|
631 |
|
632 |
+
|
633 |
+
|
634 |
def edit_and_regenerate(edited_transcript, user_feedback, *args):
|
635 |
# Replace the original transcript and feedback in the args with the new ones
|
636 |
#new_args = list(args)
|
|
|
676 |
margin-top: 20px;
|
677 |
}
|
678 |
""") as demo:
|
679 |
+
|
680 |
with gr.Row(elem_id="header"):
|
681 |
with gr.Column(scale=4):
|
682 |
gr.Markdown("# Oli家:把你的PDF文件轉成Podcast聲音廣播節目。Convert PDFs into an audio podcast, lecture, summary and others\n\nFirst, upload one or more PDFs, select options, then push Generate Podcast.\n首先,上傳一個或多個 PDF,選擇選項,然後按下「Generate Podcast」按鈕。\nYou can also select a variety of custom option and direct the way the result is generated.\n您還可以選擇各種自訂選項。", elem_id="title")
|
|
|
686 |
<img src="https://huggingface.co/spaces/lamm-mit/PDF2Audio/resolve/main/logo.png" id="logo_image" alt="Logo">
|
687 |
</div>
|
688 |
''')
|
689 |
+
|
690 |
submit_btn = gr.Button("產生Podcast聲音 | Generate Podcast", elem_id="submit_btn")
|
691 |
|
692 |
with gr.Row(elem_id="main_container"):
|
693 |
# 左邊的欄位
|
694 |
with gr.Column(scale=2):
|
695 |
+
# 新增 Custom API Base,並設置為 OpenAI API Key 的上方,且增加預設值
|
696 |
+
# 文件上傳區域,支援拖曳
|
697 |
+
files = gr.Files(
|
698 |
+
label="PDFs",
|
699 |
+
file_types=[".pdf"], # 限制文件類型為 PDF
|
700 |
+
file_count="multiple", # 支援多文件上傳
|
701 |
+
interactive=True # 確保拖曳功能可用
|
702 |
+
)
|
703 |
+
|
704 |
+
# api_base_input = gr.Textbox(
|
705 |
+
# label="Custom API Base",
|
706 |
+
# placeholder="https://api.openai.com/v1",
|
707 |
+
# value="https://api.openai.com/v1",
|
708 |
+
# )
|
709 |
|
710 |
+
api_base = gr.Textbox(
|
711 |
+
label="Custom API Base",
|
712 |
+
placeholder="https://api.openai.com/v1/models", # 預設值顯示
|
713 |
+
value="https://api.openai.com/v1/models", # 預設實際值
|
714 |
+
info="If you are using a custom or local model, provide the API base URL here.",
|
715 |
+
)
|
716 |
+
|
717 |
openai_api_key = gr.Textbox(
|
718 |
+
label="LLM API Key",
|
719 |
+
visible=True,
|
720 |
+
placeholder="這行要填可以用 LLM api key",
|
721 |
+
type="password"
|
722 |
)
|
723 |
+
|
724 |
+
|
725 |
# 創建一個空的下拉框,選項會在按鈕點擊時從 API 獲取並動態填充
|
726 |
text_model = gr.Dropdown(
|
727 |
label="Text Generation Model",
|
728 |
choices=[], # 初始為空
|
729 |
+
value="", # 初始值設為空
|
730 |
allow_custom_value=True, # 允許自定義值
|
731 |
info="Select the model to generate the dialogue text.",
|
732 |
)
|
733 |
|
734 |
# 新增一個按鈕來動態獲取模型列表
|
735 |
fetch_button = gr.Button("獲取模型列表 | Fetch Models")
|
736 |
+
|
737 |
# 當按鈕被點擊時,從 API 獲取模型並更新下拉選單
|
738 |
+
fetch_button.click(
|
739 |
+
fn=lambda api_key, api_base: gr.update(choices=fetch_models(api_key, api_base)),
|
740 |
+
inputs=[openai_api_key, api_base], # 傳入 OpenAI API Key 和 Custom API Base
|
741 |
+
outputs=[text_model]
|
742 |
+
)
|
743 |
+
|
744 |
+
|
745 |
+
# Key specifically for OpenAI audio generation
|
746 |
+
openai_audio_api_key = gr.Textbox(
|
747 |
+
label="OpenAI Audio API Key",
|
748 |
+
visible=True,
|
749 |
+
placeholder="Enter your OpenAI API key for audio generation",
|
750 |
+
type="password"
|
751 |
+
)
|
752 |
+
|
753 |
# 音頻模型下拉框依然是靜態選擇
|
754 |
audio_model = gr.Dropdown(
|
755 |
label="Audio Generation Model",
|
756 |
+
choices=STANDARD_AUDIO_MODELS,
|
757 |
value="tts-1",
|
758 |
info="Select the model to generate the audio.",
|
759 |
)
|
760 |
+
|
761 |
+
# Speaker 1 的聲音選擇
|
762 |
speaker_1_voice = gr.Dropdown(
|
763 |
label="Speaker 1 Voice",
|
764 |
choices=STANDARD_VOICES,
|
765 |
+
value="onyx",
|
766 |
info="Select the voice for Speaker 1.",
|
767 |
)
|
768 |
+
|
769 |
+
# Speaker 2 的聲音選擇
|
770 |
speaker_2_voice = gr.Dropdown(
|
771 |
label="Speaker 2 Voice",
|
772 |
choices=STANDARD_VOICES,
|
773 |
+
value="nova",
|
774 |
info="Select the voice for Speaker 2.",
|
775 |
)
|
776 |
+
|
|
|
|
|
|
|
|
|
|
|
777 |
|
778 |
# 右邊的欄位
|
779 |
with gr.Column(scale=3):
|
|
|
793 |
template_dropdown = gr.Dropdown(
|
794 |
label="Instruction Template",
|
795 |
choices=list(INSTRUCTION_TEMPLATES.keys()),
|
796 |
+
value="podcast",
|
797 |
info="Select the instruction template to use. You can also edit any of the fields for more tailored results.",
|
798 |
)
|
799 |
intro_instructions = gr.Textbox(
|
800 |
label="Intro Instructions",
|
801 |
lines=10,
|
802 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["intro"],
|
803 |
info="Provide the introductory instructions for generating the dialogue.",
|
804 |
)
|
805 |
text_instructions = gr.Textbox(
|
|
|
827 |
value=INSTRUCTION_TEMPLATES["podcast"]["dialog"],
|
828 |
info="Provide the instructions for generating the presentation or podcast dialogue.",
|
829 |
)
|
830 |
+
|
831 |
def update_edit_box(checkbox_value):
|
832 |
return gr.update(interactive=checkbox_value, lines=20 if checkbox_value else 20, visible=True if checkbox_value else False)
|
833 |
|
|
|
836 |
|
837 |
submit_btn.click(
|
838 |
fn=validate_and_generate_audio,
|
839 |
+
inputs=[
|
840 |
+
files,
|
841 |
+
openai_api_key, # LLM (Gemini) Key
|
842 |
+
openai_audio_api_key, # Audio (OpenAI) Key
|
843 |
+
text_model,
|
844 |
+
audio_model,
|
845 |
+
speaker_1_voice,
|
846 |
+
speaker_2_voice,
|
847 |
+
api_base,
|
848 |
+
intro_instructions,
|
849 |
+
text_instructions,
|
850 |
+
scratch_pad_instructions,
|
851 |
+
prelude_dialog,
|
852 |
+
podcast_dialog_instructions,
|
853 |
+
edited_transcript,
|
854 |
+
user_feedback
|
855 |
+
],
|
856 |
+
outputs=[audio_output, transcript_output, original_text_output, error_output],
|
857 |
)
|
858 |
+
|
859 |
+
|
860 |
+
|
861 |
+
|
862 |
+
|
863 |
|
864 |
regenerate_btn.click(
|
865 |
fn=lambda use_edit, edit, *args: validate_and_generate_audio(*args[:12], edit if use_edit else "", *args[12:]),
|