-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
290 lines (235 loc) · 9.21 KB
/
Copy pathmain.py
File metadata and controls
290 lines (235 loc) · 9.21 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
import os
from datetime import timedelta
import yaml
import markdown
from jinja2 import Environment, FileSystemLoader
from bs4 import BeautifulSoup
from collections import defaultdict
# --- CSS STYLE ---
DEFAULT_STYLE = {
"a": {"text-decoration": "none"},
"p": {"text-align": "justify"}
}
SCHEDULE_FIELDS_TO_IMPORT = ["speaker", "description", "bio", "speaker_size", "slides", "video"]
def load_yaml(path: str):
if not os.path.exists(path):
raise FileNotFoundError(f"{path} not found")
with open(path, encoding="utf-8", mode="r") as f:
return yaml.safe_load(f) or []
def serialize_style(style: dict[str, str]) -> str:
return "; ".join(f"{k}: {v}" for k, v in style.items())
def process_markdown(
text: str,
strip_top_level_p: bool = False,
css_customizations: dict[str, dict[str, str]] = None
) -> str:
if css_customizations is None:
css_customizations = {}
if not text:
return ""
soup = BeautifulSoup(markdown.markdown(text.strip()), features="html.parser")
if strip_top_level_p:
for p in soup.find_all("p", recursive=False):
p.unwrap()
if css_customizations:
for tag, style in css_customizations.items():
for element in soup.find_all(tag, recursive=True):
element["style"] = "; ".join(
s for s in (element.get("style", "").rstrip(";"), serialize_style(style)) if s)
return soup.decode_contents().strip()
def render_markdown(text: str) -> str:
return process_markdown(text=text, css_customizations=DEFAULT_STYLE).strip()
def render_template(context: dict, template_name: str, output_path: str, template_dir: str = "templates"):
env = Environment(loader=FileSystemLoader(template_dir), autoescape=True)
rendered_html = env.get_template(template_name).render(**context)
os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write(rendered_html)
print(f"Success! Generated {output_path}.")
def generate_data(
name: str,
input_path: str,
output_name: str,
template_name: str,
assets_path: str,
sorter=None,
formatter=None,
output_dir: str = "output",
template_dir: str = "templates",
):
data = load_yaml(input_path)
assets = load_yaml(assets_path)
if sorter:
sorter(data)
if formatter:
formatter(data)
context = {
name: data,
"github_icon": assets.get("github_icon_url", ""),
"linkedin_icon": assets.get("linkedin_icon_url", ""),
}
render_template(context, template_name, os.path.join(output_dir, output_name), template_dir)
def sort_speakers_inplace(data):
data.sort(
key=lambda s: (
s.get("last_name", "").strip().lower(),
s.get("name", "").strip().lower(),
)
)
def format_speakers_inplace(data):
for speaker in data:
speaker["company_html"] = process_markdown(
text=speaker.get("company", ""),
strip_top_level_p=True,
css_customizations=DEFAULT_STYLE
)
speaker["bio_html"] = process_markdown(
text=speaker.get("bio", ""),
css_customizations=DEFAULT_STYLE
)
for talk in speaker.get("talks", []):
talk["description_html"] = process_markdown(
text=talk.get("description", ""),
css_customizations=DEFAULT_STYLE
)
def format_workshops_inplace(data):
for speaker in data:
for workshop in speaker.get("workshops", []):
workshop["title_html"] = process_markdown(
text=workshop.get("title", ""),
strip_top_level_p=True,
css_customizations=DEFAULT_STYLE
)
workshop["description_html"] = process_markdown(
text=workshop.get("description", ""),
css_customizations=DEFAULT_STYLE
)
def cross_reference_talks(talks_data_path: str):
index = defaultdict(lambda: {"speakers": [], "biographies": [], "description": "", "slides": "", "video": ""})
for speaker in load_yaml(talks_data_path):
full_name = f"{speaker['name']} {speaker['last_name']}"
biography = render_markdown(speaker["bio"])
for talk in speaker.get("talks", []):
title = talk["title"]
entry = index[title]
entry["speakers"].append(full_name)
entry["biographies"].append(biography)
if not entry["description"]:
entry["description"] = render_markdown(talk["description"])
if talk.get("slides"):
entry["slides"] = talk["slides"]
if talk.get("video"):
entry["video"] = talk["video"]
return {
title: {
"speaker": ", ".join(data["speakers"]),
"speaker_size": len(data["speakers"]),
"description": data["description"],
"bio": "\n".join(data["biographies"]),
"slides": data["slides"],
"video": data["video"]
}
for title, data in index.items()
}
def cross_reference_workshops(workshops_data_path: str):
raw_index = defaultdict(lambda: {"names": [], "description": ""})
for speaker in load_yaml(workshops_data_path):
for workshop in speaker.get("workshops", []):
title = workshop["title"]
entry = raw_index[title]
entry["names"].append(speaker["name"])
if not entry["description"]:
entry["description"] = render_markdown(workshop["description"])
return {
title: {
"speaker": ", ".join(data["names"]),
"speaker_size": len(data["names"]),
"description": data["description"],
}
for title, data in raw_index.items()
}
def human_duration(minutes: int) -> str:
minutes = int(minutes)
hours, mins = divmod(minutes, 60)
if hours == 0:
return f"{mins} min"
if mins == 0:
return f"{hours} hour"
return f"{hours} hr, {mins} min"
def process_timestamps_inplace(schedule_data):
for talk in schedule_data:
talk['day_sort_key'] = talk['start'].strftime('%Y-%m-%d') # Jinja Sorting Key
talk['day_label'] = talk['start'].strftime('%A, %B %d') # e.g. Monday, January 01
talk['end'] = talk['start'] + timedelta(minutes=talk['duration'])
talk['duration'] = human_duration(talk['duration'])
schedule_data.sort(key=lambda x: x['start'])
for current, next_entry in zip(schedule_data, schedule_data[1:]):
if next_entry['start'] < current['end']:
print(
"Warning: overlapping talks:",
f"'{current['title']}' "
f"({current['start']} – {current['end']}) overlaps with "
f"'{next_entry['title']}' "
f"({next_entry['start']} – {next_entry['end']})"
)
def generate_schedule(
name: str,
input_path: str,
cross_reference_map: dict,
output_name: str,
template_name: str,
output_dir: str = "output",
template_dir: str = "templates",
):
schedule_data = load_yaml(input_path)
index = cross_reference_talks(cross_reference_map['speakers']) | cross_reference_workshops(cross_reference_map['workshops'])
process_timestamps_inplace(schedule_data)
for entry in schedule_data:
title = entry["title"]
if entry.get("description"):
entry["description"] = render_markdown(entry["description"])
extra_data = index.get(title)
if not extra_data:
if entry["type"] in ["talk", "workshop"]:
print(f"Warning: Could not cross-reference {entry['type']} title: {title}")
continue
for field in SCHEDULE_FIELDS_TO_IMPORT:
index_value = extra_data.get(field)
if index_value:
if entry.get(field):
print(f"Warning: Schedule for '{title}' already has a {field}. Ignoring index value.")
else:
entry[field] = index_value
render_template({name: schedule_data}, template_name, os.path.join(output_dir, output_name), template_dir)
if __name__ == "__main__":
data_assets_path = "data/assets.yaml"
schedule_path = "data/2026/schedule.yaml"
speakers_path = "data/2026/speakers.yaml"
workshops_path = "data/2026/workshops.yaml"
# Speakers
generate_data(
name="speakers",
input_path=speakers_path,
output_name="speakers.html",
template_name="speakers.html.j2",
assets_path=data_assets_path,
sorter=sort_speakers_inplace,
formatter=format_speakers_inplace,
)
# Workshops
generate_data(
name="speakers",
input_path=workshops_path,
output_name="workshops.html",
template_name="workshops.html.j2",
assets_path=data_assets_path,
formatter=format_workshops_inplace
)
# Schedule
generate_schedule(
name="talks",
input_path=schedule_path,
cross_reference_map={'speakers': speakers_path, 'workshops': workshops_path},
output_name="schedule.html",
template_name="schedule.html.j2"
)