forked from codewithsadee/vcard-personal-portfolio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
587 lines (487 loc) · 22.5 KB
/
Copy pathgenerator.py
File metadata and controls
587 lines (487 loc) · 22.5 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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
from __future__ import annotations
import datetime
import json
import re
from pathlib import Path
from typing import Any
import tomllib
ROOT_DIR = Path(__file__).resolve().parent
CONFIG_PATH = ROOT_DIR / "site.toml"
TEMPLATES_DIR = ROOT_DIR / "templates"
PLACEHOLDER_PATTERN = re.compile(
r"(?<!\$)\{([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)+)\}"
)
def load_config(path: Path = CONFIG_PATH) -> dict[str, Any]:
with path.open("rb") as file:
return tomllib.load(file)
def resolve_placeholder(context: dict[str, Any], key_path: str) -> Any:
value: Any = context
for key in key_path.split("."):
if not isinstance(value, dict) or key not in value:
raise KeyError(key_path)
value = value[key]
return value
def render_placeholders(template_text: str, context: dict[str, Any]) -> str:
def replace(match: re.Match[str]) -> str:
raw_value = resolve_placeholder(context, match.group(1))
if raw_value is None:
return ""
if isinstance(raw_value, (dict, list)):
return json.dumps(raw_value)
return str(raw_value)
return PLACEHOLDER_PATTERN.sub(replace, template_text)
def render_template(template_name: str, context: dict[str, Any]) -> str:
template_path = TEMPLATES_DIR / template_name
template_text = template_path.read_text(encoding="utf-8")
try:
return render_placeholders(template_text, context)
except KeyError as error:
missing_key = error.args[0]
raise KeyError(
f"Missing value for placeholder {missing_key!r} in template {template_name!r}."
) from error
def slugify(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
return slug or "item"
def default_project_filters(projects: list[dict[str, Any]]) -> list[dict[str, str]]:
categories: list[str] = []
for project in projects:
category = project.get("category")
if category and category not in categories:
categories.append(category)
filters = [{"key": "all", "label": "All"}]
filters.extend({"key": category, "label": category.replace("-", " ").title()} for category in categories)
return filters
def render_about(paragraphs: list[str]) -> str:
return "".join(f"<p class='mb-4 last:mb-0'>{paragraph}</p>" for paragraph in paragraphs)
def render_experience_item(item: dict[str, Any]) -> str:
title_html = f'<h3 class="text-base font-semibold font-mono text-zinc-900 dark:text-zinc-100'
if item.get("link"):
title_html += ' cursor-pointer hover:text-accent dark:hover:text-accent transition-colors"'
title_html += f' onclick="window.location.href=\'{item["link"]}\'">{item["title"]}</h3>'
title_html += f'<button class="experience-copy-link hidden group-hover:block text-zinc-400 hover:text-accent dark:hover:text-accent transition-colors" data-link="{item["link"]}" title="Copy link"><i class="bi bi-link-45deg inline-block align-middle"></i></button>'
else:
title_html += '">' + item["title"] + '</h3>'
context_item = {**item, "title_html": title_html}
return render_template("partials/experience_item.html", {"item": context_item})
def calculate_duration(start_val: Any) -> str:
if not start_val or not isinstance(start_val, str):
return ""
today = datetime.date.today()
try:
parts = [int(p) for p in start_val.split("-") if p.isdigit()]
if len(parts) == 3:
start_year, start_month, start_day = parts
else:
return str(start_val)
years = today.year - start_year - ((today.month, today.day) < (start_month, start_day))
if years <= 0:
months = (today.year - start_year) * 12 + today.month - start_month
if months <= 1:
return "1 month"
return f"{months} months"
elif years == 1:
return "over 1 year"
else:
return f"over {years} years"
except Exception:
return str(start_val)
def render_skill_item(skill: dict[str, Any], project_ids: dict[str, str]) -> str:
skill_id = slugify(skill["name"].replace("/", "-").replace("+", "plus"))
projects_html = ""
project_names = skill.get("projects", [])
if project_names:
project_pills = []
for project_name in project_names:
project_id = project_ids.get(project_name)
if project_id:
project_pills.append(
f'<a href="#{project_id}" class="project-jump inline-flex items-center px-2 py-0.5 rounded-none border border-zinc-300 dark:border-zinc-700 text-xs font-medium font-mono bg-transparent text-zinc-600 dark:text-zinc-400 hover:text-accent dark:hover:text-accent hover:border-accent dark:hover:border-accent mr-1.5 mb-1.5 transition-colors">{project_name}</a>'
)
else:
project_pills.append(
f'<span class="inline-flex items-center px-2 py-0.5 rounded-none border border-zinc-300 dark:border-zinc-700 text-xs font-medium font-mono bg-transparent text-zinc-500 dark:text-zinc-500 mr-1.5 mb-1.5">{project_name}</span>'
)
projects_html = f'<div class="mt-2 flex flex-wrap">{"".join(project_pills)}</div>'
icon_html = ""
if skill.get("icon"):
icon_val = skill["icon"]
if "devicon" in icon_val:
icon_class = icon_val
elif icon_val.startswith("bi bi-") or icon_val.startswith("bi-"):
icon_class = icon_val if icon_val.startswith("bi bi-") else f"bi {icon_val}"
else:
icon_class = f"bi bi-{icon_val}"
icon_html = f'<i class="{icon_class} text-lg mr-2 inline-block align-middle"></i>'
duration_html = ""
duration = skill.get("duration")
if skill.get("start_date"):
duration = calculate_duration(skill["start_date"])
if duration:
duration_html = f'<span class="text-xs font-mono text-zinc-500 dark:text-zinc-400">{duration}</span>'
details_html = ""
if skill.get("details"):
details_html = f'<p class="text-sm text-zinc-600 dark:text-zinc-400 mb-3 mt-2">{skill["details"]}</p>'
context = {
"item": {
"skill_id": skill_id,
"name": skill["name"],
"level": skill.get("level", ""),
"icon_html": icon_html,
"duration_html": duration_html,
"details_html": details_html,
"projects_html": projects_html,
}
}
return render_template("partials/skill_item.html", context)
def render_project_card(project: dict[str, Any], category_map: dict[str, str] | None = None) -> str:
project_title = project.get("title", "Project")
project_id = f"project-{slugify(project_title)}"
modal_id = f"modal-{project_id}"
skills_html = ""
project_skills = project.get("skills", [])
if project_skills:
pills_html = "".join(
f'<span class="inline-flex items-center px-2 py-0.5 rounded-none border border-zinc-300 dark:border-zinc-700 text-xs font-medium font-mono bg-transparent text-zinc-600 dark:text-zinc-400 mr-1.5 mb-1.5">{skill}</span>'
for skill in project_skills
)
skills_html = f'<div class="flex flex-wrap mt-3">{pills_html}</div>'
link_html = ""
if project.get("link"):
link_html = (
f'<a href="{project["link"]}" target="_blank" rel="noopener noreferrer" '
'class="inline-flex items-center text-sm font-medium font-mono text-zinc-900 dark:text-zinc-100 '
'hover:text-accent dark:hover:text-accent transition-colors mt-3">'
'View Project <span class="ml-1 text-xs">↗</span></a>'
)
image_html = ""
if project.get("image"):
image_html = (
f'<img src="{project["image"]}" alt="{project_title}" loading="lazy" decoding="async" '
'class="w-full h-48 object-cover border-b border-zinc-300 dark:border-zinc-700">'
)
date_html = ""
if project.get("date"):
category = project.get("category", "other")
category_label = category_map.get(category) if category_map else None
if not category_label:
category_label = category.replace("-", " ").title()
date_html = (
'<span class="text-xs font-medium font-mono text-zinc-500 dark:text-zinc-400 mb-2 block flex items-center">'
f'<i class="bi bi-clock mr-1 inline-block align-middle"></i>{project["date"]} \u2022 {category_label}</span>'
)
details_button_html = ""
if project.get("details") or project.get("features"):
margin_class = "ml-3" if project.get("link") else ""
details_button_html = (
f'<button class="project-details-btn text-sm font-mono text-zinc-500 hover:text-accent '
f'dark:hover:text-accent transition-colors mt-3 {margin_class}" data-modal-id="{modal_id}">'
"More Info →</button>"
)
context = {
"item": {
"project_id": project_id,
"modal_id": modal_id,
"category": project.get("category", "other"),
"title": project_title,
"description": project.get("description", ""),
"image_html": image_html,
"date_html": date_html,
"skills_html": skills_html,
"link_html": link_html,
"details_button_html": details_button_html,
}
}
return render_template("partials/project_card.html", context)
def render_project_modal(project: dict[str, Any]) -> str:
project_title = project.get("title", "Project")
project_id = f"project-{slugify(project_title)}"
modal_id = f"modal-{project_id}"
details_html = ""
if project.get("details"):
details_html = (
f'<p class="text-sm text-zinc-600 dark:text-zinc-400 leading-relaxed mb-4">'
f'{project["details"]}</p>'
)
gallery_html = ""
project_gallery = project.get("gallery", [])
if project_gallery:
slides = []
for index, item in enumerate(project_gallery):
media_type = "image"
src = ""
poster = ""
alt = f"Gallery item {index + 1}"
if isinstance(item, str):
src = item
ext = src.split("?")[0].split("#")[0].split(".")[-1].lower()
if ext in ("mp4", "webm", "ogg", "mov", "m4v"):
media_type = "video"
elif isinstance(item, dict):
media_type = item.get("type", "image")
src = item.get("src") or item.get("url", "")
poster = item.get("poster", "")
alt = item.get("alt") or item.get("caption") or f"Gallery item {index + 1}"
if not src:
continue
if media_type == "video":
poster_attr = f' poster="{poster}"' if poster else ""
media_element = (
f'<video src="{src}"{poster_attr} controls playsinline '
f'class="w-full h-full object-contain bg-black" '
f'preload="metadata"></video>'
)
else:
media_element = (
f'<img src="{src}" alt="{alt}" loading="lazy" decoding="async" '
f'class="w-full h-full object-contain bg-black">'
)
slide_html = (
f'<div class="carousel-slide min-w-full h-64 sm:h-96 flex items-center justify-center flex-shrink-0">'
f'{media_element}'
f'</div>'
)
slides.append(slide_html)
if slides:
slides_html = "".join(slides)
prev_btn = ""
next_btn = ""
indicators = ""
if len(slides) > 1:
prev_btn = (
f'<button class="carousel-prev absolute left-2 top-1/2 -translate-y-1/2 bg-black/40 hover:bg-black/70 text-white font-semibold rounded-none p-2 border border-white/20 z-10 transition-all opacity-100 md:opacity-0 md:group-hover/carousel:opacity-100 md:focus:opacity-100 flex items-center justify-center" aria-label="Previous slide">'
f'<i class="bi bi-chevron-left"></i>'
f'</button>'
)
next_btn = (
f'<button class="carousel-next absolute right-2 top-1/2 -translate-y-1/2 bg-black/40 hover:bg-black/70 text-white font-semibold rounded-none p-2 border border-white/20 z-10 transition-all opacity-100 md:opacity-0 md:group-hover/carousel:opacity-100 md:focus:opacity-100 flex items-center justify-center" aria-label="Next slide">'
f'<i class="bi bi-chevron-right"></i>'
f'</button>'
)
dots = []
for i in range(len(slides)):
active_class = "bg-accent" if i == 0 else "bg-white/40 hover:bg-white/70"
dot = f'<button class="carousel-dot h-1 w-6 transition-colors {active_class}" data-slide-to="{i}" aria-label="Go to slide {i + 1}"></button>'
dots.append(dot)
indicators = (
f'<div class="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5 z-10">'
f'{"".join(dots)}'
f'</div>'
)
gallery_html = (
f'<div class="mt-4">'
f'<h4 class="font-semibold font-mono text-zinc-900 dark:text-zinc-100 mb-2">Media</h4>'
f'<div class="relative group/carousel w-full overflow-hidden border border-zinc-300 dark:border-zinc-700 bg-zinc-100 dark:bg-zinc-900 media-carousel" data-carousel-id="carousel-{modal_id}">'
f'<div class="carousel-slides flex transition-transform duration-300 ease-out" style="transform: translateX(0%);">'
f'{slides_html}'
f'</div>'
f'{prev_btn}'
f'{next_btn}'
f'{indicators}'
f'</div>'
f'</div>'
)
features_html = ""
project_features = project.get("features", [])
if project_features:
features_list = "".join(
f'<li class="text-sm font-mono text-zinc-600 dark:text-zinc-400 flex items-start"><span class="mr-3">•</span><span>{feature}</span></li>'
for feature in project_features
)
features_html = (
'<div class="mt-4"><h4 class="font-semibold font-mono text-zinc-900 dark:text-zinc-100 mb-2">Features</h4>'
f'<ul class="space-y-1">{features_list}</ul></div>'
)
link_button_html = ""
if project.get("link"):
link_button_html = (
f'<a href="{project["link"]}" target="_blank" rel="noopener noreferrer" '
'class="inline-flex items-center px-4 py-2 bg-transparent border border-accent text-accent '
'font-medium font-mono rounded-none hover:bg-accent hover:text-global-bg '
'transition-colors">View on GitHub <span class="ml-2">↗</span></a>'
)
context = {
"item": {
"modal_id": modal_id,
"title": project_title,
"details_html": details_html,
"gallery_html": gallery_html,
"features_html": features_html,
"link_button_html": link_button_html,
}
}
return render_template("partials/project_modal.html", context)
def render_filter_buttons(filters: list[dict[str, str]]) -> str:
button_classes = (
"px-3 py-1 text-sm font-mono rounded-none border border-zinc-300 dark:border-zinc-700 bg-transparent text-zinc-700 dark:text-zinc-300 "
"hover:bg-zinc-100 dark:hover:bg-zinc-800 filter-btn transition-colors"
)
buttons: list[str] = []
for index, filter_item in enumerate(filters):
context = {
"item": {
"key": filter_item["key"],
"label": filter_item["label"],
"aria_pressed": "true" if index == 0 else "false",
"button_classes": button_classes,
}
}
buttons.append(render_template("partials/project_filter_button.html", context))
return "".join(buttons)
def build_index_context(config: dict[str, Any]) -> dict[str, Any]:
site = {"lang": "en", **config.get("site", {})}
user_config = config.get("user", {})
user = {
"name": "Your Name",
"headline": "Your headline",
"profile_image": "pfp.webp",
**user_config,
}
user["social"] = {
"github": "",
"linkedin": "",
"discord": "",
"resume": "",
**user_config.get("social", {}),
}
meta = {
"page_title": "",
"description": "",
"favicon": "",
**config.get("meta", {}),
}
if not meta["page_title"]:
meta["page_title"] = f'{user["name"]} - {user["headline"]}' if user["headline"] else user["name"]
if not meta["description"]:
meta["description"] = f'Portfolio of {user["name"]}, {user["headline"]}.'
if not meta["favicon"]:
meta["favicon"] = user["profile_image"]
sections = {
"about_title": "About",
"experience_title": "Experience",
"projects_title": "Projects",
"skills_title": "Skills",
"contact_title": "Contact",
"no_projects": "No projects found matching your criteria.",
**config.get("sections", {}),
}
contact = {
"form_action": "",
"submit_label": "Send Message",
**config.get("contact", {}),
}
footer = {
"text": "Made with <3",
**config.get("footer", {}),
}
content_config = config.get("content", {})
taglines = content_config.get("taglines", [])
if not taglines:
taglines = [user["headline"]] if user["headline"] else [user["name"]]
experiences = config.get("experiences", [])
skills = config.get("skills", {})
projects = config.get("projects", [])
about_paragraphs = content_config.get("about", [])
project_ids = {
project["title"]: f'project-{slugify(project["title"])}'
for project in projects
if project.get("title")
}
filters = config.get("project_filters") or default_project_filters(projects)
category_map = {f["key"]: f["label"] for f in filters if "key" in f and "label" in f}
skills_categories_config = config.get("skills_categories", {})
skills_categories = []
if isinstance(skills_categories_config, dict):
for key, val in skills_categories_config.items():
skills_categories.append({"key": key, "title": val})
existing_keys = {cat["key"] for cat in skills_categories}
if isinstance(skills, dict):
for key in skills.keys():
if key not in existing_keys:
title = key.replace("_", " ").title()
skills_categories.append({"key": key, "title": title})
skills_columns = []
for cat in skills_categories:
cat_key = cat["key"]
cat_title = cat["title"]
items = skills.get(cat_key, []) if isinstance(skills, dict) else []
if not items:
continue
items_html = "".join(render_skill_item(skill, project_ids) for skill in items)
column_html = (
f' <div>\n'
f' <h3 class="text-base font-semibold font-mono text-accent-2 mb-4">{cat_title}</h3>\n'
f' {items_html}\n'
f' </div>'
)
skills_columns.append(column_html)
num_columns = len(skills_columns)
if num_columns == 1:
skills_grid_class = "grid grid-cols-1 gap-8"
elif num_columns == 2:
skills_grid_class = "grid grid-cols-1 md:grid-cols-2 gap-8"
elif num_columns == 3:
skills_grid_class = "grid grid-cols-1 md:grid-cols-3 gap-8"
else:
skills_grid_class = "grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8"
skills_html = "\n".join(skills_columns)
content = {
"first_tagline": taglines[0],
"taglines_json": json.dumps(taglines),
"about_html": render_about(about_paragraphs),
"timeline_items_html": "".join(render_experience_item(item) for item in experiences),
"skills_html": skills_html,
"skills_grid_class": skills_grid_class,
"project_filters_html": render_filter_buttons(filters),
"project_cards_html": "".join(render_project_card(project, category_map) for project in projects),
"project_modals_html": "".join(render_project_modal(project) for project in projects),
}
return {
"site": site,
"meta": meta,
"user": user,
"sections": sections,
"contact": contact,
"footer": footer,
"content": content,
}
def minify_if_available(html_output: str) -> str:
try:
import htmlmin
except ImportError:
return html_output
return htmlmin.minify(html_output, remove_empty_space=True)
def build_redirect_page(path_key: str, target_url: str, user_name: str) -> str:
label = path_key.replace("-", " ").replace("/", " ").strip().title() or "Redirect"
context = {
"redirect": {
"title": f"{user_name} - {label}",
"description": f"Redirecting to {target_url}",
"url": target_url,
}
}
return render_template("redirect.html", context)
def write_redirects(config: dict[str, Any], user_name: str) -> None:
redirects = config.get("redirects", {})
if not isinstance(redirects, dict):
raise TypeError("The [redirects] section must be a TOML table.")
for path_key, target_url in redirects.items():
redirect_path = str(path_key).strip("/")
if not redirect_path:
raise ValueError("Redirect keys cannot be empty.")
if not target_url:
raise ValueError(f"Redirect URL for {path_key!r} cannot be empty.")
redirect_html = build_redirect_page(redirect_path, str(target_url), user_name)
output_path = ROOT_DIR / redirect_path / "index.html"
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(redirect_html, encoding="utf-8")
def main() -> None:
config = load_config()
context = build_index_context(config)
index_template = render_template("index.html", context)
index_output = minify_if_available(index_template)
(ROOT_DIR / "index.html").write_text(index_output, encoding="utf-8")
write_redirects(config, context["user"]["name"])
print("Successfully generated clean portfolio website!")
if __name__ == "__main__":
main()