-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy patharis_homepage.py
More file actions
1809 lines (1591 loc) · 74.5 KB
/
Copy patharis_homepage.py
File metadata and controls
1809 lines (1591 loc) · 74.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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""aris_homepage.py — generate fact-checked academic homepages from a CV.
See skills/homepage-generator/SKILL.md for the full contract.
Pipeline:
init --from-cv → textutil → emit extraction handoff JSON → user's calling LLM
fills .aris-homepage/extraction.json → this script persists
to profile.yml + publications.bib + bio.md + news.md
render → load → fact-check (DBLP/arXiv) → Python builds HTML chunks
→ injects into homepage-<persona>.html template
check → fact-check only, update audit-report.md
doctor → environment diagnostic
Round-2 cross-model design (Codex GPT-5.5 xhigh + Gemini auto-gemini-3) converged on:
- macOS textutil for .docx; python-docx as optional fallback
- LLM extraction by calling agent (not here in Python); persistence handled by this script
- JSON-schema-constrained extraction output
- Idempotency: bail by default if profile.yml exists
- DBLP direct API call (no third-party lib)
- Two-layer override: per-paper YAML + --override-all CLI
- Template approach: Python builds per-section HTML chunks; template is shell
External deps: pyyaml only (BibTeX is parsed via the stdlib parser in this file).
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import html as html_lib
import json
import mimetypes
import re
import shutil
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
try:
import yaml # type: ignore
HAS_YAML = True
except ImportError:
HAS_YAML = False
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SCHEMA_VERSION = 1
DBLP_API = "https://dblp.org/search/publ/api"
ARXIV_API = "http://export.arxiv.org/api/query"
DEFAULT_FILES = {
"profile": "profile.yml",
"bib": "publications.bib",
"bio": "bio.md",
"news": "news.md",
"extraction_review": "EXTRACTION_REVIEW.md",
"audit_report": "audit-report.md",
"output_html": "index.html",
}
PERSONAS = ("theory-minimal", "active-researcher")
TEMPLATES_DIR = Path(__file__).resolve().parent / "templates"
# Friendly labels for social/scholar links rendered in the masthead.
# (Email is excluded — it's rendered separately as a mailto: line above the strip.)
LINK_LABELS = {
"google_scholar": "Scholar",
"semantic_scholar": "Semantic Scholar",
"dblp": "DBLP",
"github": "GitHub",
"twitter": "Twitter",
"bluesky": "Bluesky",
"linkedin": "LinkedIn",
"orcid": "ORCID",
"homepage": "Homepage",
"cv": "CV",
}
# DBLP local cache — avoids re-querying same titles + rate-limit hell
DBLP_CACHE_DIR = ".aris-homepage"
DBLP_CACHE_FILE = "dblp-cache.json"
# ---------------------------------------------------------------------------
# Stdlib BibTeX parser
# ---------------------------------------------------------------------------
# Handles the BibTeX subset that real-world ML papers actually use:
# @inproceedings{key, author = {...}, title = {...}, booktitle = "...", year = 2024}
# Brace nesting, quoted values, and common LaTeX escapes (\&, \"o) are supported.
# Does NOT support: @string macros, @preamble, @comment with embedded entries,
# crossref resolution, full LaTeX-to-Unicode normalization.
_RE_ENTRY_HEADER = re.compile(r"@\s*([A-Za-z]+)\s*\{\s*([^,\s]+)\s*,")
_LATEX_ESCAPES = {
r"\&": "&", r"\%": "%", r"\$": "$", r"\#": "#", r"\_": "_",
r"\{": "{", r"\}": "}", r"\textasciitilde": "~",
}
def parse_bibtex_str(text: str) -> dict[str, dict[str, str]]:
"""Parse BibTeX text → {bibkey: {field: value, ..., 'ENTRYTYPE': type}}.
Designed to be forgiving — silently skips malformed entries rather than crashing.
"""
entries: dict[str, dict[str, str]] = {}
i = 0
n = len(text)
while i < n:
m = _RE_ENTRY_HEADER.search(text, i)
if not m:
break
entry_type = m.group(1).lower()
key = m.group(2).strip()
i = m.end()
# Parse fields until matching closing brace of the entry.
entry: dict[str, str] = {"ENTRYTYPE": entry_type}
depth = 1
while i < n and depth > 0:
# Skip whitespace + commas
while i < n and text[i] in " \t\n\r,":
i += 1
if i >= n:
break
if text[i] == "}":
depth -= 1
i += 1
continue
# Parse field name
fm = re.match(r"([A-Za-z][A-Za-z0-9_-]*)\s*=\s*", text[i:])
if not fm:
# Recover: skip to next entry boundary
i = text.find("\n", i) + 1 if "\n" in text[i:] else n
continue
fname = fm.group(1).lower()
i += fm.end()
# Parse field value: brace-balanced, quoted, or bare number
if text[i] == "{":
value, i = _read_braced(text, i)
elif text[i] == '"':
value, i = _read_quoted(text, i)
else:
vm = re.match(r"[A-Za-z0-9._:/-]+", text[i:])
value = vm.group(0) if vm else ""
i += len(value)
entry[fname] = _clean_bib_value(value)
if key:
entries[key] = entry
return entries
def _read_braced(text: str, i: int) -> tuple[str, int]:
"""Read a brace-delimited value starting at text[i] == '{'. Returns (content, new_i)."""
assert text[i] == "{"
depth = 1
i += 1
start = i
while i < len(text) and depth > 0:
c = text[i]
if c == "\\" and i + 1 < len(text):
i += 2
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
if depth == 0:
return text[start:i], i + 1
i += 1
return text[start:i], i
def _read_quoted(text: str, i: int) -> tuple[str, int]:
"""Read a quoted value starting at text[i] == '"'. Returns (content, new_i)."""
assert text[i] == '"'
i += 1
start = i
depth = 0 # supports embedded {...}
while i < len(text):
c = text[i]
if c == "\\" and i + 1 < len(text):
i += 2
continue
if c == "{":
depth += 1
elif c == "}":
depth -= 1
elif c == '"' and depth == 0:
return text[start:i], i + 1
i += 1
return text[start:i], i
def _clean_bib_value(s: str) -> str:
"""Strip leading/trailing whitespace, collapse internal whitespace, apply LaTeX escapes."""
s = s.strip()
for k, v in _LATEX_ESCAPES.items():
s = s.replace(k, v)
# Collapse internal newlines + spaces
s = re.sub(r"\s+", " ", s)
# Strip outer braces (common protection brace: {Title})
while s.startswith("{") and s.endswith("}"):
s = s[1:-1].strip()
return s
def split_authors(author_field: str) -> list[str]:
"""Split BibTeX author field on ' and '. Convert 'Last, First' → 'First Last'."""
if not author_field:
return []
raw = re.split(r"\s+and\s+", author_field)
normalized = []
for a in raw:
a = a.strip()
if "," in a:
parts = [p.strip() for p in a.split(",", 1)]
if len(parts) == 2 and parts[1]:
a = f"{parts[1]} {parts[0]}"
normalized.append(a)
return normalized
# ---------------------------------------------------------------------------
# Minimal Markdown subset for bio.md and news.md
# ---------------------------------------------------------------------------
def md_inline(s: str) -> str:
"""Escape HTML then apply minimal inline Markdown: links, bold, italic, code.
Allows raw <a ...>...</a> and <img ...> tags to pass through unescaped — needed for
embedded badges (e.g. star-history SVG inside a news bullet)."""
stash: list[str] = []
def _stash(m):
stash.append(m.group(0))
return f"§MD{len(stash)-1}§"
# Stash <a>-with-content first (may wrap an <img>); then bare <img>.
s = re.sub(r"<a\s[^>]*?>.*?</a>", _stash, s, flags=re.DOTALL)
s = re.sub(r"<img\s[^>]*?/?>", _stash, s)
s = html_lib.escape(s, quote=False)
s = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)",
r'<a href="\2" rel="noopener">\1</a>', s)
s = re.sub(r"\*\*([^*\n]+)\*\*", r"<strong>\1</strong>", s)
s = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", s)
s = re.sub(r"`([^`\n]+)`", r"<code>\1</code>", s)
for i, tag in enumerate(stash):
s = s.replace(f"§MD{i}§", tag)
return s
def md_to_paragraphs(text: str) -> str:
"""Render bio-style Markdown to <p> blocks. Blank line = paragraph break."""
out = []
for para in re.split(r"\n\s*\n", text.strip()):
if para.strip():
out.append(f"<p>{md_inline(para.strip())}</p>")
return "\n".join(out)
# ---------------------------------------------------------------------------
# Command: init --from-cv
# ---------------------------------------------------------------------------
EXTRACTION_SCHEMA = {
"type": "object",
"properties": {
"profile": {
"type": "object",
"properties": {
"identity": {
"type": "object",
"properties": {
"name": {"type": "string"},
"name_native": {"type": ["string", "null"]},
"title": {"type": ["string", "null"]},
"email": {"type": ["string", "null"]},
},
"required": ["name"],
},
"affiliations": {
"type": "object",
"properties": {
"current": {"type": "array", "items": {"type": "object"}},
"past": {"type": "array", "items": {"type": "object"}},
},
},
"education": {"type": "array", "items": {"type": "object"}},
"research": {
"type": "object",
"properties": {
"summary": {"type": "string"},
"interests": {"type": "array", "items": {"type": "string"}},
},
},
"links": {"type": "object"},
"awards": {"type": "array", "items": {"type": "object"}},
"talks": {"type": "array", "items": {"type": "object"}},
"teaching": {"type": "array", "items": {"type": "object"}},
"selected_publications": {"type": "array", "items": {"type": "string"}},
"publications_meta": {"type": "object"},
},
"required": ["identity", "research"],
},
"bibtex_entries": {"type": "string",
"description": "Full text of publications.bib (BibTeX format)."},
"bio_md": {"type": "string", "description": "1-3 paragraph bio in Markdown."},
"news_md": {"type": "string",
"description": "Reverse-chrono bullets: '- 2026-05: Did X'."},
"uncertain": {"type": "array", "items": {"type": "string"},
"description": "Claims the agent could not verify from the CV."},
},
"required": ["profile", "bibtex_entries"],
}
def cmd_init(args: argparse.Namespace) -> int:
"""Bootstrap workspace by extracting a CV into structured editable files."""
out_dir = Path(args.out).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
cv_path = Path(args.from_cv).resolve()
if not cv_path.exists():
die(f"CV file not found: {cv_path}")
if (out_dir / DEFAULT_FILES["profile"]).exists():
if args.force:
backup_existing(out_dir)
elif args.merge:
die("--merge is not yet implemented (v1.1).")
else:
die(f"{DEFAULT_FILES['profile']} already exists at {out_dir}. "
f"Use --force (backup .bak-TIMESTAMP) or --merge (v1.1).")
cv_txt = extract_text_from_cv(cv_path)
txt_path = out_dir / ".aris-homepage" / "cv.txt"
txt_path.parent.mkdir(parents=True, exist_ok=True)
txt_path.write_text(cv_txt, encoding="utf-8")
# Optional: fetch GitHub repo snapshots for additional context (v1.1).
# See issue #2: user wants to merge repo timelines into homepage news + projects.
repos_path = None
if getattr(args, "from_repos", None):
repo_specs = [r.strip() for r in args.from_repos.split(",") if r.strip()]
repos_data = fetch_github_repos(repo_specs,
include_private=getattr(args, "include_private", False))
if repos_data:
repos_path = out_dir / ".aris-homepage" / "github_repos.json"
repos_path.write_text(json.dumps(repos_data, indent=2, ensure_ascii=False),
encoding="utf-8")
print(f"✓ {len(repos_data)} GitHub repo snapshots → {repos_path}")
print_extraction_handoff(txt_path, out_dir, repos_path=repos_path)
return 0
def fetch_github_repos(repos: list[str], *, include_private: bool = False) -> list[dict]:
"""Fetch repo snapshot via `gh` CLI for each `owner/repo` spec.
Returns a list of dicts (one per successfully fetched repo) with shape:
{repo, snapshot_at, url, homepage_url, description, stars, forks,
primary_language, topics, is_archived, created_at, pushed_at,
releases: [{tag, name, date, url, description}], latest_commit,
readme_excerpt}
Private repos are skipped by default — pass include_private=True to override.
"""
if not shutil.which("gh"):
die("`gh` CLI not installed. Install via `brew install gh` or see https://cli.github.com/")
auth = subprocess.run(["gh", "auth", "status"], capture_output=True, text=True)
if auth.returncode != 0:
die("`gh` CLI not authenticated. Run: `gh auth login`")
gql = """query($owner:String!, $name:String!) {
repository(owner:$owner, name:$name) {
nameWithOwner description url homepageUrl
isPrivate isArchived
stargazerCount forkCount
createdAt pushedAt
primaryLanguage { name }
repositoryTopics(first: 10) { nodes { topic { name } } }
releases(first: 8, orderBy: {field: CREATED_AT, direction: DESC}) {
nodes { name tagName publishedAt url description }
}
defaultBranchRef {
name
target {
... on Commit {
latest: history(first: 1) {
nodes { committedDate messageHeadline url oid }
}
}
}
}
}
}"""
results: list[dict] = []
for spec in repos:
if "/" not in spec:
print(f" ⚠ invalid repo spec '{spec}' (need owner/repo); skipping", file=sys.stderr)
continue
owner, name = spec.split("/", 1)
try:
r = subprocess.run(
["gh", "api", "graphql",
"-f", f"owner={owner}", "-f", f"name={name}",
"-f", f"query={gql}"],
capture_output=True, text=True, check=True,
)
data = json.loads(r.stdout).get("data", {}).get("repository")
except subprocess.CalledProcessError as e:
print(f" ⚠ gh api failed for {spec}: {(e.stderr or '')[:200]}", file=sys.stderr)
continue
except json.JSONDecodeError:
print(f" ⚠ malformed JSON from gh for {spec}", file=sys.stderr)
continue
if not data:
print(f" ⚠ repo not found or no access: {spec}", file=sys.stderr)
continue
if data.get("isPrivate") and not include_private:
print(f" ⚠ skipping PRIVATE repo {spec} (use --include-private to override)",
file=sys.stderr)
continue
# README — separate REST call, truncated to 20KB
readme_text = ""
try:
rm = subprocess.run(
["gh", "api", f"/repos/{owner}/{name}/readme",
"-H", "Accept: application/vnd.github.raw"],
capture_output=True, text=True, check=False,
)
if rm.returncode == 0:
readme_text = rm.stdout[:20000]
except Exception:
pass
topics = [n["topic"]["name"]
for n in (data.get("repositoryTopics") or {}).get("nodes", [])]
commits = (((data.get("defaultBranchRef") or {})
.get("target") or {})
.get("latest", {}).get("nodes", []))
latest_commit = commits[0] if commits else None
snap = {
"repo": data["nameWithOwner"],
"snapshot_at": datetime.now(timezone.utc).isoformat(),
"url": data["url"],
"homepage_url": data.get("homepageUrl"),
"description": data.get("description"),
"stars": data.get("stargazerCount", 0),
"forks": data.get("forkCount", 0),
"primary_language": (data.get("primaryLanguage") or {}).get("name"),
"topics": topics,
"is_archived": data.get("isArchived", False),
"is_private": data.get("isPrivate", False),
"created_at": data.get("createdAt"),
"pushed_at": data.get("pushedAt"),
"releases": [
{
"tag": rel["tagName"],
"name": rel.get("name"),
"date": rel["publishedAt"],
"url": rel["url"],
"description": (rel.get("description") or "")[:500],
}
for rel in (data.get("releases") or {}).get("nodes", [])[:8]
],
"latest_commit": (
{
"date": latest_commit["committedDate"],
"message": latest_commit["messageHeadline"],
"url": latest_commit["url"],
"sha": latest_commit["oid"][:7],
} if latest_commit else None
),
"readme_excerpt": readme_text,
}
results.append(snap)
rel_count = len(snap["releases"])
print(f" ✓ {spec} — {snap['stars']} ★ · {rel_count} releases · "
f"{snap['primary_language'] or '—'}")
return results
def extract_text_from_cv(path: Path) -> str:
"""Convert CV → plain text. macOS textutil → python-docx → pdftotext fallback chain."""
suffix = path.suffix.lower()
if suffix == ".txt":
return path.read_text(encoding="utf-8")
if suffix == ".docx":
if shutil.which("textutil"):
r = subprocess.run(["textutil", "-convert", "txt", "-stdout", str(path)],
capture_output=True, text=True, check=True)
return r.stdout
try:
import docx # type: ignore
doc = docx.Document(str(path))
return "\n".join(p.text for p in doc.paragraphs)
except ImportError:
die("Cannot read .docx: install python-docx OR run on macOS (textutil).")
if suffix == ".pdf":
if shutil.which("pdftotext"):
r = subprocess.run(["pdftotext", str(path), "-"],
capture_output=True, text=True, check=True)
return r.stdout
die("Cannot read .pdf: install poppler-utils (provides pdftotext).")
die(f"Unsupported CV format: {suffix}. Use .txt, .docx, or .pdf.")
def print_extraction_handoff(txt_path: Path, out_dir: Path,
repos_path: Path | None = None) -> None:
"""Emit instructions for the calling LLM agent to do extraction.
This script does NOT call an LLM — the calling agent (Claude/Gemini)
reads cv.txt + optional github_repos.json, fills the JSON-schema-constrained
output, and writes .aris-homepage/extraction.json. A follow-up
`aris-homepage finalize` ingests that JSON and writes the editable sources.
"""
handoff_path = out_dir / ".aris-homepage" / "EXTRACTION_HANDOFF.md"
schema_path = out_dir / ".aris-homepage" / "extraction.schema.json"
schema_path.write_text(json.dumps(EXTRACTION_SCHEMA, indent=2), encoding="utf-8")
repos_block = ""
if repos_path is not None and repos_path.exists():
repos_block = f"""
## Optional source: GitHub repo snapshots (v1.1)
A snapshot of user-selected GitHub repos has been written to:
{repos_path.relative_to(out_dir)}
It contains per-repo: description / stars / forks / topics / primary_language /
created_at / pushed_at / up to 8 releases / latest commit / README excerpt
(truncated 20KB).
### How to use github_repos.json in extraction
- Surface each repo as a `featured_projects[]` entry (or extend an existing one)
with a new `github:` subobject carrying the snapshot data (stars, forks,
primary_language, topics, created_at, pushed_at, releases summary, latest_commit).
- Merge each repo's **timeline** into `news_md` with these rules:
* Take at most 2 events per repo (releases highest priority, then created_at).
* Cap total github-derived news at 6 across all repos.
* If a CV news entry already mentions a release / project on the same
date OR same YYYY-MM with overlapping title — DEDUP: keep the CV's
human phrasing and append the release URL; do not list both.
* stars/forks go to project stats, NOT into news.
- Use README excerpt to verify the project description matches the CV's claim
(catches misrepresentation).
- Mark anything you cannot confirm from `github_repos.json` as `uncertain[]`.
"""
handoff_path.write_text(f"""# ARIS Homepage — Extraction Handoff
The CV has been converted to plain text at:
{txt_path.relative_to(out_dir)}
{repos_block}
## Next step (LLM agent task)
Read the CV text{' + the github_repos.json snapshot' if repos_block else ''} and
emit JSON conforming to the schema at:
{schema_path.relative_to(out_dir)}
Write the JSON output to:
.aris-homepage/extraction.json
Then run:
aris-homepage finalize
…to persist the structured fields into profile.yml + publications.bib + bio.md + news.md.
## Extraction prompt template (use as a starting point)
> You are extracting structured data from an academic CV for a homepage generator.
> Read the CV text from {txt_path.name}. Emit valid JSON matching extraction.schema.json.
>
> **Rules:**
> - Use field names from the schema verbatim (no synonyms).
> - For each publication, generate a unique bibkey of the form `lastname{{year}}{{keyword}}`
> (e.g., yang2024fewshot). Bibkeys MUST be valid BibTeX keys (no spaces, no special chars).
> - In bibtex_entries, emit ONE full BibTeX entry per paper, comma-separated within each entry.
> - Bio prose goes in bio_md (Markdown). Keep it 1-3 paragraphs, third-person OR first-person.
> - News goes in news_md as bullets prefixed with date: `- 2026-05: Joined NUS as intern`.
> - For uncertain claims (e.g., guessed dates, inferred awards), add them to `uncertain[]`
> with a note. These will become checklist items in EXTRACTION_REVIEW.md.
> - Do NOT invent claims. If the CV doesn't say something, leave the field null/empty.
> - Identify the CV owner. Their name goes in profile.identity.name + name_native (if bilingual).
{('> - If github_repos.json exists, merge its timeline into news_md following the rules in the section above.' + chr(10)) if repos_block else ''}>
> After writing the JSON, instruct the user to run `aris-homepage finalize`.
""", encoding="utf-8")
print(f"✓ CV text extracted to: {txt_path}")
print(f"✓ Extraction handoff written to: {handoff_path}")
print()
print("Next: read the handoff doc and fill .aris-homepage/extraction.json,")
print(" then run `aris-homepage finalize` to persist the structured files.")
def cmd_finalize(args: argparse.Namespace) -> int:
"""Ingest .aris-homepage/extraction.json → profile.yml + publications.bib + bio.md + news.md."""
workspace = Path(args.out).resolve() if args.out else Path(".").resolve()
extraction_path = workspace / ".aris-homepage" / "extraction.json"
if not extraction_path.exists():
die(f"{extraction_path} not found. Run `aris-homepage init --from-cv ...` first, "
f"then have the calling agent fill the extraction JSON.")
data = json.loads(extraction_path.read_text(encoding="utf-8"))
profile = data.get("profile", {})
bib_text = data.get("bibtex_entries", "")
bio_md = data.get("bio_md", "")
news_md = data.get("news_md", "")
uncertain = data.get("uncertain", [])
# Persist
if not HAS_YAML:
die("pyyaml not installed. Run: pip install pyyaml --break-system-packages "
"(or use a venv).")
profile["schema_version"] = SCHEMA_VERSION
(workspace / DEFAULT_FILES["profile"]).write_text(
yaml.dump(profile, allow_unicode=True, sort_keys=False), encoding="utf-8")
(workspace / DEFAULT_FILES["bib"]).write_text(bib_text, encoding="utf-8")
if bio_md:
(workspace / DEFAULT_FILES["bio"]).write_text(bio_md, encoding="utf-8")
if news_md:
(workspace / DEFAULT_FILES["news"]).write_text(news_md, encoding="utf-8")
# Extraction review
review_lines = ["# Extraction Review", "",
"These claims were extracted from your CV but could not be auto-verified.",
"Edit the corresponding files (profile.yml, publications.bib, bio.md, news.md)",
"as needed, then run `aris-homepage render --persona theory-minimal`.", ""]
if uncertain:
review_lines.append("## ⚠️ Uncertain claims (review before rendering)")
review_lines.append("")
for u in uncertain:
review_lines.append(f"- [ ] {u}")
else:
review_lines.append("✓ No uncertain claims flagged by extraction.")
(workspace / DEFAULT_FILES["extraction_review"]).write_text(
"\n".join(review_lines) + "\n", encoding="utf-8")
print(f"✓ Wrote {DEFAULT_FILES['profile']}")
print(f"✓ Wrote {DEFAULT_FILES['bib']}")
if bio_md:
print(f"✓ Wrote {DEFAULT_FILES['bio']}")
if news_md:
print(f"✓ Wrote {DEFAULT_FILES['news']}")
print(f"✓ Wrote {DEFAULT_FILES['extraction_review']}")
print()
print("Edit the files as needed, then run:")
print(" aris-homepage render --persona theory-minimal")
return 0
# ---------------------------------------------------------------------------
# Command: render
# ---------------------------------------------------------------------------
def cmd_render(args: argparse.Namespace) -> int:
"""Render homepage HTML + audit-report.md from profile.yml + publications.bib."""
if args.persona not in PERSONAS:
die(f"Unknown persona: {args.persona}. Choose from {PERSONAS}.")
if args.persona == "active-researcher":
die("active-researcher template ships in v1.1. v1 only supports theory-minimal.")
workspace = Path(".").resolve()
profile = load_profile(workspace / DEFAULT_FILES["profile"])
bib = parse_bibtex(workspace / DEFAULT_FILES["bib"])
bio_md = read_optional(workspace / DEFAULT_FILES["bio"])
news_md = read_optional(workspace / DEFAULT_FILES["news"])
# Fact-check
audit = None
if not args.no_audit:
audit = run_fact_check(profile, bib, override_all=args.override_all, workspace=workspace)
write_audit_report(workspace / DEFAULT_FILES["audit_report"], audit, profile, args.persona)
if audit.verdict == "BLOCKED" and not args.override_all:
print(f"\n✗ Audit BLOCKED. See {DEFAULT_FILES['audit_report']}.", file=sys.stderr)
print(" Fix the failing claims OR re-run with --override-all (logged loudly).",
file=sys.stderr)
return 2
# Render
chunks = build_section_chunks(profile, bib, bio_md, news_md, persona=args.persona,
workspace=workspace)
template_path = TEMPLATES_DIR / f"homepage-{args.persona}.html"
if not template_path.exists():
die(f"Template not found: {template_path}")
template = template_path.read_text(encoding="utf-8")
html = render_template(template, chunks, profile, audit, workspace)
out_path = Path(args.out) if args.out else workspace / DEFAULT_FILES["output_html"]
out_path.write_text(html, encoding="utf-8")
print(f"✓ Rendered: {out_path} ({out_path.stat().st_size // 1024} KB)")
if audit:
print(f"✓ Audit: {audit.verdict} "
f"(PASS {len(audit.passed)} · WARN {len(audit.warned)} · "
f"FAIL {len(audit.failed)} · OVERRIDDEN {len(audit.overridden)})")
return 0
def load_profile(path: Path) -> dict[str, Any]:
"""Load + validate profile.yml. Required: schema_version, identity.name."""
if not HAS_YAML:
die("pyyaml not installed. Run: pip install pyyaml --break-system-packages")
if not path.exists():
die(f"{path} not found. Run `aris-homepage init --from-cv <cv>` first.")
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
die(f"{path}: expected a YAML mapping at top level.")
sv = data.get("schema_version")
if sv != SCHEMA_VERSION:
die(f"schema_version mismatch: file has {sv!r}, expected {SCHEMA_VERSION}.")
if not data.get("identity", {}).get("name"):
die(f"{path}: identity.name is required.")
return data
def parse_bibtex(path: Path) -> dict[str, dict[str, str]]:
"""Load publications.bib via stdlib parser."""
if not path.exists():
return {}
return parse_bibtex_str(path.read_text(encoding="utf-8"))
def read_optional(path: Path) -> str:
return path.read_text(encoding="utf-8") if path.exists() else ""
# ---------------------------------------------------------------------------
# Section chunk builders
# ---------------------------------------------------------------------------
# Each returns "" when the corresponding profile field is empty (graceful
# degradation — no LLM filler, per Gemini's risk #3).
def build_section_chunks(profile: dict, bib: dict, bio_md: str, news_md: str,
*, persona: str, workspace: Path) -> dict[str, str]:
return {
"PHOTO_HTML": build_photo_html(profile, workspace),
"PERSON_NAME": esc(profile["identity"]["name"]),
"PERSON_NAME_NATIVE_HTML": build_native_name_html(profile),
"TITLE_AFFILIATION_HTML": build_title_affil_html(profile),
"EMAIL_HTML": build_email_html(profile),
"SOCIAL_LINKS_HTML": build_social_html(profile),
"BIO_SECTION_HTML": build_bio_section(profile, bio_md),
"RESEARCH_EXPERIENCES_SECTION_HTML": build_research_experiences_section(profile),
"FEATURED_PROJECTS_SECTION_HTML": build_featured_projects_section(profile),
"RESEARCH_SECTION_HTML": build_research_section(profile),
"EDUCATION_SECTION_HTML": build_education_section(profile),
"NEWS_SECTION_HTML": build_news_section(news_md),
"PUBLICATIONS_SECTION_HTML": build_publications_section(profile, bib, persona),
"AWARDS_SECTION_HTML": build_awards_section(profile),
"TALKS_SECTION_HTML": build_talks_section(profile),
"PROFESSIONAL_SERVICES_SECTION_HTML": build_professional_services_section(profile),
"TEACHING_SECTION_HTML": build_teaching_section(profile),
"AUDIT_LINK_HTML": f" · <a href=\"{DEFAULT_FILES['audit_report']}\">audit</a>",
}
def build_photo_html(profile: dict, workspace: Path) -> str:
"""Render headshot. Supports local path (base64-inline) OR remote URL
(e.g. raw.githubusercontent.com — embeds the URL directly, no fetch)."""
photo_path_str = profile.get("identity", {}).get("photo")
if not photo_path_str:
return ""
# Remote URL — embed directly. Single-file HTML keeps the URL but doesn't fetch+inline.
if photo_path_str.startswith(("http://", "https://")):
return f'<img class="photo" src="{esc(photo_path_str)}" alt="" loading="lazy">'
# Local path — base64-inline
photo = workspace / photo_path_str
if not photo.exists():
print(f" ⚠ photo not found: {photo}", file=sys.stderr)
return ""
if photo.stat().st_size > 500_000:
print(f" ⚠ photo >500KB ({photo.stat().st_size//1024}KB), embedding anyway. "
f"Consider downscaling.", file=sys.stderr)
mime, _ = mimetypes.guess_type(photo.name)
mime = mime or "image/jpeg"
data = base64.b64encode(photo.read_bytes()).decode("ascii")
return f'<img class="photo" src="data:{mime};base64,{data}" alt="">'
def build_native_name_html(profile: dict) -> str:
native = profile.get("identity", {}).get("name_native")
if not native:
return ""
return f' <span class="name-native">{esc(native)}</span>'
def build_title_affil_html(profile: dict) -> str:
"""Render title + PRIMARY current affiliation only (single line, like manual academic pages).
Secondary affiliations (e.g., visiting positions) are intentionally NOT shown in the
masthead — they belong in the bio prose where context can be given.
"""
title = profile.get("identity", {}).get("title")
current = profile.get("affiliations", {}).get("current", []) or []
primary_parts = []
if title:
primary_parts.append(esc(title))
if current:
a = current[0]
affil_parts = [esc(a[k]) for k in ("institution", "department") if a.get(k)]
if affil_parts:
primary_parts.append(", ".join(affil_parts))
return " · ".join(primary_parts) if primary_parts else ""
def build_email_html(profile: dict) -> str:
"""Render multi-line contact block: Email + WeChat + Office (one per line).
Mirrors the manual-academic-homepage convention of stacked plain-text contact lines."""
identity = profile.get("identity", {}) or {}
lines: list[str] = []
email = identity.get("email")
wechat = identity.get("wechat")
office = identity.get("office")
if email:
lines.append(f'Email: <a href="mailto:{esc(email)}">{esc(email)}</a>')
if wechat:
lines.append(f'WeChat: {esc(wechat)}')
if office:
lines.append(f'Office: {esc(office)}')
return "<br>".join(lines)
def build_social_html(profile: dict) -> str:
"""Render social/scholar link strip. Suppresses self-referential Homepage link
(if links.homepage matches the user's GitHub Pages URL — output target)."""
links = profile.get("links", {}) or {}
suppress: set[str] = set()
homepage = links.get("homepage", "")
# Heuristic: if homepage points to <user>.github.io, it's self-referential
if homepage and (".github.io" in homepage or "github.io/" in homepage):
suppress.add("homepage")
out = []
for key, label in LINK_LABELS.items():
url = links.get(key)
if not url or key in suppress:
continue
out.append(f'<a href="{esc(url)}" rel="noopener">{label}</a>')
return "\n ".join(out)
def build_bio_section(profile: dict, bio_md: str) -> str:
body = bio_md.strip() or profile.get("research", {}).get("summary", "")
if not body:
return ""
inner = md_to_paragraphs(body) if "\n" in body or "[" in body else f"<p>{md_inline(body)}</p>"
return f'<section class="bio"><h2>Bio</h2>\n{inner}\n</section>'
def build_research_section(profile: dict) -> str:
research = profile.get("research", {}) or {}
interests = research.get("interests") or []
if not interests:
return ""
items = "\n".join(f" <li>{md_inline(str(i))}</li>" for i in interests)
return (f'<section class="research"><h2>Research Interests</h2>\n'
f'<ul>\n{items}\n</ul>\n</section>')
def build_education_section(profile: dict) -> str:
edus = profile.get("education", []) or []
if not edus:
return ""
rows = []
for e in edus:
degree = esc(e.get("degree", ""))
inst = esc(e.get("institution", ""))
adv = e.get("advisor") or []
adv_html = ""
if adv:
adv_str = ", ".join(adv) if isinstance(adv, list) else str(adv)
adv_html = f" · advised by {esc(adv_str)}"
dates = format_dates(e.get("start"), e.get("end"))
rows.append(f'<div class="edu-item"><span class="degree">{degree}'
f'{" · " + inst if inst else ""}{adv_html}</span>'
f'<span class="dates">{esc(dates)}</span></div>')
return (f'<section class="education"><h2>Education</h2>\n' +
"\n".join(rows) + "\n</section>")
def _normalize_selected_publications(selected: Any) -> list[dict]:
"""Accepts flat list OR list of {group: str, keys: [bibkey]} dicts.
Returns list of groups: [{'group': str|None, 'keys': [bibkey, ...]}, ...]."""
if not selected:
return []
if all(isinstance(x, str) for x in selected):
return [{"group": None, "keys": list(selected)}]
groups = []
for item in selected:
if isinstance(item, str):
groups.append({"group": None, "keys": [item]})
elif isinstance(item, dict):
groups.append({"group": item.get("group"), "keys": item.get("keys", [])})
return groups
def build_publications_section(profile: dict, bib: dict, persona: str) -> str:
selected = profile.get("selected_publications") or []
if not selected:
return ""
groups = _normalize_selected_publications(selected)
meta = profile.get("publications_meta", {}) or {}
user_name = profile.get("identity", {}).get("name", "")
name_tokens = [t.lower() for t in re.findall(r"\w+", user_name) if t]
preamble = (profile.get("publications", {}) or {}).get("preamble", "")
missing: list[str] = []
section_chunks: list[str] = []
def render_paper_row(bibkey: str) -> str:
if bibkey not in bib:
missing.append(bibkey)
return ""
entry = bib[bibkey]
m = meta.get(bibkey, {}) or {}
spotlight_cls = " pub-spotlight" if m.get("spotlight") else ""
title = esc(entry.get("title", "(untitled)"))
authors_str = render_authors(entry.get("author", ""), name_tokens,
co_first=m.get("co_first"))
venue = render_venue(entry)
link_html_parts = []
plinks = m.get("links", {}) or {}
# Known link types in canonical display order.
# User flagged "abs" as too cryptic when the link is just the paper — use "Paper" / "arXiv".
known_link_order = [
("paper", "Paper"),
("arxiv", "arXiv"),
("pdf", "PDF"),
("openreview", "OpenReview"),
("project", "Project"),
("code", "Code"),
("slides", "Slides"),
("talk_slides", "Talk Slides"),
("html_intro", "Intro"),
("html", "HTML"),
("video", "Video"),
("poster", "Poster"),
("paperweekly", "PaperWeekly"),
("bibtex", "BibTeX"),
]
seen_link_keys: set[str] = set()
for key, label in known_link_order:
url = plinks.get(key)
if url:
link_html_parts.append(f'<a href="{esc(url)}" rel="noopener">[{label}]</a>')
seen_link_keys.add(key)
# Custom/unknown keys keep their key name as label
for key, url in plinks.items():
if key in seen_link_keys or not url:
continue
link_html_parts.append(f'<a href="{esc(url)}" rel="noopener">[{esc(key)}]</a>')
# Awards/badges — support both singular `award: str` (back-compat) and plural `awards: [str]`
award_items: list[str] = []
if m.get("awards"):
award_items = [str(a) for a in m["awards"] if a]
elif m.get("award"):
award_items = [str(m["award"])]
award_html = "".join(f'<span class="pub-badge">{esc(a)}</span>' for a in award_items)
links_html = (f'<div class="pub-links">{"".join(link_html_parts)}{award_html}</div>'
if link_html_parts or award_items else "")
description = m.get("description", "")
description_html = (f'<div class="pub-description">{md_inline(description)}</div>'
if description else "")
content_html = (f'<div class="pub-title">{title}</div>'
f'<div class="pub-authors">{authors_str}</div>'
f'<div class="pub-venue">{venue}</div>'
f'{links_html}')
# 2-column layout when thumbnail provided. Description renders FULL-WIDTH
# below the thumb+content row via CSS grid-template-areas — matches the
# DFS-GRPO single-column treatment but kept inside the 2-col grid.
thumb = m.get("thumbnail")
if thumb:
thumb_html = (f'<div class="pub-thumb-wrap">'
f'<img class="pub-thumb" src="{esc(thumb)}" alt="" loading="lazy">'
f'</div>')
return (f'<div class="pub-item pub-item-with-thumb{spotlight_cls}">'
f'{thumb_html}<div class="pub-content">{content_html}</div>'
f'{description_html}</div>')
return f'<div class="pub-item{spotlight_cls}">{content_html}{description_html}</div>'
for group in groups:
if group["group"]:
section_chunks.append(f'<h3 class="pub-group">{esc(group["group"])}</h3>')
for bibkey in group["keys"]:
row = render_paper_row(bibkey)
if row:
section_chunks.append(row)
if missing:
print(f" ⚠ {len(missing)} bibkey(s) in selected_publications not found in .bib: "
f"{', '.join(missing)}", file=sys.stderr)
# Scholar deflection