Files
govin 76708ce767 backend: print the 参考文献 list as a bibliography, one entry per work
The list was printing each citation's quote under a `引用 #53` tag: no authors,
no year, no pages, no DOI — the quoted passage where the entry should be — and
it numbered *citations*, so a paper with 86 citations to 65 works listed 21 of
them two or three times under different numbers. The same article was `[5]` in
one paragraph and `[17]` in another.

Two rules were wrong, so two are stated here:

**A work is numbered where the reader first meets it.** A citation is a place
in the text; an entry is a work. `citations` still has one row per place, and
each row now carries the number of its *work*, so the marker in the text, the
tooltip on it and the entry in the list are the same number. The document grew
a `references` list — the entries, in order — and `reference_style`, which
names the style that wrote them.

**How a reference prints is a property of a style, not of a citation.** The new
`app/citation_styles` package holds one module per style; `springer.py`
implements Springer's basic style, whose shape is
`Names: Title. <where it sits> (year). <identifier>` with a branch per document
type — a journal with its volume(issue) and pages, a book with publisher and
place, a chapter inside somebody else's book, a patent with its number, a page
whose URL is its source.

Three of its rules are decisions rather than transcription, and each is
documented where it applies: up to six contributors are named and more become
three plus `et al.`; a journal prints under its 刊名缩写 when the writer stored
one, because no algorithm abbreviates an arbitrary title correctly; and a CJK
name keeps its printed form even with halves filled in, because dotting 「三」
into an initial is wrong in Chinese and insufficient in English.

Nothing is invented to fill a gap. An entry says what it knows and reports the
rest as `missing` (「缺 责任者、出版年」), and the document warns about the
incomplete ones by number: an entry that is short because fields are empty
looks like a fact about the document rather than a library that needs attention.

`document_text` had the same bug in the MCP surface and now prints the entries,
with in-text markers taken from the document's numbering rather than from each
sentence's local position — which is what made the text an agent reads disagree
with the list under it.

`scripts/check_citation_styles.py` checks the formatter with no server and no
database: one reference of every type, and the exact entry the style calls for.
2026-09-22 21:50:27 +08:00

565 lines
21 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Springer basic style: one stored reference, written out as a bibliography entry.
Springer's **basic** style is the numbered one — bracketed numerals in the text
and a numbered list at the end — which is the shape this project already has.
What it adds is the layout of the entry itself, taken from Springer's own
examples:
.. code-block:: text
Van der Geer, J., Hanraads, J.A.J., Lupton, R.A.: The art of writing a
scientific article. J. Sci. Commun. 163(2), 51–59 (2010).
https://doi.org/10.1016/j.Sc.2010.00372
Strunk Jr., W., White, E.B.: The Elements of Style, 4th edn. Longman,
New York (2000)
Mettam, G.R., Adams, L.B.: How to prepare an electronic version of your
article. In: Jones, B.S., Smith, R.Z. (eds.) Introduction to the Electronic
Age, pp. 281–304. E-Publishing Inc., New York (2009)
So an entry is ``Names: Title. <where the entry sits> (year). <identifier>``,
and *where it sits* is the only part that changes with the document type: a
journal with its volume and pages, a book with its publisher, a chapter inside
somebody else's book, a patent with its number.
Three rules here are decisions rather than transcription, and each is stated
where it is applied:
* **Up to six contributors are named; more become the first three and
``et al.``** — Springer's rule for this style.
* **A journal prints under its 刊名缩写 when the writer stored one**, because
Springer abbreviates journal titles and no algorithm abbreviates an arbitrary
title correctly: the library has a column for the abbreviation precisely so a
human decides it. Without one, the full 刊名 is printed rather than an
invention.
* **A CJK name is printed as stored**, halves or no halves: dotting 「三」 into
an initial is wrong in Chinese and insufficient in English (see
:func:`_name`).
* **Nothing is invented to fill a gap.** A missing year prints no parentheses, a
missing publisher no publisher; the field simply does not appear. What a
complete entry would need is reported separately by :func:`missing_fields`, so
the writer is told what is absent instead of being shown a plausible-looking
fabrication.
"""
from __future__ import annotations
import re
from datetime import date
from typing import Callable
from app.models import Reference, ReferenceAuthor
#: How many contributors are named before the list is cut short, and how many
#: survive the cut. Springer's basic style names up to six, then the first three
#: followed by ``et al.``
_AUTHOR_LIMIT = 6
_AUTHOR_KEEP = 3
#: ``122-141`` → ``122–141``. Springer prints ranges with an en dash, and the
#: stored value is whatever the writer pasted — often a plain hyphen.
_PAGE_RANGE = re.compile(r"(\d+)\s*[-–—]\s*(\d+)")
#: CJK ideographs and kana. A name containing one is printed as stored rather
#: than inverted and initialised; see :func:`_name`.
_CJK = re.compile(r"[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
_MONTHS = (
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
)
#: For a web page the URL *is* the source, so it is printed where a journal
#: would be rather than at the end as an identifier. Every other type keeps the
#: URL for the trailing ``https://doi.org/…`` slot.
_URL_IS_THE_SOURCE = frozenset({"web-page"})
def format_reference(reference: Reference) -> str:
"""Write one reference out as a Springer bibliography entry.
The clauses are assembled and joined by ``". "``, which is the style's own
punctuation: the colon after the names, the period between the title and
where the entry sits, and the period before the DOI all fall out of it.
"""
clauses = [
clause
for clause in (
_head(reference),
*_where(reference),
_identifier(reference),
_accessed(reference),
)
if clause
]
# A clause that is nothing but a year is not a sentence, so it attaches to
# what precedes it rather than following a full stop. This is the shape a
# reference with a title and a year and nothing else takes: "…: Six (2021)",
# not "…: Six. (2021)". Doing it here rather than in each of the fourteen
# builders is one rule instead of fourteen chances to forget it.
parts: list[str] = []
for clause in clauses:
if parts and clause.startswith("(") and clause.endswith(")"):
parts[-1] = f"{parts[-1]} {clause}"
else:
parts.append(clause)
return ". ".join(parts)
# --- the two halves every entry has ------------------------------------------
def _head(reference: Reference) -> str:
"""``Names: Title`` — what the entry is, and who wrote it."""
names = _head_names(reference)
title = _title(reference)
return f"{names}: {title}" if names else title
def _title(reference: Reference) -> str:
"""The title, with its subtitle after a colon.
The library stores 副题名 as its own column because a citation style is
allowed to drop it; this one prints it, so the two are joined back into the
title the reader saw.
"""
title = _clean(reference.title)
subtitle = _clean(reference.subtitle)
if subtitle and not title.endswith((":", ":")):
title = f"{title}: {subtitle}"
elif subtitle:
title = f"{title} {subtitle}"
# For a whole book the edition belongs to the title ("The Elements of
# Style, 4th edn"); for a chapter it belongs to the book it sits in, which
# is where :func:`_where_chapter` puts it.
if reference.type == "book" and _clean(reference.edition):
title = f"{title}, {_clean(reference.edition)}"
return title
def _head_names(reference: Reference) -> str:
"""The contributors that lead the entry.
Authors first. A book whose contributors are all marked 编者 is written by
its editors — ``Jones, B.S. (ed.)`` — and a 汇编 / 译者 with no author at all
still has to appear somewhere, so the last resort is the stored list in
print order.
"""
authors = [author for author in reference.authors if author.role == "author"]
if authors:
return _name_list(authors)
editors = [author for author in reference.authors if author.role == "editor"]
if editors:
return _name_list(editors) + (" (ed.)" if len(editors) == 1 else " (eds.)")
return _name_list(list(reference.authors))
def _editor_names(reference: Reference) -> str:
"""The 编者 of a chapter's containing book, marked ``(ed.)`` / ``(eds.)``.
The library keeps one contributor list per entry, so these are the
contributors the writer marked 编者. When there are none the container is
printed without a mark rather than guessing whose book it is.
"""
editors = [author for author in reference.authors if author.role == "editor"]
if not editors:
return ""
mark = " (ed.)" if len(editors) == 1 else " (eds.)"
return _name_list(editors) + mark
def _name_list(people: list[ReferenceAuthor]) -> str:
"""The contributor list, cut to Springer's limit."""
names = [_name(person) for person in people if person.name.strip()]
if len(names) > _AUTHOR_LIMIT:
return ", ".join(names[:_AUTHOR_KEEP]) + ", et al."
return ", ".join(names)
def _name(person: ReferenceAuthor) -> str:
"""One contributor as ``Family, I.N.``
The halves are the authority for rewriting a name and the whole ``name`` is
the authority for printing it, as the model says. So a row with Latin halves
is inverted and initialised — some of them arrive already abbreviated
(``Lai KK`` → ``Lai, K.K.``) — while a row without them is printed exactly as
stored, which is the only correct thing to do for an institutional author
(「世界卫生组织」, "World Health Organization") and for a CJK name whose
romanisation the library was never told.
A CJK name keeps its printed form even *with* halves filled in. ``张`` +
``三`` inverted and dotted gives 「张, 三.」, which is neither Chinese nor
English: an initial is a Latin-script idea, and 「三」 is not the initial of
a given name, it is the whole of it. Springer's own ``Zhang, S.`` needs a
romanisation this library does not hold, so the stored 「张三」 is printed
rather than turned into something that is wrong in both languages.
"""
family = _clean(person.family_name)
given = _clean(person.given_name)
if not family or _CJK.search(family) or _CJK.search(given):
return _clean(person.name)
initials = _initials(given)
return f"{family}, {initials}" if initials else family
def _initials(given: str) -> str:
"""``Yong Ming`` → ``Y.M.``, ``AL`` → ``A.L.``, ``Jean-Luc`` → ``J.-L.``"""
if not given:
return ""
initials: list[str] = []
for token in given.split():
parts = [part for part in re.split(r"[-–]", token) if part]
if len(parts) > 1:
initials.append("-".join(_initial(part) for part in parts))
else:
initials.append(_initial(token))
return "".join(part for part in initials if part)
def _initial(token: str) -> str:
"""One given-name token as initials.
A token that is already a block of initials is expanded letter by letter —
``KK`` is two names, not one — and a token that is a name contributes its
first letter.
"""
letters = [character for character in token if character.isalpha()]
if not letters:
return ""
if len(letters) > 1 and token.isupper():
return "".join(f"{character.upper()}." for character in letters)
return f"{letters[0].upper()}."
# --- where the entry sits ----------------------------------------------------
def _where(reference: Reference) -> list[str]:
"""The clauses between the title and the identifier, by document type."""
builder: Callable[[Reference], list[str]] = _WHERE.get(
reference.type, _where_generic
)
return builder(reference)
def _where_journal(reference: Reference) -> list[str]:
"""``J. Sci. Commun. 163(2), 51–59 (2010)``"""
source = _join_space(_container(reference), _volume_issue(reference))
source = _join_comma(source, _pages(reference))
return [_with_year(source, reference)]
def _where_newspaper(reference: Reference) -> list[str]:
"""``The Times, p. 12 (2020)`` — a newspaper has a date, not a volume."""
source = _join_comma(_container(reference), _pages(reference))
return [_with_year(source, reference)]
def _where_book(reference: Reference) -> list[str]:
"""``Longman, New York (2000)``, with the series ahead of it."""
clauses = []
series = _join_comma(_clean(reference.series_title), _clean(reference.series_number))
if series:
clauses.append(series)
place = _join_comma(_clean(reference.publisher), _clean(reference.publisher_place))
clauses.append(_with_year(place, reference))
return [clause for clause in clauses if clause]
def _where_chapter(reference: Reference) -> list[str]:
"""``In: Jones, B.S. (ed.) Book title, pp. 281–304. E-Publishing Inc., New York (2009)``"""
inside = _container(reference)
if inside and _clean(reference.edition):
inside = f"{inside}, {_clean(reference.edition)}"
pages = _pages(reference)
if pages:
inside = _join_comma(inside, f"pp. {pages}")
editors = _editor_names(reference)
inside = _join_space(editors, inside) if editors else inside
opening = f"In: {inside}" if inside else ""
place = _with_year(
_join_comma(_clean(reference.publisher), _clean(reference.publisher_place)),
reference,
)
return [clause for clause in (opening, place) if clause]
def _where_conference(reference: Reference) -> list[str]:
"""``In: Proceedings of …, pp. 10–20. Springer, Cham (2022)``"""
inside = _container(reference) or _clean(reference.event_title)
pages = _pages(reference)
if pages:
inside = _join_comma(inside, f"pp. {pages}")
opening = f"In: {inside}" if inside else ""
place = _with_year(
_join_comma(
_clean(reference.publisher),
_clean(reference.publisher_place) or _clean(reference.event_place),
),
reference,
)
return [clause for clause in (opening, place) if clause]
def _where_thesis(reference: Reference) -> list[str]:
"""``Thesis, 清华大学 (2020)``
The degree (PhD, 硕士) is not a field of this library, so the entry says
what it knows rather than inventing a doctorate.
"""
return [_with_year(_join_comma("Thesis", _clean(reference.publisher)), reference)]
def _where_patent(reference: Reference) -> list[str]:
"""``中国 Patent CN114000000A (2023)`` — the country and number inside the mark."""
mark = _join_space(_clean(reference.patent_country), "Patent")
marked = _join_space(mark, _clean(reference.patent_number))
return [_with_year(marked, reference)]
def _where_standard(reference: Reference) -> list[str]:
"""``GB/T 7714-2015. 中国标准出版社, 北京 (2015)``
The number follows the title rather than leading the entry: the title is
what the writer searched by and what the reader recognises.
"""
number = _clean(reference.standard_number)
place = _with_year(
_join_comma(_clean(reference.publisher), _clean(reference.publisher_place)),
reference,
)
return [clause for clause in (number, place) if clause]
def _where_report(reference: Reference) -> list[str]:
"""``NREL/TP-5000-12345, NREL, Golden (2012)``"""
clause = _join_comma(
_clean(reference.report_number),
_clean(reference.publisher),
_clean(reference.publisher_place),
)
return [_with_year(clause, reference)]
def _where_web(reference: Reference) -> list[str]:
"""``https://… (2021)`` — for a page the URL is where the entry sits."""
return [_with_year(_clean(reference.url), reference)]
def _where_dataset(reference: Reference) -> list[str]:
"""``Dataset (2024)`` — the type stands where a journal name would."""
return [_with_year("Dataset", reference)]
def _where_software(reference: Reference) -> list[str]:
"""``Software (2024)``"""
return [_with_year("Software", reference)]
def _where_preprint(reference: Reference) -> list[str]:
"""``Preprint arXiv:2405.12345 (2024)`` — how a paper is cited before a DOI."""
return [_with_year(_join_space("Preprint", _clean(reference.arxiv_id)), reference)]
def _where_generic(reference: Reference) -> list[str]:
"""Anything typed ``other``: the container, then the publisher.
The year closes whichever of the two is the last thing printed, so it never
dangles on its own in the middle of an entry.
"""
source = _join_comma(_container(reference), _pages(reference))
place = _join_comma(_clean(reference.publisher), _clean(reference.publisher_place))
if place:
return [clause for clause in (source, _with_year(place, reference)) if clause]
return [_with_year(source, reference)]
_WHERE: dict[str, Callable[[Reference], list[str]]] = {
"journal-article": _where_journal,
"newspaper-article": _where_newspaper,
"book": _where_book,
"book-chapter": _where_chapter,
"conference-paper": _where_conference,
"thesis": _where_thesis,
"patent": _where_patent,
"standard": _where_standard,
"report": _where_report,
"web-page": _where_web,
"dataset": _where_dataset,
"software": _where_software,
"preprint": _where_preprint,
}
# --- the identifier, and the day it was read ---------------------------------
def _identifier(reference: Reference) -> str:
"""``https://doi.org/10.1016/j.Sc.2010.00372``, or the URL, or nothing.
A DOI is printed as the resolvable link, which is how Springer prints it —
the column stores it bare so the two spellings cannot drift.
"""
doi = _clean(reference.doi)
if doi:
return f"https://doi.org/{doi}"
if reference.type in _URL_IS_THE_SOURCE:
return ""
return _clean(reference.url)
def _accessed(reference: Reference) -> str:
"""``Accessed 12 May 2021`` — the day an online resource was read."""
if reference.accessed_date is None:
return ""
return f"Accessed {_long_date(reference.accessed_date)}"
def _long_date(value: date) -> str:
return f"{value.day} {_MONTHS[value.month - 1]} {value.year}"
# --- what a complete entry is still missing ----------------------------------
#: The fields a complete entry needs, per type. ``None`` means "this type has no
#: such field", so the list is not padded with requirements that do not apply.
_REQUIRED: dict[str, tuple[str, ...]] = {
"journal-article": ("责任者", "刊名", "卷期页码", "出版年"),
"newspaper-article": ("责任者", "报纸名", "页码", "出版年"),
"book": ("责任者", "出版者", "出版年"),
"book-chapter": ("责任者", "书名", "页码", "出版者", "出版年"),
"conference-paper": ("责任者", "会议名", "出版年"),
"thesis": ("责任者", "培养单位", "出版年"),
"patent": ("责任者", "专利号", "出版年"),
"standard": ("标准编号", "出版年"),
"report": ("责任者", "报告编号", "出版年"),
"web-page": ("URL", "引用日期"),
"dataset": ("URL", "出版年"),
"software": ("URL", "出版年"),
"preprint": ("责任者", "出版年"),
"other": ("责任者", "出版年"),
}
def missing_fields(reference: Reference) -> list[str]:
"""Which parts of a complete entry this reference still lacks, in Chinese.
The point is that a gap should be *reported* rather than quietly rendered as
a shorter entry: an entry with no author and no year looks like a fact about
the document instead of a field nobody filled in.
"""
missing: list[str] = []
for field in _REQUIRED.get(reference.type, _REQUIRED["other"]):
if not _has(reference, field):
missing.append(field)
return missing
def _has(reference: Reference, field: str) -> bool:
"""Whether the field this label names is filled in."""
if field == "责任者":
return bool(reference.authors)
if field == "刊名" or field == "报纸名" or field == "会议名" or field == "书名":
# A chapter's 书名 and a paper's 论文集名 are both the container; a
# conference may carry its meeting name instead.
return bool(
_clean(reference.container_title)
or (field == "会议名" and _clean(reference.event_title))
)
if field == "卷期页码":
return bool(
_clean(reference.volume)
or _clean(reference.issue)
or _clean(reference.pages)
or _clean(reference.article_number)
)
if field == "页码":
return bool(_clean(reference.pages) or _clean(reference.article_number))
if field == "出版者" or field == "培养单位":
return bool(_clean(reference.publisher))
if field == "标准编号":
return bool(_clean(reference.standard_number))
if field == "报告编号":
return bool(_clean(reference.report_number) or _clean(reference.publisher))
if field == "专利号":
return bool(_clean(reference.patent_number))
if field == "URL":
return bool(_clean(reference.url) or _clean(reference.doi))
if field == "引用日期":
return reference.accessed_date is not None
if field == "出版年":
return reference.publication_year is not None
return True
# --- small helpers -----------------------------------------------------------
def _clean(value: str | None) -> str:
"""Whitespace folded, or ``""`` — so a blank field is simply absent."""
if value is None:
return ""
return " ".join(value.split())
def _container(reference: Reference) -> str:
"""The journal or book the entry sits in.
The abbreviation wins when the writer stored one: Springer abbreviates
journal titles, and an algorithm cannot abbreviate an arbitrary title
correctly, so the 刊名缩写 column is where a human decides it.
"""
return _clean(reference.container_title_short) or _clean(reference.container_title)
def _volume_issue(reference: Reference) -> str:
"""``163(2)``, ``163``, ``(2)`` or nothing."""
volume = _clean(reference.volume)
issue = _clean(reference.issue)
if volume and issue:
return f"{volume}({issue})"
return volume or (f"({issue})" if issue else "")
def _pages(reference: Reference) -> str:
"""``51–59`` with an en dash, or the article number when there is no page."""
pages = _clean(reference.pages)
if pages:
return _PAGE_RANGE.sub(lambda match: f"{match.group(1)}–{match.group(2)}", pages)
return _clean(reference.article_number)
def _with_year(clause: str, reference: Reference) -> str:
"""``Journal 163(2), 51–59 (2010)`` — the year closes the clause it follows."""
if reference.publication_year is None:
return clause
return f"{clause} ({reference.publication_year})" if clause else f"({reference.publication_year})"
def _join_comma(*parts: str) -> str:
return ", ".join(part for part in parts if part)
def _join_space(*parts: str) -> str:
return " ".join(part for part in parts if part)