academicflow 0.1.0.dev0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/.gitignore +6 -0
  2. academicflow-0.2.0/CHANGELOG.md +35 -0
  3. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/PKG-INFO +2 -2
  4. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/README.md +1 -1
  5. academicflow-0.2.0/examples/README.md +41 -0
  6. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/pyproject.toml +4 -0
  7. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/__init__.py +1 -1
  8. academicflow-0.2.0/src/academicflow/cite/bib.py +194 -0
  9. academicflow-0.2.0/src/academicflow/cite/styles.py +212 -0
  10. academicflow-0.2.0/src/academicflow/core/text.py +222 -0
  11. academicflow-0.2.0/src/academicflow/export/__init__.py +86 -0
  12. academicflow-0.2.0/src/academicflow/export/__main__.py +24 -0
  13. academicflow-0.2.0/src/academicflow/export/common.py +183 -0
  14. academicflow-0.2.0/src/academicflow/export/docx.py +162 -0
  15. academicflow-0.2.0/src/academicflow/export/latex.py +105 -0
  16. academicflow-0.2.0/src/academicflow/export/notebook.py +136 -0
  17. academicflow-0.2.0/src/academicflow/export/templates/article.tex +27 -0
  18. academicflow-0.2.0/src/academicflow/magics/__init__.py +18 -0
  19. academicflow-0.2.0/src/academicflow/magics/display.py +177 -0
  20. academicflow-0.2.0/src/academicflow/magics/magics.py +246 -0
  21. academicflow-0.2.0/src/academicflow/magics/session.py +145 -0
  22. academicflow-0.2.0/src/academicflow/summarize/__init__.py +15 -0
  23. academicflow-0.2.0/src/academicflow/summarize/extractive.py +309 -0
  24. academicflow-0.2.0/src/academicflow/summarize/llm.py +119 -0
  25. academicflow-0.2.0/tests/test_cite.py +179 -0
  26. academicflow-0.2.0/tests/test_core.py +111 -0
  27. academicflow-0.2.0/tests/test_export.py +206 -0
  28. academicflow-0.2.0/tests/test_magics.py +313 -0
  29. academicflow-0.2.0/tests/test_summarize.py +207 -0
  30. academicflow-0.1.0.dev0/CHANGELOG.md +0 -11
  31. academicflow-0.1.0.dev0/src/academicflow/cite/bib.py +0 -64
  32. academicflow-0.1.0.dev0/src/academicflow/cite/styles.py +0 -15
  33. academicflow-0.1.0.dev0/src/academicflow/core/text.py +0 -60
  34. academicflow-0.1.0.dev0/src/academicflow/export/__init__.py +0 -58
  35. academicflow-0.1.0.dev0/src/academicflow/magics/__init__.py +0 -18
  36. academicflow-0.1.0.dev0/src/academicflow/magics/display.py +0 -30
  37. academicflow-0.1.0.dev0/src/academicflow/magics/magics.py +0 -86
  38. academicflow-0.1.0.dev0/src/academicflow/magics/session.py +0 -49
  39. academicflow-0.1.0.dev0/src/academicflow/summarize/__init__.py +0 -10
  40. academicflow-0.1.0.dev0/src/academicflow/summarize/extractive.py +0 -38
  41. academicflow-0.1.0.dev0/src/academicflow/summarize/llm.py +0 -14
  42. academicflow-0.1.0.dev0/tests/test_cite.py +0 -24
  43. academicflow-0.1.0.dev0/tests/test_core.py +0 -17
  44. academicflow-0.1.0.dev0/tests/test_export.py +0 -12
  45. academicflow-0.1.0.dev0/tests/test_magics.py +0 -22
  46. academicflow-0.1.0.dev0/tests/test_summarize.py +0 -11
  47. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/LICENSE +0 -0
  48. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/cite/__init__.py +0 -0
  49. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/cite/integrity.py +0 -0
  50. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/cite/render.py +0 -0
  51. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/core/__init__.py +0 -0
  52. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/core/data/stopwords.txt +0 -0
  53. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/core/keywords.py +0 -0
  54. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/core/passive.py +0 -0
  55. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/core/readability.py +0 -0
  56. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/profiles/__init__.py +0 -0
  57. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/profiles/apa.yaml +0 -0
  58. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/profiles/ieee.yaml +0 -0
  59. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/profiles/nature.yaml +0 -0
  60. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/style/__init__.py +0 -0
  61. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/style/data/informal.yaml +0 -0
  62. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/style/profiles.py +0 -0
  63. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/style/rules.py +0 -0
  64. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/style/terminology.py +0 -0
  65. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/src/academicflow/types.py +0 -0
  66. {academicflow-0.1.0.dev0 → academicflow-0.2.0}/tests/test_style.py +0 -0
@@ -221,3 +221,9 @@ __marimo__/
221
221
 
222
222
  # Streamlit
223
223
  .streamlit/secrets.toml
224
+
225
+ # macOS Finder files
226
+ .DS_Store
227
+
228
+ # Files produced by running the example notebooks
229
+ examples/paper.*
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. Versions follow [Semantic Versioning](https://semver.org/).
4
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.2.0] - 2026-11-20
8
+
9
+ First public release.
10
+
11
+ ### Added
12
+ - **Text analysis** (`academicflow.core`): sentence splitter that handles abbreviations,
13
+ decimals and citations; tokenizer; markdown stripper.
14
+ - **Citations** (`academicflow.cite`): BibTeX parsing with LaTeX accent clean-up and clear
15
+ error messages; APA 7, IEEE and Nature reference formatting for journal articles.
16
+ - **Abstract generator** (`academicflow.summarize`): TextRank extractive summaries,
17
+ section-aware abstracts, and an optional OpenAI-compatible LLM backend (works with
18
+ Ollama) that falls back to TextRank.
19
+ - **Jupyter magics** (`academicflow.magics`): `%load_ext academicflow`, `%acite`,
20
+ `%%academic`, `%astats`, `%acheck`, `%aabstract`, `%aexport`, with a notebook session.
21
+ - **Export** (`academicflow.export`): Word (.docx), LaTeX (.tex) and Markdown export,
22
+ `export_notebook()` and a command-line entry point.
23
+ - **Examples**: quickstart notebook, full paper workflow notebook, and a sample draft with
24
+ deliberate mistakes and an answer key.
25
+ - **Docs**: MkDocs site with one page per module.
26
+ - **Infrastructure**: CI on Python 3.10-3.13, PyPI trusted publishing on tags, docs
27
+ deployment to GitHub Pages.
28
+
29
+ ### Changed
30
+ - Python 3.10 or newer is required (3.9 reached end of life).
31
+
32
+ ### Coming next
33
+ - Style checker with section-aware rules, terminology consistency and venue profiles.
34
+ - Reference formatting for conference papers, books and other entry types.
35
+ - Citation integrity checks and inline citation rendering.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: academicflow
3
- Version: 0.1.0.dev0
3
+ Version: 0.2.0
4
4
  Summary: An academic-writing pipeline for Jupyter: text analysis, style checks, BibTeX citations (APA/IEEE/Nature), abstract generation, and LaTeX/Word export.
5
5
  Project-URL: Homepage, https://github.com/zhannurkali/academicflow
6
6
  Project-URL: Documentation, https://zhannurkali.github.io/academicflow/
@@ -57,7 +57,7 @@ An academic-writing pipeline for Jupyter notebooks: text analysis, section-aware
57
57
  terminology consistency, BibTeX citations in APA / IEEE / Nature style, abstract generation,
58
58
  and one-command export to Word or LaTeX.
59
59
 
60
- > Status: early development (4-day team project). APIs may change before 1.0.
60
+ > Status: beta (0.2.0). APIs may change before 1.0.
61
61
 
62
62
  ## Install
63
63
 
@@ -9,7 +9,7 @@ An academic-writing pipeline for Jupyter notebooks: text analysis, section-aware
9
9
  terminology consistency, BibTeX citations in APA / IEEE / Nature style, abstract generation,
10
10
  and one-command export to Word or LaTeX.
11
11
 
12
- > Status: early development (4-day team project). APIs may change before 1.0.
12
+ > Status: beta (0.2.0). APIs may change before 1.0.
13
13
 
14
14
  ## Install
15
15
 
@@ -0,0 +1,41 @@
1
+ # Examples
2
+
3
+ | File | What it shows |
4
+ | --- | --- |
5
+ | `01_quickstart.ipynb` | Every feature through the Python API, in a few cells |
6
+ | `02_full_paper_workflow.ipynb` | The full demo: write a paper with magics, check it, generate an abstract, export it |
7
+ | `sample_draft.md` | The same paper as plain Markdown, for tests and scripts |
8
+ | `refs.bib` | Bibliography used by both notebooks |
9
+
10
+ Run them on JupyterHub:
11
+
12
+ ```bash
13
+ pip install academicflow
14
+ cd examples
15
+ jupyter lab
16
+ ```
17
+
18
+ ## Deliberate mistakes in the sample paper
19
+
20
+ The sample paper is written badly on purpose, so every checker has something to find.
21
+ Use this table as the answer key when you test your module.
22
+
23
+ | Section | Mistake | Expected issue |
24
+ | --- | --- | --- |
25
+ | abstract | About 240 words: over the Nature limit (200 words) | style: abstract-length |
26
+ | abstract | Contains a citation `[@vaswani2017]` | style: citation-in-abstract |
27
+ | abstract | Informal phrases: *a lot of*, *get stuck* | style: informal-word |
28
+ | introduction | Informal words: *a lot of*, *get*, *basically*, *stuff*, *really*, *obviously* | style: informal-word / hedge |
29
+ | introduction | Contractions: *don't*, *it's* | style: contraction |
30
+ | introduction | Repeated word: *the the* | style: repeated-word |
31
+ | introduction | `NLP` used before it is defined | style: acronym-undefined |
32
+ | introduction | Misspelled citation key `[@vaswani2071]` (should be `vaswani2017`) | cite: cite-missing-key |
33
+ | introduction + methods + results | *data set* / *dataset* / *data-set* | style: term-inconsistency |
34
+ | introduction + methods | `LLM` defined twice | style: acronym-redefined |
35
+ | methods | Present tense: *We use*, *We propose* | style: tense (methods: past) |
36
+ | methods | Second sentence is over 60 words | style: long-sentence |
37
+ | results | *The style checker found* repeated 3 times | style: repeated-phrase |
38
+ | conclusion | Informal words: *pretty*, *big* | style: informal-word |
39
+
40
+ If you add a rule, add a matching mistake to the sample paper (in `sample_draft.md`
41
+ and in both notebooks) and a row to this table, so the demo shows it.
@@ -75,3 +75,7 @@ target-version = "py310"
75
75
  [tool.ruff.lint]
76
76
  select = ["E", "F", "W", "I", "UP", "B"]
77
77
  ignore = ["UP007", "UP045"]
78
+
79
+ [tool.ruff.lint.per-file-ignores]
80
+ # Example notebooks contain long sample paragraphs on purpose.
81
+ "*.ipynb" = ["E501"]
@@ -10,7 +10,7 @@ Quick start in a notebook::
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
- __version__ = "0.1.0.dev0"
13
+ __version__ = "0.2.0"
14
14
 
15
15
  from academicflow.cite import Bibliography, check_integrity, find_citations, render
16
16
  from academicflow.core import analyze
@@ -0,0 +1,194 @@
1
+ """BibTeX loading and normalisation for academicflow.cite."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import unicodedata
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from pybtex.database import BibliographyData, parse_file, parse_string
11
+ from pybtex.exceptions import PybtexError
12
+
13
+ # Combining marks for LaTeX accent commands such as \" \' \` \^ \~ \= \. \c \v \u \H \k
14
+ _ACCENTS = {
15
+ '"': "\u0308", "'": "\u0301", "`": "\u0300", "^": "\u0302", "~": "\u0303",
16
+ "=": "\u0304", ".": "\u0307", "c": "\u0327", "v": "\u030c", "u": "\u0306",
17
+ "H": "\u030b", "k": "\u0328",
18
+ } # fmt: skip
19
+
20
+ _SPECIALS = {
21
+ r"\ss": "ß", r"\o": "ø", r"\O": "Ø", r"\aa": "å", r"\AA": "Å",
22
+ r"\ae": "æ", r"\AE": "Æ", r"\l": "ł", r"\L": "Ł",
23
+ } # fmt: skip
24
+
25
+ _ESCAPES = {r"\&": "&", r"\%": "%", r"\_": "_", r"\#": "#", r"\$": "$"}
26
+
27
+ _PUNCT_ACCENT = re.compile(r"\\([`'^\"~=.])\s*(?:\{\s*([A-Za-z])\s*\}|([A-Za-z]))")
28
+ _LETTER_ACCENT = re.compile(r"\\([cvuHk])\s*(?:\{\s*([A-Za-z])\s*\}|\s([A-Za-z]))")
29
+ _DOTLESS_I = re.compile(r"\\i(?![A-Za-z])")
30
+
31
+
32
+ def clean_latex(text: str) -> str:
33
+ """Convert a BibTeX field value to plain Unicode text.
34
+
35
+ Handles common LaTeX accents (``{\\"o}`` -> ``ö``), escaped symbols (``\\&``),
36
+ and removes protective braces.
37
+
38
+ Args:
39
+ text: Raw BibTeX field value.
40
+
41
+ Returns:
42
+ Cleaned text with collapsed whitespace.
43
+ """
44
+ out = _DOTLESS_I.sub("i", text)
45
+ out = _PUNCT_ACCENT.sub(lambda m: (m.group(2) or m.group(3)) + _ACCENTS[m.group(1)], out)
46
+ out = _LETTER_ACCENT.sub(lambda m: (m.group(2) or m.group(3)) + _ACCENTS[m.group(1)], out)
47
+ for src, dst in _SPECIALS.items():
48
+ out = re.sub(re.escape(src) + r"(?![A-Za-z])", dst, out)
49
+ for src, dst in _ESCAPES.items():
50
+ out = out.replace(src, dst)
51
+ out = out.replace("{", "").replace("}", "").replace("~", " ")
52
+ out = unicodedata.normalize("NFC", out)
53
+ return re.sub(r"\s+", " ", out).strip()
54
+
55
+
56
+ def _normalise_pages(pages: str) -> str:
57
+ return re.sub(r"\s*(?:--|-|\u2013|\u2014)\s*", "\u2013", pages)
58
+
59
+
60
+ def _normalise_entry(key: str, entry: Any) -> dict[str, Any]:
61
+ fields = entry.fields
62
+ authors: list[tuple[str, str]] = []
63
+ et_al = False
64
+ for person in entry.persons.get("author", []):
65
+ if str(person).strip() == "others":
66
+ et_al = True
67
+ continue
68
+ first = clean_latex(" ".join(person.first_names + person.middle_names))
69
+ last = clean_latex(" ".join(person.prelast_names + person.last_names))
70
+ if person.lineage_names:
71
+ last = f"{last} {clean_latex(' '.join(person.lineage_names))}"
72
+ authors.append((first, last))
73
+
74
+ def get(name: str) -> str:
75
+ return clean_latex(fields.get(name, ""))
76
+
77
+ doi = get("doi")
78
+ doi = re.sub(r"^https?://(dx\.)?doi\.org/", "", doi, flags=re.IGNORECASE)
79
+ return {
80
+ "key": key,
81
+ "type": entry.type.lower(),
82
+ "authors": authors,
83
+ "et_al": et_al,
84
+ "title": get("title"),
85
+ "year": get("year"),
86
+ "journal": get("journal") or get("journaltitle"),
87
+ "booktitle": get("booktitle"),
88
+ "volume": get("volume"),
89
+ "number": get("number") or get("issue"),
90
+ "pages": _normalise_pages(get("pages")),
91
+ "publisher": get("publisher"),
92
+ "doi": doi,
93
+ "url": get("url"),
94
+ }
95
+
96
+
97
+ class Bibliography:
98
+ """A set of normalised BibTeX entries.
99
+
100
+ Each entry is a dict with keys: key, type, authors [(first, last)], et_al, title,
101
+ year, journal, booktitle, volume, number, pages, publisher, doi, url.
102
+ Missing fields are empty strings.
103
+ """
104
+
105
+ def __init__(self, entries: dict[str, dict[str, Any]] | None = None) -> None:
106
+ self._entries: dict[str, dict[str, Any]] = dict(entries or {})
107
+
108
+ @classmethod
109
+ def from_string(cls, bibtex: str) -> Bibliography:
110
+ """Parse BibTeX text.
111
+
112
+ Args:
113
+ bibtex: BibTeX source.
114
+
115
+ Returns:
116
+ A Bibliography.
117
+
118
+ Raises:
119
+ ValueError: If the BibTeX is malformed (message includes the line number).
120
+ """
121
+ try:
122
+ data = parse_string(bibtex, "bibtex")
123
+ except PybtexError as exc:
124
+ raise cls._parse_error(exc, None) from exc
125
+ return cls._from_data(data)
126
+
127
+ @classmethod
128
+ def from_file(cls, path: str | Path) -> Bibliography:
129
+ """Parse a .bib file.
130
+
131
+ Args:
132
+ path: Path to the file.
133
+
134
+ Returns:
135
+ A Bibliography.
136
+
137
+ Raises:
138
+ FileNotFoundError: If the file does not exist.
139
+ ValueError: If the BibTeX is malformed (message includes the line number).
140
+ """
141
+ p = Path(path)
142
+ if not p.is_file():
143
+ raise FileNotFoundError(f"BibTeX file not found: {p}")
144
+ try:
145
+ data = parse_file(str(p), "bibtex")
146
+ except PybtexError as exc:
147
+ raise cls._parse_error(exc, p.name) from exc
148
+ return cls._from_data(data)
149
+
150
+ @staticmethod
151
+ def _parse_error(exc: Exception, name: str | None) -> ValueError:
152
+ line = getattr(exc, "lineno", None)
153
+ where = f"{name}, " if name else ""
154
+ where += f"line {line}" if line else "unknown line"
155
+ return ValueError(f"Invalid BibTeX ({where}): {getattr(exc, 'message', exc)}")
156
+
157
+ @classmethod
158
+ def _from_data(cls, data: BibliographyData) -> Bibliography:
159
+ return cls({key: _normalise_entry(key, e) for key, e in data.entries.items()})
160
+
161
+ def keys(self) -> list[str]:
162
+ """Return entry keys in file order."""
163
+ return list(self._entries)
164
+
165
+ def get(self, key: str) -> dict[str, Any]:
166
+ """Return the normalised entry for ``key``.
167
+
168
+ Raises:
169
+ KeyError: With a readable message if the key is unknown.
170
+ """
171
+ try:
172
+ return self._entries[key]
173
+ except KeyError:
174
+ raise KeyError(f"Unknown citation key: '{key}' (not in the loaded .bib)") from None
175
+
176
+ def __contains__(self, key: object) -> bool:
177
+ return key in self._entries
178
+
179
+ def __len__(self) -> int:
180
+ return len(self._entries)
181
+
182
+ def format_reference(self, key: str, style: str) -> str:
183
+ """Format one reference as markdown.
184
+
185
+ Args:
186
+ key: Citation key.
187
+ style: "apa", "ieee" or "nature".
188
+
189
+ Returns:
190
+ The formatted reference (markdown italics/bold).
191
+ """
192
+ from .styles import format_reference # lazy: styles.py is written after bib.py
193
+
194
+ return format_reference(self.get(key), style)
@@ -0,0 +1,212 @@
1
+ """Reference formatters (APA 7, IEEE, Nature) for academicflow.cite.
2
+
3
+ Output is markdown (``*italic*``, ``**bold**``). The reference number ("[1]", "1.") is NOT
4
+ included: ``render()`` adds it, because numbering depends on order of first citation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Callable
11
+ from typing import Any
12
+
13
+ _INITIALS_TOKEN = re.compile(r"(?:[^\W\d_]\.)+")
14
+
15
+
16
+ def _initials(first: str) -> str:
17
+ """Turn "John Alan" into "J. A." and "Jean-Paul" into "J.-P."."""
18
+ out: list[str] = []
19
+ for token in first.split():
20
+ if _INITIALS_TOKEN.fullmatch(token): # already initials, e.g. "J." or "J.A."
21
+ out.extend(token[i : i + 2] for i in range(0, len(token), 2))
22
+ else:
23
+ out.append("-".join(p[0].upper() + "." for p in token.split("-") if p))
24
+ return " ".join(out)
25
+
26
+
27
+ def _end(text: str) -> str:
28
+ """Add a final period unless the text already ends with . ? or !."""
29
+ return text if not text or text[-1] in ".?!" else text + "."
30
+
31
+
32
+ def _sentence_case(title: str) -> str:
33
+ """Convert a Title Case title to sentence case; leave other titles untouched.
34
+
35
+ Conservative: only converts when every longer word (4+ letters, after the first word
36
+ and after a colon) is capitalised. Acronyms and mixed-case words (BERT, iPhone) are
37
+ kept. Known limitation: proper nouns in a Title Case title (e.g. "Python") are
38
+ lowercased, because the BibTeX braces that protect them are already stripped.
39
+ """
40
+ words = title.split(" ")
41
+ positions = [
42
+ i
43
+ for i, w in enumerate(words)
44
+ if i > 0 and not words[i - 1].endswith(":") and len(w) > 3 and not w.isupper()
45
+ ]
46
+
47
+ def is_cap(w: str) -> bool:
48
+ return w[:1].isupper() and w[1:].islower()
49
+
50
+ if not positions or not all(is_cap(words[i]) for i in positions):
51
+ return title
52
+ for i in range(1, len(words)):
53
+ if not words[i - 1].endswith(":") and is_cap(words[i]):
54
+ words[i] = words[i].lower()
55
+ return " ".join(words)
56
+
57
+
58
+ # ---------------------------------------------------------------- APA 7
59
+
60
+
61
+ def _apa_authors(e: dict[str, Any]) -> str:
62
+ names = []
63
+ for first, last in e["authors"]:
64
+ ini = _initials(first)
65
+ names.append(f"{last}, {ini}" if ini else last)
66
+ if not names:
67
+ return ""
68
+ if e.get("et_al"):
69
+ return ", ".join(names) + ", et al."
70
+ if len(names) == 1:
71
+ return names[0]
72
+ if len(names) <= 20:
73
+ return ", ".join(names[:-1]) + ", & " + names[-1]
74
+ return ", ".join(names[:19]) + ", . . . " + names[-1]
75
+
76
+
77
+ def _apa(e: dict[str, Any]) -> str:
78
+ authors = _apa_authors(e)
79
+ year = e["year"] or "n.d."
80
+ title = _end(_sentence_case(e["title"]))
81
+ out = f"{_end(authors)} ({year}). {title}" if authors else f"{title} ({year})."
82
+
83
+ vol = f"*{e['volume']}*" if e["volume"] else ""
84
+ if e["number"]:
85
+ vol += f"({e['number']})"
86
+ journal = f"*{e['journal']}*" if e["journal"] else ""
87
+ source = ", ".join(p for p in (journal, vol, e["pages"]) if p)
88
+ if source:
89
+ out += f" {source}."
90
+ link = f"https://doi.org/{e['doi']}" if e["doi"] else e["url"]
91
+ if link:
92
+ out += f" {link}"
93
+ return out
94
+
95
+
96
+ # ---------------------------------------------------------------- IEEE
97
+
98
+
99
+ def _ieee_authors(e: dict[str, Any]) -> str:
100
+ names = [f"{_initials(f)} {last}".strip() for f, last in e["authors"]]
101
+ if not names:
102
+ return ""
103
+ if e.get("et_al") or len(names) > 6:
104
+ return f"{names[0]} et al."
105
+ if len(names) == 1:
106
+ return names[0]
107
+ if len(names) == 2:
108
+ return f"{names[0]} and {names[1]}"
109
+ return ", ".join(names[:-1]) + ", and " + names[-1]
110
+
111
+
112
+ def _ieee(e: dict[str, Any]) -> str:
113
+ authors = _ieee_authors(e)
114
+ title = e["title"]
115
+ pages = ""
116
+ if e["pages"]:
117
+ pages = ("pp. " if "\u2013" in e["pages"] else "p. ") + e["pages"]
118
+ rest = [
119
+ f"*{e['journal']}*" if e["journal"] else "",
120
+ f"vol. {e['volume']}" if e["volume"] else "",
121
+ f"no. {e['number']}" if e["number"] else "",
122
+ pages,
123
+ e["year"],
124
+ f"doi: {e['doi']}" if e["doi"] else "",
125
+ ]
126
+ rest = [p for p in rest if p]
127
+ head = f'{authors}, "{title},"' if authors else f'"{title},"'
128
+ if not rest:
129
+ return head[:-2] + '."'
130
+ return f"{head} {', '.join(rest)}."
131
+
132
+
133
+ # ---------------------------------------------------------------- Nature
134
+
135
+
136
+ def _nature_authors(e: dict[str, Any]) -> str:
137
+ names = []
138
+ for first, last in e["authors"]:
139
+ ini = _initials(first)
140
+ names.append(f"{last}, {ini}" if ini else last)
141
+ if not names:
142
+ return ""
143
+ if e.get("et_al") or len(names) > 5:
144
+ return f"{names[0]} et al."
145
+ if len(names) == 1:
146
+ return names[0]
147
+ if len(names) == 2:
148
+ return f"{names[0]} & {names[1]}"
149
+ return ", ".join(names[:-1]) + " & " + names[-1]
150
+
151
+
152
+ def _nature(e: dict[str, Any]) -> str:
153
+ authors = _nature_authors(e)
154
+ out = f"{_end(authors)} " if authors else ""
155
+ out += _end(_sentence_case(e["title"]))
156
+ source = f"*{e['journal']}*" if e["journal"] else ""
157
+ if e["volume"]:
158
+ source += f" **{e['volume']}**"
159
+ if e["pages"]:
160
+ source += f", {e['pages']}" if source else e["pages"]
161
+ if e["year"]:
162
+ source += f" ({e['year']})"
163
+ return f"{out} {source.strip()}." if source.strip() else out
164
+
165
+
166
+ _FORMATTERS: dict[str, Callable[[dict[str, Any]], str]] = {
167
+ "apa": _apa,
168
+ "ieee": _ieee,
169
+ "nature": _nature,
170
+ }
171
+
172
+
173
+ def format_reference(entry: dict[str, Any], style: str) -> str:
174
+ """Format one normalised bibliography entry as a markdown reference.
175
+
176
+ Articles are fully supported. Other entry types use the article layout with the
177
+ booktitle or publisher in the journal slot (temporary fallback until Day 2).
178
+
179
+ Args:
180
+ entry: Normalised entry dict from ``Bibliography.get``.
181
+ style: "apa", "ieee" or "nature".
182
+
183
+ Returns:
184
+ The reference as markdown, without a number prefix.
185
+
186
+ Raises:
187
+ ValueError: If the style is unknown.
188
+ """
189
+ key = style.lower()
190
+ if key not in _FORMATTERS:
191
+ raise ValueError(f"Unknown citation style '{style}' (use apa, ieee or nature)")
192
+ if entry["type"] != "article":
193
+ container = entry["journal"] or entry["booktitle"] or entry["publisher"]
194
+ entry = {**entry, "journal": container}
195
+ return _FORMATTERS[key](entry)
196
+
197
+
198
+ def to_latex(markdown_ref: str) -> str:
199
+ """Convert a markdown reference to LaTeX.
200
+
201
+ Escapes ``& % _ #``, then turns ``**bold**`` into ``\\textbf{}`` and ``*italic*`` into
202
+ ``\\textit{}``.
203
+
204
+ Args:
205
+ markdown_ref: Reference produced by ``format_reference``.
206
+
207
+ Returns:
208
+ LaTeX source text.
209
+ """
210
+ out = re.sub(r"([&%_#])", r"\\\1", markdown_ref)
211
+ out = re.sub(r"\*\*(.+?)\*\*", r"\\textbf{\1}", out)
212
+ return re.sub(r"\*(.+?)\*", r"\\textit{\1}", out)