tbdavid2019 commited on
Commit
9734a09
·
1 Parent(s): 0c6b5d8

新增 epub txt等file支持

Browse files
Files changed (3) hide show
  1. app.py +46 -12
  2. app20250108.py +872 -0
  3. requirements.txt +3 -1
app.py CHANGED
@@ -376,23 +376,52 @@ def 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,
@@ -408,6 +437,10 @@ def generate_audio(
408
  print(f"Dialogue generation result: {dialogue}")
409
  logger.info(f"Dialogue generation result: {dialogue}")
410
 
 
 
 
 
411
  audio = b""
412
  transcript = ""
413
  characters = 0
@@ -694,11 +727,12 @@ with gr.Blocks(title="PDF to Podcast", css="""
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(
 
376
  logger.info("Starting generate_audio...")
377
 
378
  combined_text = original_text or ""
379
+
380
  if not combined_text:
381
+ print("Extracting text from uploaded files...")
382
+ logger.info("Extracting text from uploaded files...")
383
+
384
  for file in files:
385
+ filename = file.name.lower() # 小寫方便判斷副檔名
386
+
387
+ if filename.endswith(".pdf"):
388
+ # 使用 pymupdf 讀取 PDF
389
+ doc = pymupdf.open(file.name)
390
+ for page in doc:
391
+ combined_text += page.get_text() + "\n\n"
392
+
393
+ elif filename.endswith(".txt"):
394
+ # 直接讀取純文字
395
+ with open(file.name, "r", encoding="utf-8", errors="ignore") as f:
396
+ combined_text += f.read() + "\n\n"
397
+
398
+ elif filename.endswith(".epub"):
399
+ # 使用第三方庫來解析 EPUB
400
+ # 例如 ebooklib (pip install ebooklib)
401
+ # 實際可參考 ebooklib 文件,看你要怎麼取出文字
402
+ from ebooklib import epub
403
+ from bs4 import BeautifulSoup
404
+
405
+ book = epub.read_epub(file.name)
406
+ for item in book.get_items():
407
+ if item.get_type() == 9: # ebooklib.ITEM_DOCUMENT
408
+ # item.get_body_content() 會給出 HTML
409
+ soup = BeautifulSoup(item.get_body_content(), 'html.parser')
410
+ # 取出HTML文字
411
+ combined_text += soup.get_text() + "\n\n"
412
+ else:
413
+ # 如果遇到未知或不支援的副檔名,可以選擇跳過或給警告
414
+ print(f"Skipping unsupported file format: {filename}")
415
+ logger.warning(f"Skipping unsupported file format: {filename}")
416
 
417
  print("Text extraction completed.")
418
  logger.info("Text extraction completed.")
419
 
420
+ # 呼叫你的 generate_dialogue_via_requests,把 combined_text 傳進去
421
  print("Calling generate_dialogue_via_requests...")
422
  logger.info("Calling generate_dialogue_via_requests...")
 
 
423
  dialogue = generate_dialogue_via_requests(
424
+ pdf_text=combined_text,
425
  intro_instructions=intro_instructions,
426
  text_instructions=text_instructions,
427
  scratch_pad_instructions=scratch_pad_instructions,
 
437
  print(f"Dialogue generation result: {dialogue}")
438
  logger.info(f"Dialogue generation result: {dialogue}")
439
 
440
+ # 接著照你原本的程式碼,用多執行緒把 dialogue 拆行、對應 speaker-1 / speaker-2,
441
+ # 呼叫 get_mp3() 轉語音,最後返回 audio, transcript。
442
+
443
+
444
  audio = b""
445
  transcript = ""
446
  characters = 0
 
727
  with gr.Column(scale=2):
728
  # 新增 Custom API Base,並設置為 OpenAI API Key 的上方,且增加預設值
729
  # 文件上傳區域,支援拖曳
730
+
731
  files = gr.Files(
732
+ label="PDF / TXT / EPUB",
733
+ file_types=[".pdf", ".txt", ".epub"],
734
+ file_count="multiple",
735
+ interactive=True
736
  )
737
 
738
  # api_base_input = gr.Textbox(
app20250108.py ADDED
@@ -0,0 +1,872 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures as cf
2
+ import glob
3
+ import io
4
+ import os
5
+ import time
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import List, Literal
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")
62
+ if readme_path.exists():
63
+ with open(readme_path, "r") as file:
64
+ content = file.read()
65
+ # Use regex to remove metadata enclosed in -- ... --
66
+ content = re.sub(r'--.*?--', '', content, flags=re.DOTALL)
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
+
274
+ # Function to update instruction fields based on template selection
275
+ def update_instructions(template):
276
+ return (
277
+ INSTRUCTION_TEMPLATES[template]["intro"],
278
+ INSTRUCTION_TEMPLATES[template]["text_instructions"],
279
+ INSTRUCTION_TEMPLATES[template]["scratch_pad"],
280
+ INSTRUCTION_TEMPLATES[template]["prelude"],
281
+ INSTRUCTION_TEMPLATES[template]["dialog"]
282
+ )
283
+
284
+
285
+ # Define standard values
286
+
287
+ STANDARD_AUDIO_MODELS = [
288
+ "tts-1",
289
+ "tts-1-hd",
290
+ ]
291
+
292
+ STANDARD_VOICES = [
293
+ "alloy",
294
+ "echo",
295
+ "fable",
296
+ "onyx",
297
+ "nova",
298
+ "shimmer",
299
+ ]
300
+
301
+ class DialogueItem(BaseModel):
302
+ text: str
303
+ speaker: Literal["speaker-1", "speaker-2"]
304
+
305
+ class Dialogue(BaseModel):
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,
319
+ input=text,
320
+ ) as response:
321
+ with io.BytesIO() as file:
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
344
+
345
+ def conditional_llm(model, api_base=None, api_key=None):
346
+ """
347
+ Conditionally apply the @llm decorator based on the api_base parameter.
348
+ If api_base is provided, it applies the @llm decorator with api_base.
349
+ Otherwise, it applies the @llm decorator without api_base.
350
+ """
351
+ def decorator(func):
352
+ if api_base:
353
+ return llm(model=model, api_base=api_base)(func)
354
+ else:
355
+ return llm(model=model, api_key=api_key)(func)
356
+ return decorator
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 = '',
366
+ prelude_dialog: str = '',
367
+ podcast_dialog_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 = ""
540
+ characters = 0
541
+
542
+ with cf.ThreadPoolExecutor() as executor:
543
+ futures = []
544
+ for line in llm_output.dialogue:
545
+ transcript_line = f"{line.speaker}: {line.text}"
546
+ voice = speaker_1_voice if line.speaker == "speaker-1" else speaker_2_voice
547
+ future = executor.submit(get_mp3, line.text, voice, audio_model, openai_api_key)
548
+ futures.append((future, transcript_line))
549
+ characters += len(line.text)
550
+
551
+ for future, transcript_line in futures:
552
+ audio_chunk = future.result()
553
+ audio += audio_chunk
554
+ transcript += transcript_line + "\n\n"
555
+
556
+ logger.info(f"Generated {characters} characters of audio")
557
+
558
+ temporary_directory = "./gradio_cached_examples/tmp/"
559
+ os.makedirs(temporary_directory, exist_ok=True)
560
+
561
+ # Use a temporary file -- Gradio's audio component doesn't work with raw bytes in Safari
562
+ temporary_file = NamedTemporaryFile(
563
+ dir=temporary_directory,
564
+ delete=False,
565
+ suffix=".mp3",
566
+ )
567
+ temporary_file.write(audio)
568
+ temporary_file.close()
569
+
570
+ # Delete any files in the temp directory that end with .mp3 and are over a day old
571
+ for file in glob.glob(f"{temporary_directory}*.mp3"):
572
+ if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
573
+ os.remove(file)
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)
637
+ #new_args[-2] = edited_transcript # Update edited transcript
638
+ #new_args[-1] = user_feedback # Update user feedback
639
+ return validate_and_generate_audio(*new_args)
640
+
641
+ # New function to handle user feedback and regeneration
642
+ def process_feedback_and_regenerate(feedback, *args):
643
+ # Add user feedback to the args
644
+ new_args = list(args)
645
+ new_args.append(feedback) # Add user feedback as a new argument
646
+ return validate_and_generate_audio(*new_args)
647
+
648
+
649
+
650
+ with gr.Blocks(title="PDF to Podcast", css="""
651
+ #header {
652
+ display: flex;
653
+ align-items: center;
654
+ justify-content: space-between;
655
+ padding: 20px;
656
+ background-color: transparent;
657
+ border-bottom: 1px solid #ddd;
658
+ }
659
+ #title {
660
+ font-size: 24px;
661
+ margin: 0;
662
+ }
663
+ #logo_container {
664
+ width: 200px;
665
+ height: 200px;
666
+ display: flex;
667
+ justify-content: center;
668
+ align-items: center;
669
+ }
670
+ #logo_image {
671
+ max-width: 100%;
672
+ max-height: 100%;
673
+ object-fit: contain;
674
+ }
675
+ #main_container {
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")
683
+ with gr.Column(scale=1):
684
+ gr.HTML('''
685
+ <div id="logo_container">
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):
780
+ audio_output = gr.Audio(label="Audio", format="mp3", interactive=False, autoplay=False)
781
+ transcript_output = gr.Textbox(label="Transcript", lines=20, show_copy_button=True)
782
+ original_text_output = gr.Textbox(label="Original Text", lines=10, visible=False)
783
+ error_output = gr.Textbox(visible=False)
784
+
785
+ use_edited_transcript = gr.Checkbox(label="Use Edited Transcript", value=False)
786
+ edited_transcript = gr.Textbox(label="Edit Transcript Here", lines=20, visible=False, show_copy_button=True, interactive=False)
787
+
788
+ user_feedback = gr.Textbox(label="Provide Feedback or Notes", lines=10)
789
+ regenerate_btn = gr.Button("Regenerate Podcast with Edits and Feedback")
790
+
791
+ # 中間部分輸入選項區域放置在下方
792
+ 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(
806
+ label="Standard Text Analysis Instructions",
807
+ lines=10,
808
+ placeholder="Enter text analysis instructions...",
809
+ value=INSTRUCTION_TEMPLATES["podcast"]["text_instructions"],
810
+ info="Provide the instructions for analyzing the raw data and text.",
811
+ )
812
+ scratch_pad_instructions = gr.Textbox(
813
+ label="Scratch Pad Instructions",
814
+ lines=15,
815
+ value=INSTRUCTION_TEMPLATES["podcast"]["scratch_pad"],
816
+ info="Provide the scratch pad instructions for brainstorming presentation/dialogue content.",
817
+ )
818
+ prelude_dialog = gr.Textbox(
819
+ label="Prelude Dialog",
820
+ lines=5,
821
+ value=INSTRUCTION_TEMPLATES["podcast"]["prelude"],
822
+ info="Provide the prelude instructions before the presentation/dialogue is developed.",
823
+ )
824
+ podcast_dialog_instructions = gr.Textbox(
825
+ label="Podcast Dialog Instructions",
826
+ lines=20,
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
+
834
+ use_edited_transcript.change(fn=update_edit_box, inputs=[use_edited_transcript], outputs=[edited_transcript])
835
+ template_dropdown.change(fn=update_instructions, inputs=[template_dropdown], outputs=[intro_instructions, text_instructions, scratch_pad_instructions, prelude_dialog, podcast_dialog_instructions])
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:]),
866
+ inputs=[use_edited_transcript, edited_transcript, files, openai_api_key, text_model, audio_model, speaker_1_voice, speaker_2_voice, api_base, intro_instructions, text_instructions, scratch_pad_instructions, prelude_dialog, podcast_dialog_instructions, user_feedback, original_text_output],
867
+ outputs=[audio_output, transcript_output, original_text_output, error_output]
868
+ )
869
+
870
+ # Launch the Gradio app
871
+ if __name__ == "__main__":
872
+ demo.launch()
requirements.txt CHANGED
@@ -4,4 +4,6 @@ openai
4
  loguru
5
  promptic
6
  tenacity
7
- PyMuPDF
 
 
 
4
  loguru
5
  promptic
6
  tenacity
7
+ PyMuPDF
8
+ ebooklib
9
+ bs4