Repository navigation
Expand file tree
/
Copy pathworkflow.py
More file actions
302 lines (265 loc) 路 11 KB
/
Copy pathworkflow.py
File metadata and controls
302 lines (265 loc) 路 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import os
import subprocess
import pickle
from typing import Any, List
from llama_parse import LlamaParse
from llama_index.core import SimpleDirectoryReader
from llama_index.core.llms.llm import LLM
from llama_index.core.workflow import (
step,
Context,
Workflow,
Event,
StartEvent,
StopEvent,
)
from llama_index.core.workflow.retry_policy import ConstantDelayRetryPolicy
from models import PresentationStructure, StructureFeedback, Slide, SlideInfo
from agents.structure_creater import create_presentation_structure
from agents.structure_validator import validate_presentation_structure
from agents.structure_updater import update_presentation_structure
from agents.slide_maker import compose_slide
from agents.structure_creater_from_data import create_presentation_structure_from_data
from utils import get_presentation_config, get_safe_foldername, sanitize_markdown
class DataFolderFound(Event):
pass
class TopicFound(Event):
pass
class StructureRequestReceived(Event):
topic: str
class ValidateStructureRequestReceived(Event):
structure: PresentationStructure
class UpdateStructureRequestReceived(Event):
structure: PresentationStructure
feedback: StructureFeedback
class StructureFinalized(Event):
structure: PresentationStructure
class ComposeSlideRequestReceived(Event):
slide_index: int
slide_info: SlideInfo
class SlideCreated(Event):
slide_index: int
content: str
narration: str
class PresenterWorkflow(Workflow):
def __init__(
self,
*args: Any,
llm: LLM,
**kwargs: Any,
) -> None:
super().__init__(*args, **kwargs)
self.llm = llm
@step
async def start(self, ctx: Context, ev: StartEvent) -> TopicFound | DataFolderFound:
data_folder = os.path.join("data")
# check if data folder exists and is not empty
if os.path.exists(data_folder) and os.listdir(data_folder):
await ctx.set("data_folder", data_folder)
return DataFolderFound
topic = ev.query
await ctx.set("topic", topic)
return TopicFound
@step
async def ingest_data_and_find_topic(
self, ctx: Context, ev: DataFolderFound
) -> TopicFound:
data_folder = os.path.join("data")
# read all files in the data folder
parser = LlamaParse(result_type="markdown")
file_extractor = {".pdf": parser}
documents = SimpleDirectoryReader(
file_extractor=file_extractor, input_dir=data_folder
).load_data()
presentation_structure_with_title = create_presentation_structure_from_data(
documents, self.llm
)
await ctx.set("topic", presentation_structure_with_title.title)
structure = PresentationStructure(
slides=presentation_structure_with_title.slides
)
structure_file = os.path.join(
await ctx.get("presentation_folder"), "structure.pkl"
)
with open(structure_file, "wb") as f:
pickle.dump(structure, f)
return StructureFinalized(structure=structure)
@step
async def prepare_presentation_folder(
self, ctx: Context, ev: TopicFound
) -> StructureRequestReceived:
topic = await ctx.get("topic")
presentation_folder = os.path.join("presentations", get_safe_foldername(topic))
await ctx.set("presentation_folder", presentation_folder)
if not os.path.exists(presentation_folder):
os.makedirs(presentation_folder)
structure_file = os.path.join(presentation_folder, "structure.pkl")
if os.path.exists(structure_file):
print(
f"\n> Presentation structure already exists for topic: {topic}."
" Skipping structure creation and using the existing structure.\n"
)
with open(structure_file, "rb") as f:
structure = pickle.load(f)
return StructureFinalized(structure=structure)
return StructureRequestReceived(topic=topic)
@step
async def create_presentation_structure(
self, ctx: Context, ev: StructureRequestReceived
) -> ValidateStructureRequestReceived:
topic = ev.topic
initial_structure = create_presentation_structure(topic, self.llm)
return ValidateStructureRequestReceived(structure=initial_structure)
@step
async def validate_presentation_structure(
self, ctx: Context, ev: ValidateStructureRequestReceived
) -> UpdateStructureRequestReceived | StructureFinalized:
structure = ev.structure
topic = await ctx.get("topic")
feedback = validate_presentation_structure(topic, structure, self.llm)
if feedback.is_perfect:
return StructureFinalized(structure=structure)
return UpdateStructureRequestReceived(structure=structure, feedback=feedback)
@step
async def update_presentation_structure(
self, ctx: Context, ev: UpdateStructureRequestReceived
) -> StructureFinalized:
structure = ev.structure
feedback = ev.feedback
topic = await ctx.get("topic")
updated_structure = update_presentation_structure(
topic, structure, feedback, self.llm
)
# pickle the structure in the presentation folder
structure_file = os.path.join(
await ctx.get("presentation_folder"), "structure.pkl"
)
with open(structure_file, "wb") as f:
pickle.dump(updated_structure, f)
return StructureFinalized(structure=updated_structure)
@step
async def create_slides(
self, ctx: Context, ev: StructureFinalized
) -> ComposeSlideRequestReceived:
structure = ev.structure
await ctx.set("structure", structure)
await ctx.set("num_slides", len(structure.slides))
for slide_index, slide in enumerate(structure.slides):
ctx.send_event(
ComposeSlideRequestReceived(slide_index=slide_index, slide_info=slide)
)
@step(num_workers=6, retry_policy=ConstantDelayRetryPolicy())
async def compose_one_slide(
self, ctx: Context, ev: ComposeSlideRequestReceived
) -> SlideCreated:
slide_index = ev.slide_index
slide_info = ev.slide_info
print(f"\n> Creating slide: {slide_info.title}...\n")
presentation_folder = await ctx.get("presentation_folder")
slide_folder = os.path.join(presentation_folder, f"slide_{slide_index}")
if not os.path.exists(slide_folder):
os.makedirs(slide_folder)
content_file = os.path.join(slide_folder, "content.md")
narration_file = os.path.join(slide_folder, "narration.txt")
if os.path.exists(content_file) and os.path.exists(narration_file):
with open(content_file, "r") as f:
content = f.read()
with open(narration_file, "r") as f:
narration = f.read()
return SlideCreated(
slide_index=slide_index, content=content, narration=narration
)
topic = await ctx.get("topic")
structure = await ctx.get("structure")
slides_info: List[SlideInfo] = structure.slides
num_slides = await ctx.get("num_slides")
prev_next_info = ""
if slide_index > 0:
prev_next_info += f'The previous slide is "{slides_info[slide_index-1].title}"({slides_info[slide_index-1].atomic_core_idea}). '
if slide_index < num_slides - 1:
prev_next_info += f'The next slide is "{slides_info[slide_index+1].title}"({slides_info[slide_index+1].atomic_core_idea}). '
slide = await compose_slide(topic, slide_info, prev_next_info, self.llm)
content = slide.content
narration = slide.narration
with open(content_file, "w") as f:
f.write(content)
with open(narration_file, "w") as f:
f.write(narration)
return SlideCreated(
slide_index=slide_index, content=content, narration=narration
)
@step
async def combine_slides(self, ctx: Context, ev: SlideCreated) -> StopEvent:
num_slides = await ctx.get("num_slides")
presentation_folder = await ctx.get("presentation_folder")
events = ctx.collect_events(ev, [SlideCreated] * num_slides)
if events is None:
return None
slide_created_events: List[SlideCreated] = events
slides_dict = {
ev.slide_index: f"{ev.content}\n\nNote:\n{ev.narration}\n"
for ev in slide_created_events
}
slides_list = [slides_dict[i] for i in range(num_slides)]
slides_separator = "\n\n[comment]: # (!!!)\n\n"
full_presentation_template = sanitize_markdown(
slides_separator.join(slides_list)
)
full_presentation_template = (
get_presentation_config() + full_presentation_template
)
template_file = os.path.join(presentation_folder, "presentation_template.md")
with open(template_file, "w") as f:
f.write(full_presentation_template)
# using mermaid-cli to render mermaid diagrams
print("\n> Rendering diagrams...\n")
presentation_file = os.path.join(presentation_folder, "presentation.md")
subprocess.run(
["mmdc", "-i", template_file, "-o", presentation_file, "-e", "png"]
)
with open(presentation_file, "r") as f:
presentation_content = f.read()
with open(presentation_file, "w") as f:
f.write(sanitize_markdown(presentation_content))
media_dir = os.path.join(presentation_folder, "media")
if not os.path.exists(media_dir):
os.makedirs(media_dir)
# copy all png files from presentation folder to media folder
for filename in os.listdir(presentation_folder):
if filename.endswith(".png"):
os.rename(
os.path.join(presentation_folder, filename),
os.path.join(media_dir, filename),
)
# using mdslides to render presentation
print("\n> Rendering presentation...\n")
output_dir = os.path.join(presentation_folder, "output")
html_file = os.path.join(output_dir, "index.html")
pdf_file = os.path.join(presentation_folder, "presentation.pdf")
subprocess.run(
[
"mdslides",
presentation_file,
"--include",
media_dir,
"--output_dir",
output_dir,
]
)
print(
f'\n> Presentation rendered. Run "open {html_file}" to view the presentation.\n'
)
print("\n> Exporting presentation to PDF...\n")
subprocess.run(
[
"decktape",
"--headless=true",
"--screenshots",
"--screenshots-directory=.",
"reveal",
html_file,
pdf_file,
]
)
print(f'\n> Exported presentation to PDF. Open it using "open {pdf_file}"\n')
return StopEvent(result=presentation_folder)