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.
This commit is contained in:
2026-09-22 21:50:27 +08:00
parent 15955f552d
commit 76708ce767
8 changed files with 1305 additions and 46 deletions
+435
View File
@@ -0,0 +1,435 @@
"""Check the citation formatter against one reference of every type.
Run it with no server and no database::
.venv/bin/python scripts/check_citation_styles.py
The formatter is pure — a reference in, a printed entry out — so unlike the
``smoke_*`` scripts this one needs nothing running. It builds a reference of each
document type in memory, asserts the exact entry Springer's basic style calls
for, and exits non-zero on the first entry that does not match.
Why it exists: the style has one branch per document type, and a branch that is
wrong prints something that *looks* like a bibliography entry rather than
failing loudly. A paper citing a patent would show a plausible-looking,
incorrect line. Nineteen assertions is a cheap way to keep that from happening.
"""
from __future__ import annotations
import sys
from datetime import date
from pathlib import Path
# Running this as a plain script puts scripts/ on sys.path, not backend/, so
# `import app` would fail. Anchor to the backend directory instead.
BACKEND_DIR = Path(__file__).resolve().parents[1]
if str(BACKEND_DIR) not in sys.path:
sys.path.insert(0, str(BACKEND_DIR))
from app.citation_styles import ( # noqa: E402
DEFAULT_STYLE,
STYLES,
format_reference,
missing_fields,
)
from app.models import Reference, ReferenceAuthor # noqa: E402
_checks = 0
def check(label: str, actual: str, expected: str) -> None:
"""Assert one printed entry, showing both sides when it differs."""
global _checks
_checks += 1
if actual != expected:
raise AssertionError(
f"{label}\n expected: {expected}\n actual: {actual}"
)
print(f" ok {label}")
def author(name: str, family: str | None = None, given: str | None = None,
role: str = "author") -> ReferenceAuthor:
"""One contributor, built in memory — no session, no flush."""
return ReferenceAuthor(
name=name, family_name=family, given_name=given, role=role, sort=0
)
def reference(**fields) -> Reference:
"""A reference with sensible filled-in defaults, overridden per case."""
base: dict = {
"type": "journal-article",
"title": "题名",
"authors": [author("Smith J", "Smith", "J")],
}
base.update(fields)
authors = base.pop("authors")
row = Reference(**base)
row.authors = authors
return row
def main() -> int:
print(f"style: {DEFAULT_STYLE}(可用:{'、'.join(sorted(STYLES))})")
print("\n1. a journal article: names, title, journal, volume(issue), pages, year, DOI")
check(
"journal article",
format_reference(
reference(
title="The art of writing a scientific article",
container_title="Journal of Science Communication",
container_title_short="J. Sci. Commun.",
volume="163",
issue="2",
pages="51-59",
publication_year=2010,
doi="10.1016/j.Sc.2010.00372",
authors=[
author("Van der Geer J", "Van der Geer", "J"),
author("Hanraads JAJ", "Hanraads", "JAJ"),
author("Lupton RA", "Lupton", "RA"),
],
)
),
"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",
)
print("\n2. the abbreviation wins when the writer stored one, and a range gets an en dash")
entry = format_reference(
reference(
title="A paper",
container_title="Full Journal Name",
container_title_short=None,
volume="9",
pages="1000-1010",
publication_year=2020,
)
)
check(
"full 刊名 when there is no 缩写",
entry,
"Smith, J.: A paper. Full Journal Name 9, 1000–1010 (2020)",
)
print("\n3. more than six contributors become three and et al.")
check(
"seven authors",
format_reference(
reference(
title="A crowded paper",
volume="1",
pages="1-2",
publication_year=2021,
authors=[
author(f"Family{index} A", f"Family{index}", "A")
for index in range(1, 8)
],
)
),
"Family1, A., Family2, A., Family3, A., et al.: A crowded paper. "
"1, 1–2 (2021)",
)
check(
"six authors are all named",
format_reference(
reference(
title="Six",
publication_year=2021,
authors=[
author(f"Family{index} A", f"Family{index}", "A")
for index in range(1, 7)
],
)
),
"Family1, A., Family2, A., Family3, A., Family4, A., Family5, A., "
"Family6, A.: Six (2021)",
)
print("\n4. names: initials, blocks of initials, hyphens, and no halves at all")
check(
"given names become initials",
format_reference(reference(title="T", authors=[author("Yong Ming Li", "Li", "Yong Ming")], publication_year=2020)),
"Li, Y.M.: T (2020)",
)
check(
"a block of initials is expanded letter by letter",
format_reference(reference(title="T", authors=[author("Lai KK", "Lai", "KK")], publication_year=2020)),
"Lai, K.K.: T (2020)",
)
check(
"a hyphenated given name keeps its hyphen",
format_reference(reference(title="T", authors=[author("Dupont JL", "Dupont", "Jean-Luc")], publication_year=2020)),
"Dupont, J.-L.: T (2020)",
)
check(
"an institutional author is printed as stored",
format_reference(reference(title="T", authors=[author("世界卫生组织")], publication_year=2020)),
"世界卫生组织: T (2020)",
)
check(
"a CJK name with no halves is not romanised by guesswork",
format_reference(reference(title="T", authors=[author("张三")], publication_year=2020)),
"张三: T (2020)",
)
check(
"a CJK name keeps its printed form even with halves filled in",
format_reference(
reference(
title="T",
authors=[author("张三", "张", "三")],
publication_year=2020,
)
),
"张三: T (2020)",
)
check(
"editors of a book are marked (ed.)",
format_reference(
reference(
type="book",
title="Edited volume",
publisher="Springer",
publisher_place="Cham",
publication_year=2021,
authors=[author("Jones BS", "Jones", "BS", role="editor")],
)
),
"Jones, B.S. (ed.): Edited volume. Springer, Cham (2021)",
)
print("\n5. every other document type")
check(
"book with an edition and a series",
format_reference(
reference(
type="book",
title="The Elements of Style",
edition="4th edn",
series_title="Style Guides",
series_number="7",
publisher="Longman",
publisher_place="New York",
publication_year=2000,
authors=[author("Strunk W", "Strunk", "W")],
)
),
"Strunk, W.: The Elements of Style, 4th edn. Style Guides, 7. "
"Longman, New York (2000)",
)
check(
"book chapter, with the book's editors marked",
format_reference(
reference(
type="book-chapter",
title="How to prepare an electronic version of your article",
container_title="Introduction to the Electronic Age",
pages="281-304",
publisher="E-Publishing Inc.",
publisher_place="New York",
publication_year=2009,
authors=[
author("Mettam GR", "Mettam", "GR"),
author("Adams LB", "Adams", "LB"),
author("Jones BS", "Jones", "BS", role="editor"),
],
)
),
"Mettam, G.R., Adams, L.B.: How to prepare an electronic version of your "
"article. In: Jones, B.S. (ed.) Introduction to the Electronic Age, "
"pp. 281–304. E-Publishing Inc., New York (2009)",
)
check(
"conference paper",
format_reference(
reference(
type="conference-paper",
title="Crowdsourcing in the tourism industry",
container_title="Proceedings of the 3rd International Conference on Tourism",
pages="1-10",
publisher="Springer",
publisher_place="Cham",
publication_year=2019,
authors=[author("Garrigos-Simon FJ", "Garrigos-Simon", "FJ")],
)
),
"Garrigos-Simon, F.J.: Crowdsourcing in the tourism industry. In: "
"Proceedings of the 3rd International Conference on Tourism, pp. 1–10. "
"Springer, Cham (2019)",
)
check(
"conference paper that only knows its meeting",
format_reference(
reference(
type="conference-paper",
title="A meeting paper",
event_title="第 20 届管理学年会",
event_place="北京",
publication_year=2022,
)
),
"Smith, J.: A meeting paper. In: 第 20 届管理学年会. 北京 (2022)",
)
check(
"thesis",
format_reference(
reference(
type="thesis",
title="A dissertation",
publisher="清华大学",
publisher_place="北京",
publication_year=2020,
)
),
"Smith, J.: A dissertation. Thesis, 清华大学 (2020)",
)
check(
"patent",
format_reference(
reference(
type="patent",
title="一种基于多层聚类的技术识别方法",
patent_country="中国",
patent_number="CN114000000A",
publication_year=2023,
)
),
"Smith, J.: 一种基于多层聚类的技术识别方法. 中国 Patent CN114000000A (2023)",
)
check(
"standard",
format_reference(
reference(
type="standard",
title="信息与文献 参考文献著录规则",
standard_number="GB/T 7714-2015",
publisher="中国标准出版社",
publisher_place="北京",
publication_year=2015,
authors=[],
)
),
"信息与文献 参考文献著录规则. GB/T 7714-2015. 中国标准出版社, 北京 (2015)",
)
check(
"report",
format_reference(
reference(
type="report",
title="Annual technology review",
report_number="NREL/TP-5000-12345",
publisher="NREL",
publisher_place="Golden",
publication_year=2012,
)
),
"Smith, J.: Annual technology review. NREL/TP-5000-12345, NREL, Golden (2012)",
)
check(
"web page, with the day it was read",
format_reference(
reference(
type="web-page",
title="Cancer statistics for the UK",
url="https://www.cancerresearchuk.org/health-professional/cancer-statistics",
publication_year=2021,
accessed_date=date(2021, 5, 12),
authors=[author("Cancer Research UK")],
)
),
"Cancer Research UK: Cancer statistics for the UK. "
"https://www.cancerresearchuk.org/health-professional/cancer-statistics "
"(2021). Accessed 12 May 2021",
)
check(
"dataset",
format_reference(
reference(
type="dataset",
title="Patent citation network",
url="https://doi.org/10.6084/m9.figshare.1234567",
publication_year=2024,
)
),
"Smith, J.: Patent citation network. Dataset (2024). "
"https://doi.org/10.6084/m9.figshare.1234567",
)
check(
"preprint, which has no DOI yet",
format_reference(
reference(
type="preprint",
title="A preprint",
arxiv_id="arXiv:2405.12345",
publication_year=2024,
)
),
"Smith, J.: A preprint. Preprint arXiv:2405.12345 (2024)",
)
check(
"newspaper article",
format_reference(
reference(
type="newspaper-article",
title="A news story",
container_title="The Times",
pages="12",
publication_year=2020,
)
),
"Smith, J.: A news story. The Times, 12 (2020)",
)
check(
"a subtitle rejoins its title",
format_reference(
reference(
title="技术惯性与冲量的耦合机制",
subtitle="基于科学与技术融合网络的实证分析",
volume="198",
pages="122-141",
publication_year=2024,
)
),
"Smith, J.: 技术惯性与冲量的耦合机制: 基于科学与技术融合网络的实证分析. "
"198, 122–141 (2024)",
)
print("\n6. a gap is reported, not papered over")
check(
"an entry with no year prints no invented year",
format_reference(reference(title="No year", volume="1", pages="1-2")),
"Smith, J.: No year. 1, 1–2",
)
missing = missing_fields(
reference(title="No year", volume=None, pages=None, container_title=None)
)
check("the missing fields are named in Chinese", "、".join(missing), "刊名、卷期页码、出版年")
check(
"a complete entry reports nothing missing",
"、".join(missing_fields(reference(
title="Complete",
container_title="A Journal",
volume="1",
pages="1-2",
publication_year=2020,
))),
"",
)
check(
"a web page without a URL is told so, in the style's own terms",
"、".join(missing_fields(reference(
type="web-page", title="No address", url=None, doi=None, accessed_date=None
))),
"URL、引用日期",
)
print(f"\nall {_checks} checks passed")
return 0
if __name__ == "__main__":
sys.exit(main())