-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_people.py
More file actions
559 lines (433 loc) · 17 KB
/
build_people.py
File metadata and controls
559 lines (433 loc) · 17 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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#!/usr/bin/env python3
"""Build people.html from spreadsheet data.
Reads data from data/people.xlsx and generates people.html
using the template in templates/people.html.
"""
import re
from pathlib import Path
from typing import List, Dict, Any, Optional
import openpyxl
from utils import inject_content
from citation_utils import resolve_link
def parse_cv_undergrad_order(cv_path: Path) -> List[str]:
"""Parse the CV to get the order of undergraduate advisees.
The CV lists undergrads in reverse chronological order by join date
(most recent joiner first). This order is authoritative.
Args:
cv_path: Path to JRM_CV.tex
Returns:
List of names in CV order (first = highest priority)
"""
if not cv_path.exists():
return []
content = cv_path.read_text(encoding="utf-8")
# Find the Undergraduate Advisees section
match = re.search(
r"\\textit\{Undergraduate Advisees\}.*?\\begin\{etaremune\}(.*?)\\end\{etaremune\}",
content,
re.DOTALL
)
if not match:
return []
section = match.group(1)
# Extract names from \item entries
# Format: \item Name[*]? (years)
names = []
for item_match in re.finditer(r"\\item\s+(.+?)\s*\(", section):
name = item_match.group(1).strip()
# Remove asterisk (senior thesis marker)
name = name.rstrip("*").strip()
names.append(name)
return names
def parse_links_field(links_str: str) -> str:
"""Parse links field into HTML.
Format: 'Label:URL, "Quoted Label":URL, ...'
- Comma-separated pairs of label:url
- Labels can be quoted for labels with spaces
- URLs are resolved (local paths converted to GitHub URLs)
Args:
links_str: Links string in the format 'Label:URL, "Label":URL'
Returns:
HTML string like '[<a href="...">Label</a>] [<a href="...">Label</a>]'
"""
if not links_str:
return ""
links = []
# Parse the links string - handle both quoted and unquoted labels
# Pattern: either "quoted label":url or label:url, separated by commas
remaining = links_str.strip()
while remaining:
remaining = remaining.lstrip(" ,")
if not remaining:
break
if remaining.startswith('"'):
# Quoted label
end_quote = remaining.find('"', 1)
if end_quote == -1:
break
label = remaining[1:end_quote]
rest = remaining[end_quote + 1 :].lstrip()
if rest.startswith(":"):
rest = rest[1:]
# Find end of URL (next comma or end of string)
comma_pos = rest.find(",")
if comma_pos == -1:
url = rest.strip()
remaining = ""
else:
url = rest[:comma_pos].strip()
remaining = rest[comma_pos + 1 :]
links.append((label, url))
else:
# Unquoted label - split on first colon
colon_pos = remaining.find(":")
if colon_pos == -1:
break
label = remaining[:colon_pos].strip()
rest = remaining[colon_pos + 1 :]
# Find end of URL - but URL may contain colons (https://)
# So find the next comma that's not part of a URL
comma_pos = rest.find(",")
if comma_pos == -1:
url = rest.strip()
remaining = ""
else:
url = rest[:comma_pos].strip()
remaining = rest[comma_pos + 1 :]
links.append((label, url))
# Build HTML
parts = []
for label, url in links:
if url:
resolved_url = resolve_link(url, base_path="documents")
parts.append(f'[<a href="{resolved_url}" target="_blank">{label}</a>]')
return " ".join(parts)
def load_people(xlsx_path: Path) -> Dict[str, List[Dict[str, Any]]]:
"""Load all people data from Excel spreadsheet.
Args:
xlsx_path: Path to the people.xlsx file
Returns:
Dictionary with keys for each section (director, members, etc.)
Each value is a list of person dictionaries.
"""
wb = openpyxl.load_workbook(xlsx_path, read_only=True, data_only=True)
data = {}
for sheet_name in wb.sheetnames:
sheet = wb[sheet_name]
# Get headers from first row
headers = [cell.value for cell in sheet[1]]
rows = []
for row in sheet.iter_rows(min_row=2, values_only=True):
# Skip empty rows
if not any(cell is not None for cell in row):
continue
row_dict = {}
for header, value in zip(headers, row):
if value is None:
row_dict[header] = ""
else:
row_dict[header] = value
rows.append(row_dict)
data[sheet_name] = rows
wb.close()
return data
def generate_director_content(director: Dict[str, Any]) -> str:
"""Generate HTML for the lab director section.
Args:
director: Dictionary with director data
Returns:
HTML string for director section
"""
image = director.get("image", "")
name = director.get("name", "")
name_url = director.get("name_url", "")
role = director.get("role", "")
bio = director.get("bio", "")
links_field = director.get("links_html", "")
# Build image path (use placeholder if not specified)
image_src = f"images/people/{image}" if image else "images/people/placeholder.png"
# Build name with optional link
if name_url:
name_display = f'<a href="{name_url}" target="_blank">{name}</a>'
else:
name_display = name
# Build role display
role_display = f" | {role}" if role else ""
# Parse links field into HTML
links_html = parse_links_field(links_field)
links_p = f"\n <p>{links_html}</p>" if links_html else ""
html = f''' <div class="two-column lab-director">
<figure>
<img src="{image_src}" alt="{name}">
</figure>
<div>
<h3>{name_display}{role_display}</h3>
<p>{bio}</p>{links_p}
</div>
</div>'''
return html
def generate_member_card(member: Dict[str, Any]) -> str:
"""Generate HTML for a single member card.
Args:
member: Dictionary with member data
Returns:
HTML string for the member card
"""
image = member.get("image", "")
name = member.get("name", "")
name_url = member.get("name_url", "")
role = member.get("role", "")
bio = member.get("bio", "")
# Build image path (use placeholder if not specified)
image_src = f"images/people/{image}" if image else "images/people/placeholder.png"
# Build name with optional link
if name_url:
name_display = f'<a href="{name_url}" target="_blank">{name}</a>'
else:
name_display = name
# Build role display
role_display = f" | {role}" if role else ""
html = f''' <div class="person-card">
<img src="{image_src}" alt="{name}">
<h3>{name_display}{role_display}</h3>
<p>{bio}</p>
</div>'''
return html
def generate_members_content(members: List[Dict[str, Any]]) -> str:
"""Generate HTML content for all active lab members.
Members are arranged in a grid of 3 per row.
Args:
members: List of member dictionaries
Returns:
HTML string with all member cards organized in grids
"""
if not members:
return ""
cards = [generate_member_card(m) for m in members]
# Group cards into rows of 3
grids = []
for i in range(0, len(cards), 3):
row_cards = cards[i : i + 3]
grid_html = ' <div class="people-grid">\n'
grid_html += "\n".join(row_cards)
grid_html += "\n </div>"
grids.append(grid_html)
return "\n\n".join(grids)
def format_position_display(current_position: str, current_position_url: str) -> str:
"""Format the current position text with optional hyperlink.
Handles patterns like "now at X", "now a X", "then a X", "then at X".
If the position already contains such a pattern, uses it as-is and
hyperlinks just the relevant part. Otherwise prepends "now at".
Args:
current_position: The position text (may include prefix like "now at")
current_position_url: Optional URL to link
Returns:
Formatted position display string
"""
if not current_position:
return ""
# Patterns that indicate the text already has a prefix
# Match: "now at ", "now a ", "then at ", "then a "
prefix_pattern = re.match(r'^(now at |now a |then at |then a )', current_position, re.IGNORECASE)
if prefix_pattern:
# Text already has a prefix - extract prefix and the rest
prefix = prefix_pattern.group(1)
rest = current_position[len(prefix):]
if current_position_url:
# Hyperlink just the part after the prefix
return f'{prefix}<a href="{current_position_url}" target="_blank">{rest}</a>'
else:
return current_position
else:
# No prefix - add "now at"
if current_position_url:
return f'now at <a href="{current_position_url}" target="_blank">{current_position}</a>'
else:
return f"now at {current_position}"
def generate_alumni_entry(alum: Dict[str, Any]) -> str:
"""Generate HTML for a single alumni entry.
Args:
alum: Dictionary with alumni data (name, name_url, years, current_position, current_position_url)
Returns:
HTML string for the alumni entry
"""
name = alum.get("name", "")
name_url = alum.get("name_url", "")
years = alum.get("years", "")
current_position = alum.get("current_position", "")
current_position_url = alum.get("current_position_url", "")
# Build name with optional link
if name_url:
name_display = f'<a href="{name_url}" target="_blank">{name}</a>'
else:
name_display = name
# Build position display with optional link
position_display = format_position_display(current_position, current_position_url)
# Build parenthetical info
paren_parts = []
if years:
paren_parts.append(years)
if position_display:
paren_parts.append(position_display)
paren_display = f" ({'; '.join(paren_parts)})" if paren_parts else ""
return f"{name_display}{paren_display}"
def _parse_start_year(years_str: str) -> int:
"""Extract start year from a years string like '2019-2021' or '2021'."""
if not years_str:
return 0
return int(str(years_str).split('-')[0].strip())
def generate_alumni_list_content(alumni: List[Dict[str, Any]]) -> str:
"""Generate HTML content for an alumni list (postdocs, grads, managers).
Alumni are sorted in reverse chronological order by start year.
Args:
alumni: List of alumni dictionaries
Returns:
HTML string with alumni entries separated by <br>
"""
if not alumni:
return ""
sorted_alumni = sorted(
alumni,
key=lambda a: _parse_start_year(a.get('years', '')),
reverse=True,
)
entries = [generate_alumni_entry(a) for a in sorted_alumni]
return "<br>\n ".join(entries)
def generate_undergrad_entry(alum: Dict[str, Any]) -> str:
"""Generate HTML for a single undergraduate alumni entry.
Args:
alum: Dictionary with alumni data (name, years, current_position, current_position_url)
Returns:
HTML string for the alumni entry
"""
name = alum.get("name", "")
years = alum.get("years", "")
current_position = alum.get("current_position", "")
current_position_url = alum.get("current_position_url", "")
# Build position display with optional link
if current_position and current_position_url:
position_display = f'now at <a href="{current_position_url}" target="_blank">{current_position}</a>'
elif current_position:
position_display = f"now at {current_position}"
else:
position_display = ""
# Build parenthetical info
paren_parts = []
if years:
paren_parts.append(years)
if position_display:
paren_parts.append(position_display)
paren_display = f" ({'; '.join(paren_parts)})" if paren_parts else ""
return f"{name}{paren_display}"
def generate_undergrad_list_content(
alumni: List[Dict[str, Any]], cv_order: Optional[List[str]] = None
) -> str:
"""Generate HTML content for undergraduate alumni list.
Alumni are sorted to match CV order (reverse chronological by join date).
Args:
alumni: List of alumni dictionaries
cv_order: Optional list of names in CV order (from parse_cv_undergrad_order)
Returns:
HTML string with alumni entries separated by <br>
"""
if not alumni:
return ""
# Sort by start year descending (reverse chronological),
# falling back to CV order for ties
cv_position = {}
if cv_order:
for i, name in enumerate(cv_order):
cv_position[name] = i
def sort_key(a):
start_year = _parse_start_year(a.get("years", ""))
name = a.get("name", "")
cv_pos = cv_position.get(name, 99999)
# Negate start_year for descending; use cv_pos as tiebreaker
return (-start_year, cv_pos)
sorted_alumni = sorted(alumni, key=sort_key)
entries = [generate_undergrad_entry(a) for a in sorted_alumni]
return "<br>\n ".join(entries)
def generate_collaborator_entry(collab: Dict[str, Any]) -> str:
"""Generate HTML for a single collaborator entry.
Args:
collab: Dictionary with collaborator data (name, url, description)
Returns:
HTML string for the collaborator paragraph
"""
name = collab.get("name", "")
url = collab.get("url", "")
description = collab.get("description", "")
# The description already contains the full text, but we need to replace
# the name portion with a link
if url:
# If description starts with name, replace it with linked version
if description.startswith(name):
linked_name = f'<a href="{url}" target="_blank">{name}</a>'
description = linked_name + description[len(name) :]
else:
# Otherwise just create the link
description = f'<a href="{url}" target="_blank">{name}</a>'
return f"<p>{description}</p>"
def generate_collaborators_content(collaborators: List[Dict[str, Any]]) -> str:
"""Generate HTML content for collaborators section.
Args:
collaborators: List of collaborator dictionaries
Returns:
HTML string with all collaborator paragraphs
"""
if not collaborators:
return ""
entries = [generate_collaborator_entry(c) for c in collaborators]
return "\n ".join(entries)
def build_people(data_path: Path, template_path: Path, output_path: Path, cv_path: Optional[Path] = None) -> None:
"""Build people.html from data and template.
Args:
data_path: Path to people.xlsx
template_path: Path to template HTML file
output_path: Path for generated HTML file
cv_path: Optional path to JRM_CV.tex for ordering undergrad alumni
"""
# Load data
data = load_people(data_path)
# Get CV order for undergrad alumni
cv_order = []
if cv_path:
cv_order = parse_cv_undergrad_order(cv_path)
# Generate content for each section
director_content = ""
if data.get("director"):
director_content = generate_director_content(data["director"][0])
replacements = {
"DIRECTOR_CONTENT": director_content,
"MEMBERS_CONTENT": generate_members_content(data.get("members", [])),
"ALUMNI_POSTDOCS_CONTENT": generate_alumni_list_content(
data.get("alumni_postdocs", [])
),
"ALUMNI_GRADS_CONTENT": generate_alumni_list_content(
data.get("alumni_grads", [])
),
"ALUMNI_MANAGERS_CONTENT": generate_alumni_list_content(
data.get("alumni_managers", [])
),
"ALUMNI_UNDERGRADS_CONTENT": generate_undergrad_list_content(
data.get("alumni_undergrads", []), cv_order
),
"COLLABORATORS_CONTENT": generate_collaborators_content(
data.get("collaborators", [])
),
}
# Inject into template
inject_content(template_path, output_path, replacements)
# Report
total = sum(len(items) for items in data.values())
print(f"Generated {output_path} with {total} people entries")
def main():
"""Main entry point for CLI usage."""
project_root = Path(__file__).parent.parent
data_path = project_root / "data" / "people.xlsx"
template_path = project_root / "templates" / "people.html"
output_path = project_root / "people.html"
cv_path = project_root / "documents" / "JRM_CV.tex"
build_people(data_path, template_path, output_path, cv_path)
if __name__ == "__main__":
main()