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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
|
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 |
+
|
10 |
+
import gradio as gr
|
11 |
+
|
12 |
+
from loguru import logger
|
13 |
+
from openai import OpenAI
|
14 |
+
from promptic import llm
|
15 |
+
from pydantic import BaseModel, ValidationError
|
16 |
+
from pypdf import PdfReader
|
17 |
+
from tenacity import retry, retry_if_exception_type
|
18 |
+
|
19 |
+
import re
|
20 |
+
|
21 |
+
def read_readme():
|
22 |
+
readme_path = Path("README.md")
|
23 |
+
if readme_path.exists():
|
24 |
+
with open(readme_path, "r") as file:
|
25 |
+
content = file.read()
|
26 |
+
# Use regex to remove metadata enclosed in -- ... --
|
27 |
+
content = re.sub(r'--.*?--', '', content, flags=re.DOTALL)
|
28 |
+
return content
|
29 |
+
else:
|
30 |
+
return "README.md not found. Please check the repository for more information."
|
31 |
+
|
32 |
+
# Define multiple sets of instruction templates
|
33 |
+
INSTRUCTION_TEMPLATES = {
|
34 |
+
################# PODCAST ##################
|
35 |
+
"podcast": {
|
36 |
+
"intro": """Your task is to take the input text provided and turn it into an lively, engaging, informative podcast dialogue, in the style of NPR. The input text may be messy or unstructured, as it could come from a variety of sources like PDFs or web pages.
|
37 |
+
|
38 |
+
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.
|
39 |
+
|
40 |
+
Define all terms used carefully for a broad audience of listeners.
|
41 |
+
""",
|
42 |
+
"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.",
|
43 |
+
"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.
|
44 |
+
|
45 |
+
Keep in mind that your podcast 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.
|
46 |
+
|
47 |
+
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.
|
48 |
+
|
49 |
+
Define all terms used clearly and spend effort to explain the background.
|
50 |
+
|
51 |
+
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.
|
52 |
+
|
53 |
+
Make sure to make it fun and exciting.
|
54 |
+
""",
|
55 |
+
"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.
|
56 |
+
""",
|
57 |
+
"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.
|
58 |
+
|
59 |
+
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.
|
60 |
+
|
61 |
+
Make the dialogue as long and detailed as possible, 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.
|
62 |
+
|
63 |
+
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.
|
64 |
+
|
65 |
+
The podcast should have around 20000 words.
|
66 |
+
""",
|
67 |
+
},
|
68 |
+
################# MATERIAL DISCOVERY SUMMARY ##################
|
69 |
+
"SciAgents material discovery summary": {
|
70 |
+
"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.
|
71 |
+
|
72 |
+
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.
|
73 |
+
|
74 |
+
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.
|
75 |
+
|
76 |
+
Define all terms used carefully for a broad audience of listeners.
|
77 |
+
""",
|
78 |
+
"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.",
|
79 |
+
"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.
|
80 |
+
|
81 |
+
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.
|
82 |
+
|
83 |
+
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.
|
84 |
+
|
85 |
+
Define all terms used clearly and spend effort to explain the background.
|
86 |
+
|
87 |
+
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.
|
88 |
+
|
89 |
+
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.
|
90 |
+
""",
|
91 |
+
"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.
|
92 |
+
""",
|
93 |
+
"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.
|
94 |
+
|
95 |
+
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.
|
96 |
+
|
97 |
+
Remember, this describes a design developed by SciAgents, and this must be explicitly stated for the listeners.
|
98 |
+
|
99 |
+
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.
|
100 |
+
|
101 |
+
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.
|
102 |
+
|
103 |
+
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.
|
104 |
+
|
105 |
+
The conversation should have around 20000 words.
|
106 |
+
"""
|
107 |
+
},
|
108 |
+
################# LECTURE ##################
|
109 |
+
"lecture": {
|
110 |
+
"intro": """You are Professor Richard Feynman. Your task is to develop a script for a lecture. You never mention your name.
|
111 |
+
|
112 |
+
The material covered in the lecture is based on the provided text.
|
113 |
+
|
114 |
+
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.
|
115 |
+
|
116 |
+
Define all terms used carefully for a broad audience of students.
|
117 |
+
""",
|
118 |
+
"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.",
|
119 |
+
"scratch_pad": """
|
120 |
+
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.
|
121 |
+
|
122 |
+
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.
|
123 |
+
|
124 |
+
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.
|
125 |
+
|
126 |
+
Define all terms used clearly and spend effort to explain the background.
|
127 |
+
|
128 |
+
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.
|
129 |
+
|
130 |
+
Make sure to make it fun and exciting.
|
131 |
+
""",
|
132 |
+
"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.
|
133 |
+
""",
|
134 |
+
"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.
|
135 |
+
|
136 |
+
Include clear definitions and terms, and examples.
|
137 |
+
|
138 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
139 |
+
|
140 |
+
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.
|
141 |
+
|
142 |
+
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.
|
143 |
+
|
144 |
+
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.
|
145 |
+
|
146 |
+
The lecture should have around 20000 words.
|
147 |
+
""",
|
148 |
+
},
|
149 |
+
################# SUMMARY ##################
|
150 |
+
"summary": {
|
151 |
+
"intro": """Your task is to develop a summary of a paper. You never mention your name.
|
152 |
+
|
153 |
+
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.
|
154 |
+
|
155 |
+
Define all terms used carefully for a broad audience.
|
156 |
+
""",
|
157 |
+
"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.",
|
158 |
+
"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.
|
159 |
+
|
160 |
+
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.
|
161 |
+
|
162 |
+
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.
|
163 |
+
|
164 |
+
Make sure to make it engaging and exciting.
|
165 |
+
""",
|
166 |
+
"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.
|
167 |
+
""",
|
168 |
+
"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.
|
169 |
+
|
170 |
+
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.
|
171 |
+
|
172 |
+
Include clear definitions and terms, and examples, of all key issues.
|
173 |
+
|
174 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
175 |
+
|
176 |
+
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
177 |
+
|
178 |
+
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.
|
179 |
+
|
180 |
+
The summary should have around 1024 words.
|
181 |
+
""",
|
182 |
+
},
|
183 |
+
################# SHORT SUMMARY ##################
|
184 |
+
"short summary": {
|
185 |
+
"intro": """Your task is to develop a summary of a paper. You never mention your name.
|
186 |
+
|
187 |
+
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.
|
188 |
+
|
189 |
+
Define all terms used carefully for a broad audience.
|
190 |
+
""",
|
191 |
+
"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.",
|
192 |
+
"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.
|
193 |
+
|
194 |
+
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.
|
195 |
+
|
196 |
+
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.
|
197 |
+
|
198 |
+
Make sure to make it engaging and exciting.
|
199 |
+
""",
|
200 |
+
"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.
|
201 |
+
""",
|
202 |
+
"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.
|
203 |
+
|
204 |
+
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.
|
205 |
+
|
206 |
+
Include clear definitions and terms, and examples, of all key issues.
|
207 |
+
|
208 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
209 |
+
|
210 |
+
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
211 |
+
|
212 |
+
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.
|
213 |
+
|
214 |
+
The summary should have around 256 words.
|
215 |
+
""",
|
216 |
+
},
|
217 |
+
}
|
218 |
+
|
219 |
+
# Function to update instruction fields based on template selection
|
220 |
+
def update_instructions(template):
|
221 |
+
return (
|
222 |
+
INSTRUCTION_TEMPLATES[template]["intro"],
|
223 |
+
INSTRUCTION_TEMPLATES[template]["text_instructions"],
|
224 |
+
INSTRUCTION_TEMPLATES[template]["scratch_pad"],
|
225 |
+
INSTRUCTION_TEMPLATES[template]["prelude"],
|
226 |
+
INSTRUCTION_TEMPLATES[template]["dialog"]
|
227 |
+
)
|
228 |
+
|
229 |
+
import concurrent.futures as cf
|
230 |
+
import glob
|
231 |
+
import io
|
232 |
+
import os
|
233 |
+
import time
|
234 |
+
from pathlib import Path
|
235 |
+
from tempfile import NamedTemporaryFile
|
236 |
+
from typing import List, Literal
|
237 |
+
|
238 |
import gradio as gr
|
239 |
|
240 |
+
from loguru import logger
|
241 |
+
from openai import OpenAI
|
242 |
+
from promptic import llm
|
243 |
+
from pydantic import BaseModel, ValidationError
|
244 |
+
from pypdf import PdfReader
|
245 |
+
from tenacity import retry, retry_if_exception_type
|
246 |
+
|
247 |
+
# Define standard values
|
248 |
+
STANDARD_TEXT_MODELS = [
|
249 |
+
"o1-preview-2024-09-12",
|
250 |
+
"o1-preview",
|
251 |
+
"gpt-4o-2024-08-06",
|
252 |
+
"gpt-4o-mini",
|
253 |
+
"o1-mini-2024-09-12",
|
254 |
+
"o1-mini",
|
255 |
+
"chatgpt-4o-latest",
|
256 |
+
"gpt-4-turbo",
|
257 |
+
"openai/custom_model",
|
258 |
+
]
|
259 |
+
|
260 |
+
STANDARD_AUDIO_MODELS = [
|
261 |
+
"tts-1",
|
262 |
+
"tts-1-hd",
|
263 |
+
]
|
264 |
+
|
265 |
+
STANDARD_VOICES = [
|
266 |
+
"alloy",
|
267 |
+
"echo",
|
268 |
+
"fable",
|
269 |
+
"onyx",
|
270 |
+
"nova",
|
271 |
+
"shimmer",
|
272 |
+
]
|
273 |
+
|
274 |
+
class DialogueItem(BaseModel):
|
275 |
+
text: str
|
276 |
+
speaker: Literal["speaker-1", "speaker-2"]
|
277 |
+
|
278 |
+
class Dialogue(BaseModel):
|
279 |
+
scratchpad: str
|
280 |
+
dialogue: List[DialogueItem]
|
281 |
+
|
282 |
+
def get_mp3(text: str, voice: str, audio_model: str, api_key: str = None) -> bytes:
|
283 |
+
client = OpenAI(
|
284 |
+
api_key=api_key or os.getenv("OPENAI_API_KEY"),
|
285 |
+
)
|
286 |
+
|
287 |
+
with client.audio.speech.with_streaming_response.create(
|
288 |
+
model=audio_model,
|
289 |
+
voice=voice,
|
290 |
+
input=text,
|
291 |
+
) as response:
|
292 |
+
with io.BytesIO() as file:
|
293 |
+
for chunk in response.iter_bytes():
|
294 |
+
file.write(chunk)
|
295 |
+
return file.getvalue()
|
296 |
+
|
297 |
+
|
298 |
+
from functools import wraps
|
299 |
+
|
300 |
+
def conditional_llm(model, api_base=None, api_key=None):
|
301 |
+
"""
|
302 |
+
Conditionally apply the @llm decorator based on the api_base parameter.
|
303 |
+
If api_base is provided, it applies the @llm decorator with api_base.
|
304 |
+
Otherwise, it applies the @llm decorator without api_base.
|
305 |
+
"""
|
306 |
+
def decorator(func):
|
307 |
+
if api_base:
|
308 |
+
return llm(model=model, api_base=api_base)(func)
|
309 |
+
else:
|
310 |
+
return llm(model=model, api_key=api_key)(func)
|
311 |
+
return decorator
|
312 |
+
|
313 |
+
def generate_audio(
|
314 |
+
files: list,
|
315 |
+
openai_api_key: str = None,
|
316 |
+
text_model: str = "o1-preview-2024-09-12",
|
317 |
+
audio_model: str = "tts-1",
|
318 |
+
speaker_1_voice: str = "alloy",
|
319 |
+
speaker_2_voice: str = "echo",
|
320 |
+
api_base: str = None,
|
321 |
+
intro_instructions: str = '',
|
322 |
+
text_instructions: str = '',
|
323 |
+
scratch_pad_instructions: str = '',
|
324 |
+
prelude_dialog: str = '',
|
325 |
+
podcast_dialog_instructions: str = '',
|
326 |
+
edited_transcript: str = None,
|
327 |
+
user_feedback: str = None,
|
328 |
+
original_text: str = None,
|
329 |
+
debug = False,
|
330 |
+
) -> tuple:
|
331 |
+
# Validate API Key
|
332 |
+
if not os.getenv("OPENAI_API_KEY") and not openai_api_key:
|
333 |
+
raise gr.Error("OpenAI API key is required")
|
334 |
+
|
335 |
+
combined_text = original_text or ""
|
336 |
+
|
337 |
+
# If there's no original text, extract it from the uploaded files
|
338 |
+
if not combined_text:
|
339 |
+
for file in files:
|
340 |
+
with Path(file).open("rb") as f:
|
341 |
+
reader = PdfReader(f)
|
342 |
+
text = "\n\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
|
343 |
+
combined_text += text + "\n\n"
|
344 |
+
|
345 |
+
# Configure the LLM based on selected model and api_base
|
346 |
+
@retry(retry=retry_if_exception_type(ValidationError))
|
347 |
+
@conditional_llm(model=text_model, api_base=api_base, api_key=openai_api_key)
|
348 |
+
def generate_dialogue(text: str, intro_instructions: str, text_instructions: str, scratch_pad_instructions: str,
|
349 |
+
prelude_dialog: str, podcast_dialog_instructions: str,
|
350 |
+
edited_transcript: str = None, user_feedback: str = None, ) -> Dialogue:
|
351 |
+
"""
|
352 |
+
{intro_instructions}
|
353 |
+
|
354 |
+
Here is the original input text:
|
355 |
+
|
356 |
+
<input_text>
|
357 |
+
{text}
|
358 |
+
</input_text>
|
359 |
+
|
360 |
+
{text_instructions}
|
361 |
+
|
362 |
+
<scratchpad>
|
363 |
+
{scratch_pad_instructions}
|
364 |
+
</scratchpad>
|
365 |
+
|
366 |
+
{prelude_dialog}
|
367 |
+
|
368 |
+
<podcast_dialogue>
|
369 |
+
{podcast_dialog_instructions}
|
370 |
+
</podcast_dialogue>
|
371 |
+
{edited_transcript}{user_feedback}
|
372 |
+
"""
|
373 |
+
|
374 |
+
instruction_improve='Based on the original text, please generate an improved version of the dialogue by incorporating the edits, comments and feedback.'
|
375 |
+
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 ""
|
376 |
+
user_feedback_processed="\nOverall user feedback:\n\n"+user_feedback if user_feedback !="" else ""
|
377 |
+
|
378 |
+
if edited_transcript_processed.strip()!='' or user_feedback_processed.strip()!='':
|
379 |
+
user_feedback_processed="<requested_improvements>"+user_feedback_processed+"\n\n"+instruction_improve+"</requested_improvements>"
|
380 |
+
|
381 |
+
if debug:
|
382 |
+
logger.info (edited_transcript_processed)
|
383 |
+
logger.info (user_feedback_processed)
|
384 |
+
|
385 |
+
# Generate the dialogue using the LLM
|
386 |
+
llm_output = generate_dialogue(
|
387 |
+
combined_text,
|
388 |
+
intro_instructions=intro_instructions,
|
389 |
+
text_instructions=text_instructions,
|
390 |
+
scratch_pad_instructions=scratch_pad_instructions,
|
391 |
+
prelude_dialog=prelude_dialog,
|
392 |
+
podcast_dialog_instructions=podcast_dialog_instructions,
|
393 |
+
edited_transcript=edited_transcript_processed,
|
394 |
+
user_feedback=user_feedback_processed
|
395 |
+
)
|
396 |
+
|
397 |
+
# Generate audio from the transcript
|
398 |
+
audio = b""
|
399 |
+
transcript = ""
|
400 |
+
characters = 0
|
401 |
+
|
402 |
+
with cf.ThreadPoolExecutor() as executor:
|
403 |
+
futures = []
|
404 |
+
for line in llm_output.dialogue:
|
405 |
+
transcript_line = f"{line.speaker}: {line.text}"
|
406 |
+
voice = speaker_1_voice if line.speaker == "speaker-1" else speaker_2_voice
|
407 |
+
future = executor.submit(get_mp3, line.text, voice, audio_model, openai_api_key)
|
408 |
+
futures.append((future, transcript_line))
|
409 |
+
characters += len(line.text)
|
410 |
+
|
411 |
+
for future, transcript_line in futures:
|
412 |
+
audio_chunk = future.result()
|
413 |
+
audio += audio_chunk
|
414 |
+
transcript += transcript_line + "\n\n"
|
415 |
+
|
416 |
+
logger.info(f"Generated {characters} characters of audio")
|
417 |
+
|
418 |
+
temporary_directory = "./gradio_cached_examples/tmp/"
|
419 |
+
os.makedirs(temporary_directory, exist_ok=True)
|
420 |
+
|
421 |
+
# Use a temporary file -- Gradio's audio component doesn't work with raw bytes in Safari
|
422 |
+
temporary_file = NamedTemporaryFile(
|
423 |
+
dir=temporary_directory,
|
424 |
+
delete=False,
|
425 |
+
suffix=".mp3",
|
426 |
+
)
|
427 |
+
temporary_file.write(audio)
|
428 |
+
temporary_file.close()
|
429 |
+
|
430 |
+
# Delete any files in the temp directory that end with .mp3 and are over a day old
|
431 |
+
for file in glob.glob(f"{temporary_directory}*.mp3"):
|
432 |
+
if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
|
433 |
+
os.remove(file)
|
434 |
+
|
435 |
+
return temporary_file.name, transcript, combined_text
|
436 |
+
|
437 |
+
def validate_and_generate_audio(*args):
|
438 |
+
files = args[0]
|
439 |
+
if not files:
|
440 |
+
return None, None, None, "Please upload at least one PDF file before generating audio."
|
441 |
+
try:
|
442 |
+
audio_file, transcript, original_text = generate_audio(*args)
|
443 |
+
return audio_file, transcript, original_text, None # Return None as the error when successful
|
444 |
+
except Exception as e:
|
445 |
+
# If an error occurs during generation, return None for the outputs and the error message
|
446 |
+
return None, None, None, str(e)
|
447 |
+
|
448 |
+
def edit_and_regenerate(edited_transcript, user_feedback, *args):
|
449 |
+
# Replace the original transcript and feedback in the args with the new ones
|
450 |
+
#new_args = list(args)
|
451 |
+
#new_args[-2] = edited_transcript # Update edited transcript
|
452 |
+
#new_args[-1] = user_feedback # Update user feedback
|
453 |
+
return validate_and_generate_audio(*new_args)
|
454 |
+
|
455 |
+
# New function to handle user feedback and regeneration
|
456 |
+
def process_feedback_and_regenerate(feedback, *args):
|
457 |
+
# Add user feedback to the args
|
458 |
+
new_args = list(args)
|
459 |
+
new_args.append(feedback) # Add user feedback as a new argument
|
460 |
+
return validate_and_generate_audio(*new_args)
|
461 |
+
|
462 |
+
with gr.Blocks(title="PDF to Audio", css="""
|
463 |
+
#header {
|
464 |
+
display: flex;
|
465 |
+
align-items: center;
|
466 |
+
justify-content: space-between;
|
467 |
+
padding: 20px;
|
468 |
+
background-color: transparent;
|
469 |
+
border-bottom: 1px solid #ddd;
|
470 |
+
}
|
471 |
+
#title {
|
472 |
+
font-size: 24px;
|
473 |
+
margin: 0;
|
474 |
+
}
|
475 |
+
#logo_container {
|
476 |
+
width: 200px;
|
477 |
+
height: 200px;
|
478 |
+
display: flex;
|
479 |
+
justify-content: center;
|
480 |
+
align-items: center;
|
481 |
+
}
|
482 |
+
#logo_image {
|
483 |
+
max-width: 100%;
|
484 |
+
max-height: 100%;
|
485 |
+
object-fit: contain;
|
486 |
+
}
|
487 |
+
#main_container {
|
488 |
+
margin-top: 20px;
|
489 |
+
}
|
490 |
+
""") as demo:
|
491 |
+
|
492 |
+
with gr.Row(elem_id="header"):
|
493 |
+
with gr.Column(scale=4):
|
494 |
+
gr.Markdown("# Convert PDFs into an audio podcast, lecture, summary and others\n\nFirst, upload one or more PDFs, select options, then push Generate Audio.\n\nYou can also select a variety of custom option and direct the way the result is generated.", elem_id="title")
|
495 |
+
with gr.Column(scale=1):
|
496 |
+
gr.HTML('''
|
497 |
+
<div id="logo_container">
|
498 |
+
<img src="https://huggingface.co/spaces/lamm-mit/PDF2Audio/resolve/main/logo.png" id="logo_image" alt="Logo">
|
499 |
+
</div>
|
500 |
+
''')
|
501 |
+
#gr.Markdown("")
|
502 |
+
submit_btn = gr.Button("Generate Audio", elem_id="submit_btn")
|
503 |
+
|
504 |
+
with gr.Row(elem_id="main_container"):
|
505 |
+
with gr.Column(scale=2):
|
506 |
+
files = gr.Files(label="PDFs", file_types=["pdf"], )
|
507 |
+
|
508 |
+
openai_api_key = gr.Textbox(
|
509 |
+
label="OpenAI API Key",
|
510 |
+
visible=True, # Always show the API key field
|
511 |
+
placeholder="Enter your OpenAI API Key here...",
|
512 |
+
type="password" # Hide the API key input
|
513 |
+
)
|
514 |
+
text_model = gr.Dropdown(
|
515 |
+
label="Text Generation Model",
|
516 |
+
choices=STANDARD_TEXT_MODELS,
|
517 |
+
value="o1-preview-2024-09-12", #"gpt-4o-mini",
|
518 |
+
info="Select the model to generate the dialogue text.",
|
519 |
+
)
|
520 |
+
audio_model = gr.Dropdown(
|
521 |
+
label="Audio Generation Model",
|
522 |
+
choices=STANDARD_AUDIO_MODELS,
|
523 |
+
value="tts-1",
|
524 |
+
info="Select the model to generate the audio.",
|
525 |
+
)
|
526 |
+
speaker_1_voice = gr.Dropdown(
|
527 |
+
label="Speaker 1 Voice",
|
528 |
+
choices=STANDARD_VOICES,
|
529 |
+
value="alloy",
|
530 |
+
info="Select the voice for Speaker 1.",
|
531 |
+
)
|
532 |
+
speaker_2_voice = gr.Dropdown(
|
533 |
+
label="Speaker 2 Voice",
|
534 |
+
choices=STANDARD_VOICES,
|
535 |
+
value="echo",
|
536 |
+
info="Select the voice for Speaker 2.",
|
537 |
+
)
|
538 |
+
api_base = gr.Textbox(
|
539 |
+
label="Custom API Base",
|
540 |
+
placeholder="Enter custom API base URL if using a custom/local model...",
|
541 |
+
info="If you are using a custom or local model, provide the API base URL here, e.g.: http://localhost:8080/v1 for llama.cpp REST server.",
|
542 |
+
)
|
543 |
+
|
544 |
+
with gr.Column(scale=3):
|
545 |
+
template_dropdown = gr.Dropdown(
|
546 |
+
label="Instruction Template",
|
547 |
+
choices=list(INSTRUCTION_TEMPLATES.keys()),
|
548 |
+
value="podcast",
|
549 |
+
info="Select the instruction template to use. You can also edit any of the fields for more tailored results.",
|
550 |
+
)
|
551 |
+
intro_instructions = gr.Textbox(
|
552 |
+
label="Intro Instructions",
|
553 |
+
lines=10,
|
554 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["intro"],
|
555 |
+
info="Provide the introductory instructions for generating the dialogue.",
|
556 |
+
)
|
557 |
+
text_instructions = gr.Textbox(
|
558 |
+
label="Standard Text Analysis Instructions",
|
559 |
+
lines=10,
|
560 |
+
placeholder="Enter text analysis instructions...",
|
561 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["text_instructions"],
|
562 |
+
info="Provide the instructions for analyzing the raw data and text.",
|
563 |
+
)
|
564 |
+
scratch_pad_instructions = gr.Textbox(
|
565 |
+
label="Scratch Pad Instructions",
|
566 |
+
lines=15,
|
567 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["scratch_pad"],
|
568 |
+
info="Provide the scratch pad instructions for brainstorming presentation/dialogue content.",
|
569 |
+
)
|
570 |
+
prelude_dialog = gr.Textbox(
|
571 |
+
label="Prelude Dialog",
|
572 |
+
lines=5,
|
573 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["prelude"],
|
574 |
+
info="Provide the prelude instructions before the presentation/dialogue is developed.",
|
575 |
+
)
|
576 |
+
podcast_dialog_instructions = gr.Textbox(
|
577 |
+
label="Podcast Dialog Instructions",
|
578 |
+
lines=20,
|
579 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["dialog"],
|
580 |
+
info="Provide the instructions for generating the presentation or podcast dialogue.",
|
581 |
+
)
|
582 |
+
|
583 |
+
audio_output = gr.Audio(label="Audio", format="mp3")
|
584 |
+
transcript_output = gr.Textbox(label="Transcript", lines=20, show_copy_button=True)
|
585 |
+
original_text_output = gr.Textbox(label="Original Text", lines=10, visible=False)
|
586 |
+
error_output = gr.Textbox(visible=False) # Hidden textbox to store error message
|
587 |
+
|
588 |
+
use_edited_transcript = gr.Checkbox(label="Use Edited Transcript (check if you want to make edits to the initially generated transcript)", value=False)
|
589 |
+
edited_transcript = gr.Textbox(label="Edit Transcript Here. E.g., mark edits in the text with clear instructions. E.g., '[ADD DEFINITION OF MATERIOMICS]'.", lines=20, visible=False,
|
590 |
+
show_copy_button=True, interactive=False)
|
591 |
+
|
592 |
+
user_feedback = gr.Textbox(label="Provide Feedback or Notes", lines=10, #placeholder="Enter your feedback or notes here..."
|
593 |
+
)
|
594 |
+
regenerate_btn = gr.Button("Regenerate Audio with Edits and Feedback")
|
595 |
+
# Function to update the interactive state of edited_transcript
|
596 |
+
def update_edit_box(checkbox_value):
|
597 |
+
return gr.update(interactive=checkbox_value, lines=20 if checkbox_value else 20, visible=True if checkbox_value else False)
|
598 |
+
|
599 |
+
# Update the interactive state of edited_transcript when the checkbox is toggled
|
600 |
+
use_edited_transcript.change(
|
601 |
+
fn=update_edit_box,
|
602 |
+
inputs=[use_edited_transcript],
|
603 |
+
outputs=[edited_transcript]
|
604 |
+
)
|
605 |
+
# Update instruction fields when template is changed
|
606 |
+
template_dropdown.change(
|
607 |
+
fn=update_instructions,
|
608 |
+
inputs=[template_dropdown],
|
609 |
+
outputs=[intro_instructions, text_instructions, scratch_pad_instructions, prelude_dialog, podcast_dialog_instructions]
|
610 |
+
)
|
611 |
+
|
612 |
+
submit_btn.click(
|
613 |
+
fn=validate_and_generate_audio,
|
614 |
+
inputs=[
|
615 |
+
files, openai_api_key, text_model, audio_model,
|
616 |
+
speaker_1_voice, speaker_2_voice, api_base,
|
617 |
+
intro_instructions, text_instructions, scratch_pad_instructions,
|
618 |
+
prelude_dialog, podcast_dialog_instructions,
|
619 |
+
edited_transcript, # placeholder for edited_transcript
|
620 |
+
user_feedback, # placeholder for user_feedback
|
621 |
+
],
|
622 |
+
outputs=[audio_output, transcript_output, original_text_output, error_output]
|
623 |
+
).then(
|
624 |
+
fn=lambda audio, transcript, original_text, error: (
|
625 |
+
transcript if transcript else "",
|
626 |
+
error if error else None
|
627 |
+
),
|
628 |
+
inputs=[audio_output, transcript_output, original_text_output, error_output],
|
629 |
+
outputs=[edited_transcript, error_output]
|
630 |
+
).then(
|
631 |
+
fn=lambda error: gr.Warning(error) if error else None,
|
632 |
+
inputs=[error_output],
|
633 |
+
outputs=[]
|
634 |
+
)
|
635 |
+
|
636 |
+
regenerate_btn.click(
|
637 |
+
fn=lambda use_edit, edit, *args: validate_and_generate_audio(
|
638 |
+
*args[:12], # All inputs up to podcast_dialog_instructions
|
639 |
+
edit if use_edit else "", # Use edited transcript if checkbox is checked, otherwise empty string
|
640 |
+
*args[12:] # user_feedback and original_text_output
|
641 |
+
),
|
642 |
+
inputs=[
|
643 |
+
use_edited_transcript, edited_transcript,
|
644 |
+
files, openai_api_key, text_model, audio_model,
|
645 |
+
speaker_1_voice, speaker_2_voice, api_base,
|
646 |
+
intro_instructions, text_instructions, scratch_pad_instructions,
|
647 |
+
prelude_dialog, podcast_dialog_instructions,
|
648 |
+
user_feedback, original_text_output
|
649 |
+
],
|
650 |
+
outputs=[audio_output, transcript_output, original_text_output, error_output]
|
651 |
+
).then(
|
652 |
+
fn=lambda audio, transcript, original_text, error: (
|
653 |
+
transcript if transcript else "",
|
654 |
+
error if error else None
|
655 |
+
),
|
656 |
+
inputs=[audio_output, transcript_output, original_text_output, error_output],
|
657 |
+
outputs=[edited_transcript, error_output]
|
658 |
+
).then(
|
659 |
+
fn=lambda error: gr.Warning(error) if error else None,
|
660 |
+
inputs=[error_output],
|
661 |
+
outputs=[]
|
662 |
+
)
|
663 |
+
|
664 |
+
# Add README content at the bottom
|
665 |
+
gr.Markdown("---") # Horizontal line to separate the interface from README
|
666 |
+
gr.Markdown(read_readme())
|
667 |
+
|
668 |
+
# Enable queueing for better performance
|
669 |
+
demo.queue(max_size=20, default_concurrency_limit=32)
|
670 |
|
671 |
+
# Launch the Gradio app
|
672 |
+
if __name__ == "__main__":
|
673 |
+
demo.launch()
|