|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Convert docs/references.bib to docs/bibliography.md. |
| 3 | +
|
| 4 | +Usage: |
| 5 | + uv run python docs/bib2md.py [--bib PATH] [--out PATH] |
| 6 | +
|
| 7 | +The BibTeX file is the source of truth; run this script whenever it changes. |
| 8 | +""" |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import argparse |
| 12 | +import re |
| 13 | +import sys |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +# --------------------------------------------------------------------------- |
| 17 | +# Parser |
| 18 | +# --------------------------------------------------------------------------- |
| 19 | + |
| 20 | +_ENTRY_RE = re.compile( |
| 21 | + r"@(\w+)\s*\{\s*([\w][\w:/-]*)\s*,\s*(.*?)\n\}", |
| 22 | + re.DOTALL, |
| 23 | +) |
| 24 | +_FIELD_RE = re.compile( |
| 25 | + r"""(\w+)\s*=\s*(?:\{((?:[^{}]|\{[^{}]*\})*)\}|"([^"]*)")""", |
| 26 | + re.DOTALL, |
| 27 | +) |
| 28 | + |
| 29 | + |
| 30 | +def _strip_braces(text: str) -> str: |
| 31 | + """Remove single-level LaTeX capitalisation braces, e.g. {Lévy} -> Lévy.""" |
| 32 | + return re.sub(r"\{([^{}]*)\}", r"\1", text) |
| 33 | + |
| 34 | + |
| 35 | +def _clean(value: str) -> str: |
| 36 | + text = _strip_braces(" ".join(value.split())) |
| 37 | + # Convert LaTeX en-dash (--) to a plain hyphen |
| 38 | + return text.replace("--", "-") |
| 39 | + |
| 40 | + |
| 41 | +def parse_bib(text: str) -> list[dict[str, str]]: |
| 42 | + entries = [] |
| 43 | + for m in _ENTRY_RE.finditer(text): |
| 44 | + entry: dict[str, str] = { |
| 45 | + "type": m.group(1).lower(), |
| 46 | + "key": m.group(2), |
| 47 | + } |
| 48 | + for fm in _FIELD_RE.finditer(m.group(3)): |
| 49 | + raw = fm.group(2) if fm.group(2) is not None else fm.group(3) |
| 50 | + entry[fm.group(1).lower()] = _clean(raw) |
| 51 | + entries.append(entry) |
| 52 | + return entries |
| 53 | + |
| 54 | + |
| 55 | +# --------------------------------------------------------------------------- |
| 56 | +# Author formatting |
| 57 | +# --------------------------------------------------------------------------- |
| 58 | + |
| 59 | +def _format_single_author(author: str) -> str: |
| 60 | + """Convert 'Lastname, Firstname' to 'Firstname Lastname'; leave others as-is.""" |
| 61 | + author = author.strip() |
| 62 | + # Only reformat if a comma is clearly separating last from first name |
| 63 | + # (avoid splitting on commas inside name suffixes or freeform strings) |
| 64 | + parts = author.split(",", 1) |
| 65 | + if len(parts) == 2: |
| 66 | + last, first = parts[0].strip(), parts[1].strip() |
| 67 | + # Sanity: last name should be a single word (no spaces) |
| 68 | + if first and " " not in last: |
| 69 | + return f"{first} {last}" |
| 70 | + return author |
| 71 | + |
| 72 | + |
| 73 | +def format_authors(author_field: str) -> str: |
| 74 | + # Normalise separators: "and" and "&" both split authors |
| 75 | + normalised = re.sub(r"\s+and\s+", " & ", author_field, flags=re.IGNORECASE) |
| 76 | + authors = [a.strip() for a in normalised.split("&") if a.strip()] |
| 77 | + return ", ".join(_format_single_author(a) for a in authors) |
| 78 | + |
| 79 | + |
| 80 | +# --------------------------------------------------------------------------- |
| 81 | +# Entry formatter |
| 82 | +# --------------------------------------------------------------------------- |
| 83 | + |
| 84 | +def _title_link(title: str, url: str) -> str: |
| 85 | + if not url: |
| 86 | + return title |
| 87 | + return f'[{title}]({url}){{target="_blank" rel="noopener"}}' |
| 88 | + |
| 89 | + |
| 90 | +def _journal_detail(entry: dict[str, str]) -> str: |
| 91 | + """Build 'Journal, Vol(Num):Pages' string.""" |
| 92 | + journal = entry.get("journal", "") |
| 93 | + volume = entry.get("volume", "") |
| 94 | + number = entry.get("number", "") |
| 95 | + pages = entry.get("pages", "") |
| 96 | + if not journal: |
| 97 | + return "" |
| 98 | + detail = journal |
| 99 | + if volume: |
| 100 | + vol_str = volume |
| 101 | + if number: |
| 102 | + vol_str += f"({number})" |
| 103 | + if pages: |
| 104 | + vol_str += f":{pages}" |
| 105 | + detail += f", {vol_str}" |
| 106 | + elif pages: |
| 107 | + detail += f", {pages}" |
| 108 | + return detail |
| 109 | + |
| 110 | + |
| 111 | +def format_entry(entry: dict[str, str]) -> str: |
| 112 | + key = entry["key"] |
| 113 | + title = entry.get("title", "Unknown Title") |
| 114 | + year = entry.get("year", "") |
| 115 | + url = entry.get("url", "") |
| 116 | + author = entry.get("author", "") |
| 117 | + |
| 118 | + # Prefer doi as url when no url field present |
| 119 | + if not url and "doi" in entry: |
| 120 | + doi = entry["doi"].lstrip("doi:") |
| 121 | + url = f"https://doi.org/{doi}" |
| 122 | + |
| 123 | + author_str = format_authors(author) if author else "" |
| 124 | + title_md = _title_link(title, url) |
| 125 | + year_str = f"({year})" if year else "" |
| 126 | + |
| 127 | + # Prefix: "Author(s). (Year)" |
| 128 | + prefix_parts = [] |
| 129 | + if author_str: |
| 130 | + prefix_parts.append(author_str.rstrip(".") + ".") |
| 131 | + if year_str: |
| 132 | + prefix_parts.append(year_str) |
| 133 | + prefix = " ".join(prefix_parts) |
| 134 | + |
| 135 | + # Suffix depends on entry type |
| 136 | + entry_type = entry.get("type", "article") |
| 137 | + if entry_type == "article": |
| 138 | + suffix = _journal_detail(entry) |
| 139 | + elif entry_type == "book": |
| 140 | + suffix = entry.get("publisher", "") |
| 141 | + elif entry_type in ("mastersthesis", "phdthesis"): |
| 142 | + suffix = entry.get("school", "") |
| 143 | + else: |
| 144 | + suffix = entry.get("publisher", entry.get("school", "")) |
| 145 | + |
| 146 | + body = f"{prefix} {title_md}" if prefix else title_md |
| 147 | + if suffix: |
| 148 | + body = f"{body}, {suffix}" |
| 149 | + |
| 150 | + return f"#### {key}\n\n{body}\n" |
| 151 | + |
| 152 | + |
| 153 | +# --------------------------------------------------------------------------- |
| 154 | +# Main |
| 155 | +# --------------------------------------------------------------------------- |
| 156 | + |
| 157 | +def convert(bib_path: Path, out_path: Path) -> None: |
| 158 | + text = bib_path.read_text(encoding="utf-8") |
| 159 | + entries = parse_bib(text) |
| 160 | + if not entries: |
| 161 | + print(f"No entries found in {bib_path}", file=sys.stderr) |
| 162 | + sys.exit(1) |
| 163 | + |
| 164 | + entries.sort(key=lambda e: e["key"].lower()) |
| 165 | + |
| 166 | + lines = ["# Bibliography\n", "\n---\n"] |
| 167 | + for entry in entries: |
| 168 | + lines.append("\n") |
| 169 | + lines.append(format_entry(entry)) |
| 170 | + |
| 171 | + out_path.write_text("".join(lines), encoding="utf-8") |
| 172 | + print(f"Wrote {len(entries)} entries to {out_path}") |
| 173 | + |
| 174 | + |
| 175 | +def main() -> None: |
| 176 | + docs = Path(__file__).parent |
| 177 | + parser = argparse.ArgumentParser(description=__doc__) |
| 178 | + parser.add_argument( |
| 179 | + "--bib", |
| 180 | + type=Path, |
| 181 | + default=docs / "references.bib", |
| 182 | + help="Input BibTeX file (default: docs/references.bib)", |
| 183 | + ) |
| 184 | + parser.add_argument( |
| 185 | + "--out", |
| 186 | + type=Path, |
| 187 | + default=docs / "bibliography.md", |
| 188 | + help="Output Markdown file (default: docs/bibliography.md)", |
| 189 | + ) |
| 190 | + args = parser.parse_args() |
| 191 | + convert(args.bib, args.out) |
| 192 | + |
| 193 | + |
| 194 | +if __name__ == "__main__": |
| 195 | + main() |
0 commit comments