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|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Define multiple sets of instruction templates
|
20 |
+
INSTRUCTION_TEMPLATES = {
|
21 |
+
"material discovery summary": {
|
22 |
+
"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.
|
23 |
+
|
24 |
+
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.
|
25 |
+
|
26 |
+
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.
|
27 |
+
|
28 |
+
Define all terms used carefully for a broad audience of listeners.
|
29 |
+
""",
|
30 |
+
"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.",
|
31 |
+
"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.
|
32 |
+
|
33 |
+
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.
|
34 |
+
|
35 |
+
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.
|
36 |
+
|
37 |
+
Define all terms used clearly and spend effort to explain the background.
|
38 |
+
|
39 |
+
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.
|
40 |
+
|
41 |
+
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.
|
42 |
+
""",
|
43 |
+
"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.
|
44 |
+
""",
|
45 |
+
"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.
|
46 |
+
|
47 |
+
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.
|
48 |
+
|
49 |
+
Remember, this describes a design developed by SciAgents, and this must be explicitly stated for the listeners.
|
50 |
+
|
51 |
+
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.
|
52 |
+
|
53 |
+
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.
|
54 |
+
|
55 |
+
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.
|
56 |
+
|
57 |
+
The podcast should have around 20000 words.
|
58 |
+
"""
|
59 |
+
},
|
60 |
+
"podcast": {
|
61 |
+
"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.
|
62 |
+
|
63 |
+
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.
|
64 |
+
|
65 |
+
Define all terms used carefully for a broad audience of listeners.
|
66 |
+
""",
|
67 |
+
"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.",
|
68 |
+
"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.
|
69 |
+
|
70 |
+
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.
|
71 |
+
|
72 |
+
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.
|
73 |
+
|
74 |
+
Define all terms used clearly and spend effort to explain the background.
|
75 |
+
|
76 |
+
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.
|
77 |
+
|
78 |
+
Make sure to make it fun and exciting.
|
79 |
+
""",
|
80 |
+
"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.
|
81 |
+
""",
|
82 |
+
"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.
|
83 |
+
|
84 |
+
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.
|
85 |
+
|
86 |
+
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.
|
87 |
+
|
88 |
+
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.
|
89 |
+
|
90 |
+
The podcast should have around 20000 words.
|
91 |
+
""",
|
92 |
+
},
|
93 |
+
"lecture": {
|
94 |
+
"intro": """You are Professor Richard Feynman. Your task is to develop a script for a lecture. You never mention your name.
|
95 |
+
|
96 |
+
The material covered in the lecture is based on the provided text.
|
97 |
+
|
98 |
+
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.
|
99 |
+
|
100 |
+
Define all terms used carefully for a broad audience of students.
|
101 |
+
""",
|
102 |
+
"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.",
|
103 |
+
"scratch_pad": """
|
104 |
+
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.
|
105 |
+
|
106 |
+
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.
|
107 |
+
|
108 |
+
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.
|
109 |
+
|
110 |
+
Define all terms used clearly and spend effort to explain the background.
|
111 |
+
|
112 |
+
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.
|
113 |
+
|
114 |
+
Make sure to make it fun and exciting.
|
115 |
+
""",
|
116 |
+
"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.
|
117 |
+
""",
|
118 |
+
"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.
|
119 |
+
|
120 |
+
Include clear definitions and terms, and examples.
|
121 |
+
|
122 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
123 |
+
|
124 |
+
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.
|
125 |
+
|
126 |
+
At the end of the dialogue, 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.
|
127 |
+
|
128 |
+
Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas one last time before class is over.
|
129 |
+
|
130 |
+
The lecture should have around 20000 words.
|
131 |
+
""",
|
132 |
+
},
|
133 |
+
"short summary": {
|
134 |
+
"intro": """Your task is to develop a summary of a paper. You never mention your name.
|
135 |
+
|
136 |
+
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.
|
137 |
+
|
138 |
+
Define all terms used carefully for a broad audience.
|
139 |
+
""",
|
140 |
+
"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 an accurate summary.",
|
141 |
+
"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.
|
142 |
+
|
143 |
+
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.
|
144 |
+
|
145 |
+
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.
|
146 |
+
|
147 |
+
Define all terms used clearly and spend effort to explain the background.
|
148 |
+
|
149 |
+
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.
|
150 |
+
|
151 |
+
Make sure to make it fun and exciting.
|
152 |
+
""",
|
153 |
+
"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.
|
154 |
+
""",
|
155 |
+
"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 students.
|
156 |
+
|
157 |
+
Start your script by stating that this is a summary, referencing the title or headings in the input text.
|
158 |
+
|
159 |
+
Include clear definitions and terms, and examples.
|
160 |
+
|
161 |
+
Do not include any bracketed placeholders like [Host] or [Guest]. Design your output to be read aloud -- it will be directly converted into audio.
|
162 |
+
|
163 |
+
There is only one speaker, you. Stay on topic and maintaining an engaging flow.
|
164 |
+
|
165 |
+
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.
|
166 |
+
|
167 |
+
The summary should have around 512 words.
|
168 |
+
""",
|
169 |
+
},
|
170 |
+
}
|
171 |
+
|
172 |
+
# Function to update instruction fields based on template selection
|
173 |
+
def update_instructions(template):
|
174 |
+
return (
|
175 |
+
INSTRUCTION_TEMPLATES[template]["intro"],
|
176 |
+
INSTRUCTION_TEMPLATES[template]["text_instructions"],
|
177 |
+
INSTRUCTION_TEMPLATES[template]["scratch_pad"],
|
178 |
+
INSTRUCTION_TEMPLATES[template]["prelude"],
|
179 |
+
INSTRUCTION_TEMPLATES[template]["dialog"]
|
180 |
+
)
|
181 |
+
|
182 |
+
import concurrent.futures as cf
|
183 |
+
import glob
|
184 |
+
import io
|
185 |
+
import os
|
186 |
+
import time
|
187 |
+
from pathlib import Path
|
188 |
+
from tempfile import NamedTemporaryFile
|
189 |
+
from typing import List, Literal
|
190 |
+
|
191 |
+
import gradio as gr
|
192 |
+
|
193 |
+
from loguru import logger
|
194 |
+
from openai import OpenAI
|
195 |
+
from promptic import llm
|
196 |
+
from pydantic import BaseModel, ValidationError
|
197 |
+
from pypdf import PdfReader
|
198 |
+
from tenacity import retry, retry_if_exception_type
|
199 |
+
|
200 |
+
# Define standard values
|
201 |
+
STANDARD_TEXT_MODELS = [
|
202 |
+
"o1-preview-2024-09-12",
|
203 |
+
"gpt-4o-2024-08-06",
|
204 |
+
"o1-mini-2024-09-12",
|
205 |
+
"gpt-4o-mini",
|
206 |
+
"openai/custom_model",
|
207 |
+
]
|
208 |
+
|
209 |
+
STANDARD_AUDIO_MODELS = [
|
210 |
+
"tts-1",
|
211 |
+
"tts-1-hd",
|
212 |
+
]
|
213 |
+
|
214 |
+
STANDARD_VOICES = [
|
215 |
+
"alloy",
|
216 |
+
"echo",
|
217 |
+
"fable",
|
218 |
+
"onyx",
|
219 |
+
"nova",
|
220 |
+
"shimmer",
|
221 |
+
]
|
222 |
+
|
223 |
+
# Uncomment and configure Sentry if needed
|
224 |
+
# sentry_sdk.init(os.getenv("SENTRY_DSN"))
|
225 |
+
|
226 |
+
# Uncomment and configure FastAPI if needed
|
227 |
+
# app = FastAPI()
|
228 |
+
# app.mount("./static", StaticFiles(directory="static"), name="static")
|
229 |
+
|
230 |
+
class DialogueItem(BaseModel):
|
231 |
+
text: str
|
232 |
+
speaker: Literal["speaker-1", "speaker-2"]
|
233 |
+
|
234 |
+
class Dialogue(BaseModel):
|
235 |
+
scratchpad: str
|
236 |
+
dialogue: List[DialogueItem]
|
237 |
+
|
238 |
+
def get_mp3(text: str, voice: str, audio_model: str, api_key: str = None) -> bytes:
|
239 |
+
client = OpenAI(
|
240 |
+
api_key=api_key or os.getenv("OPENAI_API_KEY"),
|
241 |
+
)
|
242 |
+
|
243 |
+
with client.audio.speech.with_streaming_response.create(
|
244 |
+
model=audio_model,
|
245 |
+
voice=voice,
|
246 |
+
input=text,
|
247 |
+
) as response:
|
248 |
+
with io.BytesIO() as file:
|
249 |
+
for chunk in response.iter_bytes():
|
250 |
+
file.write(chunk)
|
251 |
+
return file.getvalue()
|
252 |
+
|
253 |
+
|
254 |
+
from functools import wraps
|
255 |
+
|
256 |
+
def conditional_llm(model, api_base=None):
|
257 |
+
"""
|
258 |
+
Conditionally apply the @llm decorator based on the api_base parameter.
|
259 |
+
If api_base is provided, it applies the @llm decorator with api_base.
|
260 |
+
Otherwise, it applies the @llm decorator without api_base.
|
261 |
+
"""
|
262 |
+
def decorator(func):
|
263 |
+
if api_base:
|
264 |
+
return llm(model=model, api_base=api_base)(func)
|
265 |
+
else:
|
266 |
+
return llm(model=model)(func)
|
267 |
+
return decorator
|
268 |
+
|
269 |
+
def generate_audio(
|
270 |
+
files: list,
|
271 |
+
openai_api_key: str = None,
|
272 |
+
text_model: str = "o1-preview-2024-09-12",
|
273 |
+
audio_model: str = "tts-1",
|
274 |
+
speaker_1_voice: str = "alloy",
|
275 |
+
speaker_2_voice: str = "echo",
|
276 |
+
api_base: str = None,
|
277 |
+
intro_instructions: str = '',
|
278 |
+
text_instructions: str = '',
|
279 |
+
scratch_pad_instructions: str = '',
|
280 |
+
prelude_dialog: str = '',
|
281 |
+
podcast_dialog_instructions: str = '',
|
282 |
+
) -> bytes:
|
283 |
+
# Validate API Key
|
284 |
+
if not os.getenv("OPENAI_API_KEY") and not openai_api_key:
|
285 |
+
raise gr.Error("OpenAI API key is required")
|
286 |
+
|
287 |
+
combined_text = ""
|
288 |
+
|
289 |
+
# Loop through each uploaded file and extract text
|
290 |
+
for file in files:
|
291 |
+
with Path(file).open("rb") as f:
|
292 |
+
reader = PdfReader(f)
|
293 |
+
text = "\n\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
|
294 |
+
combined_text += text + "\n\n" # Add separation between different files' texts
|
295 |
+
|
296 |
+
# Configure the LLM based on selected model and api_base
|
297 |
+
@retry(retry=retry_if_exception_type(ValidationError))
|
298 |
+
@conditional_llm(model=text_model, api_base=api_base)
|
299 |
+
def generate_dialogue(text: str, intro_instructions: str, text_instructions: str, scratch_pad_instructions: str, prelude_dialog: str, podcast_dialog_instructions: str) -> Dialogue:
|
300 |
+
"""
|
301 |
+
{intro_instructions}
|
302 |
+
|
303 |
+
Here is the input text you will be working with:
|
304 |
+
|
305 |
+
<input_text>
|
306 |
+
{text}
|
307 |
+
</input_text>
|
308 |
+
|
309 |
+
{text_instructions}
|
310 |
+
|
311 |
+
<scratchpad>
|
312 |
+
{scratch_pad_instructions}
|
313 |
+
</scratchpad>
|
314 |
+
|
315 |
+
{prelude_dialog}
|
316 |
+
|
317 |
+
<podcast_dialogue>
|
318 |
+
{podcast_dialog_instructions}
|
319 |
+
</podcast_dialogue>
|
320 |
+
"""
|
321 |
+
|
322 |
+
# Generate the dialogue using the LLM
|
323 |
+
llm_output = generate_dialogue(
|
324 |
+
combined_text,
|
325 |
+
intro_instructions=intro_instructions,
|
326 |
+
text_instructions=text_instructions,
|
327 |
+
scratch_pad_instructions=scratch_pad_instructions,
|
328 |
+
prelude_dialog=prelude_dialog,
|
329 |
+
podcast_dialog_instructions=podcast_dialog_instructions
|
330 |
+
)
|
331 |
+
|
332 |
+
audio = b""
|
333 |
+
transcript = ""
|
334 |
+
|
335 |
+
characters = 0
|
336 |
+
|
337 |
+
with cf.ThreadPoolExecutor() as executor:
|
338 |
+
futures = []
|
339 |
+
for line in llm_output.dialogue:
|
340 |
+
transcript_line = f"{line.speaker}: {line.text}"
|
341 |
+
voice = speaker_1_voice if line.speaker == "speaker-1" else speaker_2_voice
|
342 |
+
future = executor.submit(get_mp3, line.text, voice, audio_model, openai_api_key)
|
343 |
+
futures.append((future, transcript_line))
|
344 |
+
characters += len(line.text)
|
345 |
+
|
346 |
+
for future, transcript_line in futures:
|
347 |
+
audio_chunk = future.result()
|
348 |
+
audio += audio_chunk
|
349 |
+
transcript += transcript_line + "\n\n"
|
350 |
+
|
351 |
+
logger.info(f"Generated {characters} characters of audio")
|
352 |
+
|
353 |
+
temporary_directory = "./gradio_cached_examples/tmp/"
|
354 |
+
os.makedirs(temporary_directory, exist_ok=True)
|
355 |
+
|
356 |
+
# Use a temporary file -- Gradio's audio component doesn't work with raw bytes in Safari
|
357 |
+
temporary_file = NamedTemporaryFile(
|
358 |
+
dir=temporary_directory,
|
359 |
+
delete=False,
|
360 |
+
suffix=".mp3",
|
361 |
+
)
|
362 |
+
temporary_file.write(audio)
|
363 |
+
temporary_file.close()
|
364 |
+
|
365 |
+
# Delete any files in the temp directory that end with .mp3 and are over a day old
|
366 |
+
for file in glob.glob(f"{temporary_directory}*.mp3"):
|
367 |
+
if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
|
368 |
+
os.remove(file)
|
369 |
+
|
370 |
+
return temporary_file.name, transcript
|
371 |
+
|
372 |
+
def validate_and_generate_audio(*args):
|
373 |
+
files = args[0]
|
374 |
+
if not files:
|
375 |
+
return None, None, "Please upload at least one PDF file before generating audio."
|
376 |
+
audio_file, transcript = generate_audio(*args)
|
377 |
+
return audio_file, transcript, None
|
378 |
+
|
379 |
+
with gr.Blocks(title="PDF to Audio", css="""
|
380 |
+
#main_container {margin-top: 60px;}
|
381 |
+
""") as demo:
|
382 |
+
|
383 |
+
gr.Markdown("# Convert PDFs into an audio podcast, lecture, summary and others\nFirst, upload one or more PDFs, select options, then push Generate Audio.")
|
384 |
+
submit_btn = gr.Button("Generate Audio", elem_id="submit_btn")
|
385 |
+
|
386 |
+
with gr.Row(elem_id="main_container"):
|
387 |
+
with gr.Column(scale=2):
|
388 |
+
files = gr.Files(label="PDFs", file_types=["pdf"], )
|
389 |
+
|
390 |
+
openai_api_key = gr.Textbox(
|
391 |
+
label="OpenAI API Key",
|
392 |
+
visible=not bool(os.getenv("OPENAI_API_KEY")),
|
393 |
+
placeholder="Enter your OpenAI API Key here...",
|
394 |
+
)
|
395 |
+
text_model = gr.Dropdown(
|
396 |
+
label="Text Generation Model",
|
397 |
+
choices=STANDARD_TEXT_MODELS,
|
398 |
+
value="gpt-4o-mini",
|
399 |
+
info="Select the model to generate the dialogue text.",
|
400 |
+
)
|
401 |
+
audio_model = gr.Dropdown(
|
402 |
+
label="Audio Generation Model",
|
403 |
+
choices=STANDARD_AUDIO_MODELS,
|
404 |
+
value="tts-1",
|
405 |
+
info="Select the model to generate the audio.",
|
406 |
+
)
|
407 |
+
speaker_1_voice = gr.Dropdown(
|
408 |
+
label="Speaker 1 Voice",
|
409 |
+
choices=STANDARD_VOICES,
|
410 |
+
value="alloy",
|
411 |
+
info="Select the voice for Speaker 1.",
|
412 |
+
)
|
413 |
+
speaker_2_voice = gr.Dropdown(
|
414 |
+
label="Speaker 2 Voice",
|
415 |
+
choices=STANDARD_VOICES,
|
416 |
+
value="echo",
|
417 |
+
info="Select the voice for Speaker 2.",
|
418 |
+
)
|
419 |
+
api_base = gr.Textbox(
|
420 |
+
label="Custom API Base",
|
421 |
+
placeholder="Enter custom API base URL if using a custom/local model...",
|
422 |
+
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.",
|
423 |
+
)
|
424 |
+
|
425 |
+
with gr.Column(scale=3):
|
426 |
+
template_dropdown = gr.Dropdown(
|
427 |
+
label="Instruction Template",
|
428 |
+
choices=list(INSTRUCTION_TEMPLATES.keys()),
|
429 |
+
value="podcast",
|
430 |
+
info="Select the instruction template to use.",
|
431 |
+
)
|
432 |
+
intro_instructions = gr.Textbox(
|
433 |
+
label="Intro Instructions",
|
434 |
+
lines=10,
|
435 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["intro"],
|
436 |
+
info="Provide the introductory instructions for generating the dialogue.",
|
437 |
+
)
|
438 |
+
text_instructions = gr.Textbox(
|
439 |
+
label="Standard Text Analysis Instructions",
|
440 |
+
lines=10,
|
441 |
+
placeholder="Enter text analysis instructions...",
|
442 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["text_instructions"],
|
443 |
+
info="Provide the instructions for analyzing the raw data and text.",
|
444 |
+
)
|
445 |
+
scratch_pad_instructions = gr.Textbox(
|
446 |
+
label="Scratch Pad Instructions",
|
447 |
+
lines=15,
|
448 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["scratch_pad"],
|
449 |
+
info="Provide the scratch pad instructions for brainstorming dialogue content.",
|
450 |
+
)
|
451 |
+
prelude_dialog = gr.Textbox(
|
452 |
+
label="Prelude Dialog",
|
453 |
+
lines=5,
|
454 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["prelude"],
|
455 |
+
info="Provide the prelude dialog instructions.",
|
456 |
+
)
|
457 |
+
podcast_dialog_instructions = gr.Textbox(
|
458 |
+
label="Podcast Dialog Instructions",
|
459 |
+
lines=20,
|
460 |
+
value=INSTRUCTION_TEMPLATES["podcast"]["dialog"],
|
461 |
+
info="Provide the instructions for generating the podcast dialogue.",
|
462 |
+
)
|
463 |
+
|
464 |
+
audio_output = gr.Audio(label="Audio", format="mp3")
|
465 |
+
transcript_output = gr.Textbox(label="Transcript", lines=20, show_copy_button=True)
|
466 |
+
error_output = gr.Textbox(visible=False) # Hidden textbox to store error message
|
467 |
+
|
468 |
+
# Update instruction fields when template is changed
|
469 |
+
template_dropdown.change(
|
470 |
+
fn=update_instructions,
|
471 |
+
inputs=[template_dropdown],
|
472 |
+
outputs=[intro_instructions, text_instructions, scratch_pad_instructions, prelude_dialog, podcast_dialog_instructions]
|
473 |
+
)
|
474 |
+
|
475 |
+
submit_btn.click(
|
476 |
+
fn=validate_and_generate_audio,
|
477 |
+
inputs=[
|
478 |
+
files, openai_api_key, text_model, audio_model,
|
479 |
+
speaker_1_voice, speaker_2_voice, api_base,
|
480 |
+
intro_instructions, text_instructions, scratch_pad_instructions,
|
481 |
+
prelude_dialog, podcast_dialog_instructions
|
482 |
+
],
|
483 |
+
outputs=[
|
484 |
+
audio_output,
|
485 |
+
transcript_output,
|
486 |
+
error_output
|
487 |
+
]
|
488 |
+
).then(
|
489 |
+
fn=lambda error: gr.Warning(error) if error else None,
|
490 |
+
inputs=[error_output],
|
491 |
+
outputs=[]
|
492 |
+
)
|
493 |
+
|
494 |
+
# Enable queueing for better performance
|
495 |
+
demo.queue(max_size=20, default_concurrency_limit=20)
|
496 |
+
|
497 |
+
# Launch the Gradio app
|
498 |
+
if __name__ == "__main__":
|
499 |
+
demo.launch()
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio
|
2 |
+
pandas
|
3 |
+
openai
|
4 |
+
pypdf
|
5 |
+
loguru
|
6 |
+
promptic
|
7 |
+
tenacity
|