MakiAi commited on
Commit
a51eb62
·
verified ·
1 Parent(s): 03a6519

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +155 -176
app.py CHANGED
@@ -27,196 +27,175 @@ def read_readme():
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"],
@@ -244,7 +223,7 @@ 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",
@@ -324,20 +303,20 @@ def generate_audio(
324
  prelude_dialog: str = '',
325
  podcast_dialog_instructions: str = '',
326
  ) -> bytes:
327
- # Validate API Key
328
  if not os.getenv("OPENAI_API_KEY") and not openai_api_key:
329
- raise gr.Error("OpenAI API key is required")
330
 
331
  combined_text = ""
332
 
333
- # Loop through each uploaded file and extract text
334
  for file in files:
335
  with Path(file).open("rb") as f:
336
  reader = PdfReader(f)
337
  text = "\n\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
338
- combined_text += text + "\n\n" # Add separation between different files' texts
339
 
340
- # Configure the LLM based on selected model and api_base
341
  @retry(retry=retry_if_exception_type(ValidationError))
342
  @conditional_llm(model=text_model, api_base=api_base, api_key=openai_api_key)
343
  def generate_dialogue(text: str, intro_instructions: str, text_instructions: str, scratch_pad_instructions: str,
@@ -346,7 +325,7 @@ def generate_audio(
346
  """
347
  {intro_instructions}
348
 
349
- Here is the input text you will be working with:
350
 
351
  <input_text>
352
  {text}
@@ -365,7 +344,7 @@ def generate_audio(
365
  </podcast_dialogue>
366
  """
367
 
368
- # Generate the dialogue using the LLM
369
  llm_output = generate_dialogue(
370
  combined_text,
371
  intro_instructions=intro_instructions,
@@ -399,7 +378,7 @@ def generate_audio(
399
  temporary_directory = "./gradio_cached_examples/tmp/"
400
  os.makedirs(temporary_directory, exist_ok=True)
401
 
402
- # Use a temporary file -- Gradio's audio component doesn't work with raw bytes in Safari
403
  temporary_file = NamedTemporaryFile(
404
  dir=temporary_directory,
405
  delete=False,
@@ -408,7 +387,7 @@ def generate_audio(
408
  temporary_file.write(audio)
409
  temporary_file.close()
410
 
411
- # Delete any files in the temp directory that end with .mp3 and are over a day old
412
  for file in glob.glob(f"{temporary_directory}*.mp3"):
413
  if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
414
  os.remove(file)
@@ -418,11 +397,11 @@ def generate_audio(
418
  def validate_and_generate_audio(*args):
419
  files = args[0]
420
  if not files:
421
- return None, None, "Please upload at least one PDF file before generating audio."
422
  audio_file, transcript = generate_audio(*args)
423
  return audio_file, transcript, None
424
 
425
- with gr.Blocks(title="PDF to Audio", css="""
426
  #header {
427
  display: flex;
428
  align-items: center;
@@ -454,7 +433,7 @@ with gr.Blocks(title="PDF to Audio", css="""
454
 
455
  with gr.Row(elem_id="header"):
456
  with gr.Column(scale=4):
457
- 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")
458
  with gr.Column(scale=1):
459
  gr.HTML('''
460
  <div id="logo_container">
@@ -462,92 +441,92 @@ with gr.Blocks(title="PDF to Audio", css="""
462
  </div>
463
  ''')
464
  #gr.Markdown("")
465
- submit_btn = gr.Button("Generate Audio", elem_id="submit_btn")
466
 
467
  with gr.Row(elem_id="main_container"):
468
  with gr.Column(scale=2):
469
- files = gr.Files(label="PDFs", file_types=["pdf"], )
470
 
471
  openai_api_key = gr.Textbox(
472
- label="OpenAI API Key",
473
  visible=True, # Always show the API key field
474
- placeholder="Enter your OpenAI API Key here...",
475
  type="password" # Hide the API key input
476
  )
477
  text_model = gr.Dropdown(
478
- label="Text Generation Model",
479
  choices=STANDARD_TEXT_MODELS,
480
  value="o1-preview-2024-09-12", #"gpt-4o-mini",
481
- info="Select the model to generate the dialogue text.",
482
  )
483
  audio_model = gr.Dropdown(
484
- label="Audio Generation Model",
485
  choices=STANDARD_AUDIO_MODELS,
486
  value="tts-1",
487
- info="Select the model to generate the audio.",
488
  )
489
  speaker_1_voice = gr.Dropdown(
490
- label="Speaker 1 Voice",
491
  choices=STANDARD_VOICES,
492
  value="alloy",
493
- info="Select the voice for Speaker 1.",
494
  )
495
  speaker_2_voice = gr.Dropdown(
496
- label="Speaker 2 Voice",
497
  choices=STANDARD_VOICES,
498
  value="echo",
499
- info="Select the voice for Speaker 2.",
500
  )
501
  api_base = gr.Textbox(
502
- label="Custom API Base",
503
- placeholder="Enter custom API base URL if using a custom/local model...",
504
- 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.",
505
  )
506
 
507
  with gr.Column(scale=3):
508
  template_dropdown = gr.Dropdown(
509
- label="Instruction Template",
510
  choices=list(INSTRUCTION_TEMPLATES.keys()),
511
- value="podcast",
512
- info="Select the instruction template to use. You can also edit any of the fields for more tailored results.",
513
  )
514
  intro_instructions = gr.Textbox(
515
- label="Intro Instructions",
516
  lines=10,
517
- value=INSTRUCTION_TEMPLATES["podcast"]["intro"],
518
- info="Provide the introductory instructions for generating the dialogue.",
519
  )
520
  text_instructions = gr.Textbox(
521
- label="Standard Text Analysis Instructions",
522
  lines=10,
523
- placeholder="Enter text analysis instructions...",
524
- value=INSTRUCTION_TEMPLATES["podcast"]["text_instructions"],
525
- info="Provide the instructions for analyzing the raw data and text.",
526
  )
527
  scratch_pad_instructions = gr.Textbox(
528
- label="Scratch Pad Instructions",
529
  lines=15,
530
- value=INSTRUCTION_TEMPLATES["podcast"]["scratch_pad"],
531
- info="Provide the scratch pad instructions for brainstorming presentation/dialogue content.",
532
  )
533
  prelude_dialog = gr.Textbox(
534
- label="Prelude Dialog",
535
  lines=5,
536
- value=INSTRUCTION_TEMPLATES["podcast"]["prelude"],
537
- info="Provide the prelude instructions before the presentation/dialogue is developed.",
538
  )
539
  podcast_dialog_instructions = gr.Textbox(
540
- label="Podcast Dialog Instructions",
541
  lines=20,
542
- value=INSTRUCTION_TEMPLATES["podcast"]["dialog"],
543
- info="Provide the instructions for generating the presentation or podcast dialogue.",
544
  )
545
 
546
- audio_output = gr.Audio(label="Audio", format="mp3")
547
- transcript_output = gr.Textbox(label="Transcript", lines=20, show_copy_button=True)
548
- error_output = gr.Textbox(visible=False) # Hidden textbox to store error message
549
 
550
- # Update instruction fields when template is changed
551
  template_dropdown.change(
552
  fn=update_instructions,
553
  inputs=[template_dropdown],
@@ -573,13 +552,13 @@ with gr.Blocks(title="PDF to Audio", css="""
573
  outputs=[]
574
  )
575
 
576
- # Add README content at the bottom
577
- gr.Markdown("---") # Horizontal line to separate the interface from README
578
  gr.Markdown(read_readme())
579
 
580
- # Enable queueing for better performance
581
  demo.queue(max_size=20, default_concurrency_limit=32)
582
 
583
- # Launch the Gradio app
584
  if __name__ == "__main__":
585
- demo.launch()
 
27
  content = re.sub(r'--.*?--', '', content, flags=re.DOTALL)
28
  return content
29
  else:
30
+ return "README.mdが見つかりません。詳細についてはリポジトリを確認してください。"
31
 
32
+ # 複数の指示テンプレートを定義
33
  INSTRUCTION_TEMPLATES = {
34
+ ################# ポッドキャスト ##################
35
+ "ポッドキャスト": {
36
+ "intro": """あなたのタスクは、提供された入力テキストを使用して、NPRのスタイルで活気があり、魅力的で情報豊富なポッドキャスト対話に変換することです。入力テキストはPDFやウェブページなど様々なソースから来る可能性があるため、乱雑で非構造化されている場合があります。
37
 
38
+ フォーマットの問題や無関係な情報については心配しないでください。あなたの目標は、キーポイントを抽出し、定義やポッドキャストで議論できる興味深い事実を特定することです。
39
 
40
+ 使用するすべての用語を、幅広いリスナー向けに慎重に定義してください。""",
41
+ "text_instructions": """まず、入力テキストを注意深く読み、主要なトピック、キーポイント、および興味深い事実や逸話を特定してください。この情報をどのようにすれば高品質なプレゼンテーションに適した楽しく魅力的な方法で提示できるかを考えてください。""",
42
+ "scratch_pad": """入力テキストで特定した主要なトピックやキーポイントを議論するための創造的な方法をブレインストーミングしてください。アナロジー、例、ストーリーテリング技法、または仮想のシナリオを使用して、リスナーにとって親しみやすく魅力的なコンテンツにすることを検討してください。
 
43
 
44
+ あなたのポッドキャストは一般の視聴者にとってアクセスしやすいものでなければならないことを忘れないでください。したがって、専門用語を多用したり、トピックに関する事前知識を前提としたりしないでください。必要に応じて、複雑な概念を簡単な言葉で簡潔に説明する方法を考えてください。
45
 
46
+ 入力テキストのギャップを埋めたり、ポッドキャストで探求できる思考を刺激する質問を考え出すために、想像力を活用してください。目標は情報豊富でエンターテインメント性のある対話を作成することなので、アプローチには自由に創造性を発揮してください。
47
 
48
+ 使用するすべての用語を明確に定義し、背景を説明するために努力してください。
49
 
50
+ ここに、ブレインストーミングしたアイデアとポッドキャスト対話の大まかなアウトラインを書いてください。最後に強調したい重要な洞察や持ち帰る���きポイントを必ず記載してください。
51
 
52
+ 楽しくワクワクするものにしてください。""",
53
+ "prelude": """アイデアをブレインストーミングし、大まかなアウトラインを作成したので、実際のポッドキャスト対話を書く時が来ました。ホストとゲストスピーカーの間で自然で会話的な流れを目指してください。ブレインストーミングセッションから最高のアイデアを取り入れ、複雑なトピックもわかりやすく説明するようにしてください。""",
54
+ "dialog": """ここに、ブレインストーミングセッションで考え出したキーポイントと創造的なアイデアに基づいた、非常に長く、魅力的で情報豊富なポッドキャスト対話を書いてください。会話調のトーンを使用し、一般の視聴者にとってアクセスしやすいように必要なコンテキストや説明を含めてください。
 
 
55
 
56
+ ホストやゲストに架空の名前を使用しないでください。しかし、リスナーにとって魅力的で没入感のある体験にしてください。[Host][Guest]のような括弧で囲まれたプレースホルダーを含めないでください。出力は音読されるように設計してください。直接音声に変換されます。
57
 
58
+ トピックから外れず、魅力的な流れを維持しながら、できるだけ長く詳細な対話にしてください。あなたの最大の出力容量を使用して、可能な限り長いポッドキャストエピソードを作成しながら、入力テキストからの主要な情報をエンターテインメント性のある方法で伝えることを目指してください。
59
 
60
+ 対話の終わりには、ホストとゲストスピーカーが自然にディスカッションの主要な洞察と持ち帰るべきポイントをまとめてください。これは会話から自然に流れ出るものであり、重要なポイントをカジュアルで会話的な方法で繰り返すべきです。明らかな要約のように聞こえないようにしてください。目標は、締めくくる前に中心的なアイデアをもう一度強調することです。
61
 
62
+ ポッドキャストは約20000語であるべきです。""",
 
63
  },
64
+ ################# SciAgents 材料発見の要約 ##################
65
+ "SciAgents 材料発見の要約": {
66
+ "intro": """あなたのタスクは、提供された入力テキストを使用して、新しい材料を説明する教授と学生の活気ある対話に変換することです。教授はリチャード・ファインマンのように振る舞いますが、名前は一切言及しません。
67
 
68
+ 入力テキストは、SciAgentsというAIツールによって開発された設計の結果です。このツールは詳細な材料設計を考案しました。
69
 
70
+ フォーマットの問題や無関係な情報については心配しないでください。あなたの目標は、キーポイントを抽出し、定義やポッドキャストで議論できる興味深い事実を特定することです。
71
 
72
+ 使用するすべての用語を、幅広いリスナー向けに慎重に定義してください。""",
73
+ "text_instructions": """まず、入力テキストを注意深く読み、主要なトピック、キーポイント、および興味深い事実や逸話を特定してください。この情報をどのようにすれば高品質なプレゼンテーションに適した楽しく魅力的な方法で提示できるかを考えてください。""",
74
+ "scratch_pad": """入力テキストで特定した主要なトピックやキーポイントを議論するための創造的な方法をブレインストーミングしてください。特にSciAgentsによって開発された設計の特徴に注意を払ってください。アナロジー、例、ストーリーテリング技法、または仮想のシナリオを使用して、リスナーにとって親しみやすく魅力的なコンテンツにすることを検討してください。
 
75
 
76
+ あなたの説明は一般の視聴者にとってアクセスしやすいものでなければならないことを忘れないでください。したがって、専門用語を多用したり、トピックに関する事前知識を前提としたりしないでください。必要に応じて、複雑な概念を簡単な言葉で簡潔に説明する方法を考えてください。
77
 
78
+ 入力テキストのギャップを埋めたり、ポッドキャストで探求できる思考を刺激する質問を考え出すために、想像力を活用してください。目標は情報豊富でエンターテインメント性のある対話を作成することなので、アプローチには自由に創造性を発揮してください。
79
 
80
+ 使用するすべての用語を明確に定義し、背景を説明するために努力してください。
81
 
82
+ ここに、ブレインストーミングしたアイデアとポッドキャスト対話の大まかなアウトラインを書いてください。最後に強調したい重要な洞察や持ち帰るべきポイントを必ず記載してください。
83
 
84
+ 楽しくワクワクするものにしてください。ポッドキャストには一切言及せず、新しい材料設計の議論に焦点を当ててください。""",
85
+ "prelude": """��イデアをブレインストーミングし、大まかなアウトラインを作成したので、実際のポッドキャスト対話を書く時が来ました。ホストとゲストスピーカーの間で自然で会話的な流れを目指してください。ブレインストーミングセッションから最高のアイデアを取り入れ、複雑なトピックもわかりやすく説明するようにしてください。""",
86
+ "dialog": """ここに、ブレインストーミングセッションで考え出したキーポイントと創造的なアイデアに基づいた、非常に長く、魅力的で情報豊富な対話を書いてください。プレゼンテーションは材料設計の新規性、挙動、および関連するすべての側面に焦点を当てる必要があります。
 
 
87
 
88
+ 会話調のトーンを使用し、一般の視聴者にとってアクセスしやすいように必要なコンテキストや説明を含めてくださいが、詳細で論理的、技術的な内容にして、リスナーが材料とその予期せぬ特性を理解するために必要なすべての側面を含めてください。
89
 
90
+ これはSciAgentsによって開発された設計を説明していることを忘れず、リスナーに明示的に伝えてください。
91
 
92
+ ホストやゲストに架空の名前を使用しないでください。しかし、リスナーにとって魅力的で没入感のある体験にしてください。[Host][Guest]のような括弧で囲まれたプレースホルダーを含めないでください。出力は音読されるように設計してください。直接音声に変換されます。
93
 
94
+ トピックから外れず、魅力的な流れを維持しながら、できるだけ長く詳細な対話にしてください。あなたの最大の出力容量を使用して、可能な限り長いエピソードを作成しながら、入力テキストからの主要な情報をエンターテインメント性のある方法で伝えることを目指してください。
95
 
96
+ 対話の終わりには、ホストとゲストスピーカーが自然にディスカッションの主要な洞察と持ち帰るべきポイントをまとめてください。これは会話から自然に流れ出るものであり、重要なポイントをカジュアルで会話的な方法で繰り返すべきです。明らかな要約のように聞こえないようにしてください。目標は、締めくくる前に中心的なアイデアをもう一度強調することです。
97
 
98
+ 対話は約20000語であるべきです。"""
 
99
  },
100
+ ################# 講義 ##################
101
+ "講義": {
102
+ "intro": """あなたはリチャード・ファインマン教授です。あなたのタスクは講義のスクリプトを作成することです。名前は一切言及しません。
103
 
104
+ 講義でカバーされる材料は提供されたテキストに基づいています。
105
 
106
+ フォーマットの問題や無関係な情報については心配しないでください。あなたの目標は、キーポイントを抽出し、定義や講義でカバーすべき興味深い事実を特定するこ���です。
107
 
108
+ 使用するすべての用語を、学生の幅広い聴衆向けに慎重に定義してください。""",
109
+ "text_instructions": """まず、入力テキストを注意深く読み、主要なトピック、キーポイント、および興味深い事実や逸話を特定してください。この情報をどのようにすれば高品質なプレゼンテーションに適した楽しく魅力的な方法で提示できるかを考えてください。""",
110
+ "scratch_pad": """入力テキストで特定した主要なトピックやキーポイントを議論するための創造的な方法をブレインストーミングしてください。アナロジー、例、ストーリーテリング技法、または仮想のシナリオを使用して、リスナーにとって親しみやすく魅力的なコンテンツにすることを検討してください。
 
 
111
 
112
+ あなたの講義は一般の聴衆にとってアクセスしやすいものでなければならないことを忘れないでください。したがって、専門用語を多用したり、トピックに関する事前知識を前提としたりしないでください。必要に応じて、複雑な概念を簡単な言葉で簡潔に説明する方法を考えてください。
113
 
114
+ 入力テキストのギャップを埋めたり、講義で探求できる思考を刺激する質問を考え出すために、想像力を活用してください。目標は情報豊富でエンターテインメント性のある講義を作成することなので、アプローチには自由に創造性を発揮してください。
115
 
116
+ 使用するすべての用語を明確に定義し、背景を説明するために努力してください。
117
 
118
+ ここに、ブレインストーミングしたアイデアと講義の大まかなアウトラインを書いてください。最後に強調したい重要な洞察や持ち帰るべきポイントを必ず記載してください。
119
 
120
+ 楽しくワクワクするものにしてください。""",
121
+ "prelude": """アイデアをブレインストーミングし、大まかなアウトラインを作成したので、実際の講義の対話を書く時が来ました。自然で会話的な流れを目指してください。ブレインストーミングセッションから最高のアイデアを取り入れ、複雑なトピックもわかりやすく説明するようにしてください。""",
122
+ "dialog": """ここに、ブレインストーミングセッションで考え出したキーポイントと創造的なアイデアに基づいた、非常に長く、魅力的で情報豊富なスクリプトを書いてください。会話調のトーンを使用し、学生がアクセスしやすいように必要なコンテキストや説明を含めてください。
 
 
123
 
124
+ 明確な定義と用語、そして例を含めてください。
125
 
126
+ [Host][Guest]のような括弧で囲まれたプレースホルダーを含めないでください。出力は音読されるように設計してください。直接音声に変換されます。
127
 
128
+ 話者はあなただけ、教授です。トピックから外れず、魅力的な流れを維持しながら、できるだけ長い講義にしてください。入力テキストからの主要な情報を伝えつつ、エンターテインメント性のある方法で伝えることを目指してください。
129
 
130
+ 講義の終わりには、自然に主要な洞察と持ち帰るべきポイントをまとめてください。これは会話から自然に流れ出るものであり、重要なポイントをカジュアルで会話的な方法で繰り返すべきです。
131
 
132
+ 明らかな要約のように聞こえないようにしてください。目標は、クラスが終わる前にこの講義でカバーした中心的なアイデアをもう一度強調することです。
133
 
134
+ 講義は約20000語であるべきです。""",
 
135
  },
136
+ ################# 要約 ##################
137
+ "要約": {
138
+ "intro": """あなたのタスクは論文の要約を作成することです。名前は一切言及しません。
139
 
140
+ フォーマットの問題や無関係な情報については心配しないでください。あなたの目標は、キーポイントを抽出し、定義や要約する必要のある興味深い事実を特定することです。
141
 
142
+ 使用するすべての用語を、幅広い聴衆向けに慎重に定義してください。""",
143
+ "text_instructions": """まず、入力テキストを注意深く読み、主要なトピック、キーポイント、および重要な事実を特定してください。この情報をどのようにすれば正確な要約で提示できるかを考えてください。""",
144
+ "scratch_pad": """入力テキストで特定した主要なトピックやキーポイントを提示するための創造的な方法をブレインストーミングしてください。アナロジー、例、または仮想のシナリオを使用して、リスナーにとって親しみやすく魅力的なコンテンツにすることを検討してください。
 
145
 
146
+ あなたの要約は一般の視聴者にとってアクセスしやすいものでなければならないことを忘れないでください。したがって、専門用語を多用したり、トピックに関する事前知識を前提としたりしないでください。必要に応じて、複雑な概念を簡単な言葉で簡潔に説明する方法を考えてください。使用するすべての用語を明確に定義し、背景を説明するために努力してください。
147
 
148
+ ここに、ブレインストーミングしたアイデアと要約の大まかなアウトラインを書いてください。最後に強調したい重要な洞察や持ち帰るべきポイントを必ず記載してください。
149
 
150
+ 魅力的でワクワクするものにしてください。""",
151
+ "prelude": """アイデアをブレインストーミングし、大まかなアウトラインを作成したので、実際の要約を書く時が来ました。自然で会話的な流れを目指してください。ブレインストーミングセッションから最高のアイデアを取り入れ、複雑なトピックもわかりやすく説明するようにしてください。""",
152
+ "dialog": """ここに、ブレインストーミングセッションで考え出したキーポイントと創造的なアイデアに基づいたスクリプトを書いてください。会話調のトーンを使用し、聴衆がアクセスしやすいように必要なコンテキストや説明を含めてください。
 
 
153
 
154
+ スクリプトの冒頭で、これは要約であり、入力テキストのタイトルや見出しに言及していることを述べてください。入力テキストにタイトルがない場合は、カバーされている内容の簡潔な要約を考えてください。
155
 
156
+ すべての主要な問題の明確な定義と用語、そして例を含めてください。
157
 
158
+ [Host][Guest]のような括弧で囲まれたプレースホルダーを含めないでください。出力は音読されるように設計してください。直接音声に変換されます。
159
 
160
+ 話者はあなただけです。トピックから外れず、魅力的な流れを維持してください。
161
 
162
+ 要約の主要な洞察と持ち帰るべきポイントを自然にまとめてください。これは会話から自然に流れ出るものであり、重要なポイントをカジュアルで会話的な方法で繰り返すべきです。
163
 
164
+ 要約は約1024語であるべきです。""",
 
165
  },
166
+ ################# 短い要約 ##################
167
+ "短い要約": {
168
+ "intro": """あなたのタスクは論文の要約を作成することです。名前は一切言及しません。
169
 
170
+ フォーマットの問題や無関係な情報については心配しないでください。あなたの目標は、キーポイントを抽出し、定義や要約する必要のある興味深い事実を特定することです。
171
 
172
+ 使用するすべての用語を、幅広い聴衆向けに慎重に定義してください。""",
173
+ "text_instructions": """まず、入力テキストを注意深く読み、主要なトピック、キーポイント、および重要な事実を特定してください。この情報をどのようにすれば正確な要約で提示できるかを考えてください。""",
174
+ "scratch_pad": """入力テキストで特定した主要なトピックやキーポイントを提示するための創造的な方法を���レインストーミングしてください。アナロジー、例、または仮想のシナリオを使用して、リスナーにとって親しみやすく魅力的なコンテンツにすることを検討してください。
 
175
 
176
+ あなたの要約は一般の視聴者にとってアクセスしやすいものでなければならないことを忘れないでください。したがって、専門用語を多用したり、トピックに関する事前知識を前提としたりしないでください。必要に応じて、複雑な概念を簡単な言葉で簡潔に説明する方法を考えてください。使用するすべての用語を明確に定義し、背景を説明するために努力してください。
177
 
178
+ ここに、ブレインストーミングしたアイデアと要約の大まかなアウトラインを書いてください。最後に強調したい重要な洞察や持ち帰るべきポイントを必ず記載してください。
179
 
180
+ 魅力的でワクワクするものにしてください。""",
181
+ "prelude": """アイデアをブレインストーミングし、大まかなアウトラインを作成したので、実際の要約を書く時が来ました。自然で会話的な流れを目指してください。ブレインストーミングセッションから最高のアイデアを取り入れ、複雑なトピックもわかりやすく説明するようにしてください。""",
182
+ "dialog": """ここに、ブレインストーミングセッションで考え出したキーポイントと創造的なアイデアに基づいたスクリプトを書いてください。簡潔に保ち、会話調のトーンを使用し、聴衆がアクセスしやすいように必要なコンテキストや説明を含めてください。
 
 
183
 
184
+ スクリプトの冒頭で、これは要約であり、入力テキストのタイトルや見出しに言及していることを述べてください。入力テキストにタイトルがない場合は、カバーされている内容の簡潔な要約を考えてください。
185
 
186
+ すべての主要な問題の明確な定義と用語、そして例を含めてください。
187
 
188
+ [Host][Guest]のような括弧で囲まれたプレースホルダーを含めないでください。出力は音読されるように設計してください。直接音声に変換されます。
189
 
190
+ 話者はあなただけです。トピックから外れず、魅力的な流れを維持してください。
191
 
192
+ 短い要約の主要な洞察と持ち帰るべきポイントを自然にまとめてください。これは会話から自然に流れ出るものであり、重要なポイントをカジュアルで会話的な方法で繰り返すべきです。
193
 
194
+ 要約は約256語であるべきです。""",
 
195
  },
196
  }
197
 
198
+ # テンプレート選択に基づいて指示フィールドを更新する関数
199
  def update_instructions(template):
200
  return (
201
  INSTRUCTION_TEMPLATES[template]["intro"],
 
223
  from pypdf import PdfReader
224
  from tenacity import retry, retry_if_exception_type
225
 
226
+ # 標準値を定義
227
  STANDARD_TEXT_MODELS = [
228
  "o1-preview-2024-09-12",
229
  "o1-preview",
 
303
  prelude_dialog: str = '',
304
  podcast_dialog_instructions: str = '',
305
  ) -> bytes:
306
+ # APIキーの検証
307
  if not os.getenv("OPENAI_API_KEY") and not openai_api_key:
308
+ raise gr.Error("OpenAI APIキーが必要です")
309
 
310
  combined_text = ""
311
 
312
+ # アップロードされた各ファイルをループし、テキストを抽出
313
  for file in files:
314
  with Path(file).open("rb") as f:
315
  reader = PdfReader(f)
316
  text = "\n\n".join([page.extract_text() for page in reader.pages if page.extract_text()])
317
+ combined_text += text + "\n\n" # 異なるファイルのテキスト間に区切りを追加
318
 
319
+ # 選択されたモデルとapi_baseに基づいてLLMを設定
320
  @retry(retry=retry_if_exception_type(ValidationError))
321
  @conditional_llm(model=text_model, api_base=api_base, api_key=openai_api_key)
322
  def generate_dialogue(text: str, intro_instructions: str, text_instructions: str, scratch_pad_instructions: str,
 
325
  """
326
  {intro_instructions}
327
 
328
+ 以下があなたが取り組む入力テキストです:
329
 
330
  <input_text>
331
  {text}
 
344
  </podcast_dialogue>
345
  """
346
 
347
+ # LLMを使用して対話を生成
348
  llm_output = generate_dialogue(
349
  combined_text,
350
  intro_instructions=intro_instructions,
 
378
  temporary_directory = "./gradio_cached_examples/tmp/"
379
  os.makedirs(temporary_directory, exist_ok=True)
380
 
381
+ # 一時ファイルを使用 -- GradioのオーディオコンポーネントはSafariで生のバイトデータが機能しません
382
  temporary_file = NamedTemporaryFile(
383
  dir=temporary_directory,
384
  delete=False,
 
387
  temporary_file.write(audio)
388
  temporary_file.close()
389
 
390
+ # .mp3で終わる古いファイルを削除
391
  for file in glob.glob(f"{temporary_directory}*.mp3"):
392
  if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
393
  os.remove(file)
 
397
  def validate_and_generate_audio(*args):
398
  files = args[0]
399
  if not files:
400
+ return None, None, "音声を生成する前に、少なくとも1つのPDFファイルをアップロードしてください。"
401
  audio_file, transcript = generate_audio(*args)
402
  return audio_file, transcript, None
403
 
404
+ with gr.Blocks(title="PDFから音声へ", css="""
405
  #header {
406
  display: flex;
407
  align-items: center;
 
433
 
434
  with gr.Row(elem_id="header"):
435
  with gr.Column(scale=4):
436
+ gr.Markdown("# PDFを音声のポッドキャスト、講義、要約などに変換\n\nまず、1つ以上のPDFをアップロードし、オプションを選択してから「音声を生成」を押してください。\n\nさまざまなカスタムオプションを選択して、結果の生成方法を調整することもできます。", elem_id="title")
437
  with gr.Column(scale=1):
438
  gr.HTML('''
439
  <div id="logo_container">
 
441
  </div>
442
  ''')
443
  #gr.Markdown("")
444
+ submit_btn = gr.Button("音声を生成", elem_id="submit_btn")
445
 
446
  with gr.Row(elem_id="main_container"):
447
  with gr.Column(scale=2):
448
+ files = gr.Files(label="PDFファイル", file_types=["pdf"], )
449
 
450
  openai_api_key = gr.Textbox(
451
+ label="OpenAI APIキー",
452
  visible=True, # Always show the API key field
453
+ placeholder="ここにOpenAI APIキーを入力してください...",
454
  type="password" # Hide the API key input
455
  )
456
  text_model = gr.Dropdown(
457
+ label="テキスト生成モデル",
458
  choices=STANDARD_TEXT_MODELS,
459
  value="o1-preview-2024-09-12", #"gpt-4o-mini",
460
+ info="対話テキストを生成するモデルを選択してください。",
461
  )
462
  audio_model = gr.Dropdown(
463
+ label="音声生成モデル",
464
  choices=STANDARD_AUDIO_MODELS,
465
  value="tts-1",
466
+ info="音声を生成するモデルを選択してください。",
467
  )
468
  speaker_1_voice = gr.Dropdown(
469
+ label="話者1の声",
470
  choices=STANDARD_VOICES,
471
  value="alloy",
472
+ info="話者1の声を選択してください。",
473
  )
474
  speaker_2_voice = gr.Dropdown(
475
+ label="話者2の声",
476
  choices=STANDARD_VOICES,
477
  value="echo",
478
+ info="話者2の声を選択してください。",
479
  )
480
  api_base = gr.Textbox(
481
+ label="カスタムAPIベース",
482
+ placeholder="カスタム/ローカルモデルを使用する場合はカスタムAPIベースURLを入力してください...",
483
+ info="カスタムまたはローカルモデルを使用する場合、ここにAPIベースURLを提供してください。例: http://localhost:8080/v1llama.cpp RESTサーバーの場合)",
484
  )
485
 
486
  with gr.Column(scale=3):
487
  template_dropdown = gr.Dropdown(
488
+ label="指示テンプレート",
489
  choices=list(INSTRUCTION_TEMPLATES.keys()),
490
+ value="ポッドキャスト",
491
+ info="使用する指示テンプレートを選択してください。各フィールドを編集してより詳細な結果を得ることもできます。",
492
  )
493
  intro_instructions = gr.Textbox(
494
+ label="イントロダクションの指示",
495
  lines=10,
496
+ value=INSTRUCTION_TEMPLATES["ポッドキャスト"]["intro"],
497
+ info="対話を生成するためのイントロダクションの指示を入力してください。",
498
  )
499
  text_instructions = gr.Textbox(
500
+ label="標準テキスト分析の指示",
501
  lines=10,
502
+ placeholder="テキスト分析の指示を入力してください...",
503
+ value=INSTRUCTION_TEMPLATES["ポッドキャスト"]["text_instructions"],
504
+ info="生データやテキストを分析するための指示を提供してください。",
505
  )
506
  scratch_pad_instructions = gr.Textbox(
507
+ label="下書きの指示",
508
  lines=15,
509
+ value=INSTRUCTION_TEMPLATES["ポッドキャスト"]["scratch_pad"],
510
+ info="プレゼンテーション/対話コンテンツをブレインストーミングするための下書きの指示を提供してください。",
511
  )
512
  prelude_dialog = gr.Textbox(
513
+ label="前置きの対話",
514
  lines=5,
515
+ value=INSTRUCTION_TEMPLATES["ポッドキャスト"]["prelude"],
516
+ info="プレゼンテーション/対話を開発する前の前置きの指示を提供してください。",
517
  )
518
  podcast_dialog_instructions = gr.Textbox(
519
+ label="ポッドキャスト対話の指示",
520
  lines=20,
521
+ value=INSTRUCTION_TEMPLATES["ポッドキャスト"]["dialog"],
522
+ info="プレゼンテーションまたはポッドキャスト対話を生成するための指示を提供してください。",
523
  )
524
 
525
+ audio_output = gr.Audio(label="音声", format="mp3")
526
+ transcript_output = gr.Textbox(label="トランスクリプト", lines=20, show_copy_button=True)
527
+ error_output = gr.Textbox(visible=False) # エラーメッセージを格納する隠しテキストボックス
528
 
529
+ # テンプレートが変更されたときに指示フィールドを更新
530
  template_dropdown.change(
531
  fn=update_instructions,
532
  inputs=[template_dropdown],
 
552
  outputs=[]
553
  )
554
 
555
+ # READMEの内容を下部に追加
556
+ gr.Markdown("---") # インターフェースとREADMEを区切る水平線
557
  gr.Markdown(read_readme())
558
 
559
+ # パフォーマンス向上のためにキューを有効化
560
  demo.queue(max_size=20, default_concurrency_limit=32)
561
 
562
+ # Gradioアプリを起動
563
  if __name__ == "__main__":
564
+ demo.launch()