Files
paper-doc/backend/scripts/seed.py
T
govin 199e328b48 refactor: call a heading a title, and its use a placement
`template_field_library` and `template_field` were one word apart and meant
opposite kinds of thing — a catalogue of rows versus one row — and neither name
said what a row actually is. Every row of the library is a **heading**: a piece
of text like 「1. Introduction」 with a level and typography, which is what the
reader sees at the top of a paragraph; and every row of the join table is that
heading *placed* in a template, `sort` included.

    template_field_library  -> template_title
    template_field          -> template_title_placement
    field_id (the column)   -> title_id
    TemplateFieldLibrary    -> TemplateTitle
    TemplateField           -> TemplateTitlePlacement

The join table keeps its own name rather than becoming `_link`, because it is
not a bare link: it carries `sort`, the only place display order is stored, and
it deliberately allows the same title twice in one template. `_link` would
describe two foreign keys and hide the column the ordering rule rests on.

Carried through every level, because a half-renamed layer is how the confusing
pair got there in the first place: HTTP paths (`/template-field-library` ->
`/template-titles`), the template payload (`fields`/`field_id` ->
`placements`/`title_id`, and `field_count` -> `placement_count`), the Pydantic
schemas, the CRUD modules, the seed script, the frontend API module and types,
and `docs/OVERVIEW.md`, which now states the naming rules outright.

Two deliberate exceptions:

* `paper_template_filed_sort` is untouched — it is a column of the paper module
  and is spelled as the feature was specified.
* The MCP tools keep their agent-facing names (`field_list`, `field_ids`, and
  the `fields`/`field_id` keys in their responses). Agents already call them by
  those names; the storage names they read underneath have changed.

The migration renames in place (data preserved: 4 templates, 45 titles, 63
placements) and is written to tolerate a database where part of it already ran,
which is not hypothetical — the first attempt renamed the tables and then failed
on the column, because Alembic's MySQL dialect wants an explicit type for
`alter_column` and will not rename a column without one. TiDB carries the
foreign key along with both the renamed table and the renamed column, rehearsed
against the cluster first, and it stays enforced.

Verified: seed re-runs clean, the paper smoke test's 45 checks and the MCP
smoke test's 47 pass, `vue-tsc` and the build are clean, and the UI was driven
in a headless browser through the template list, its preview drawer, the title
library page, the template form (which now posts `placements` with `title_id`)
and the paper document with no console errors.
2026-09-22 16:55:02 +08:00

201 lines
6.8 KiB
Python

"""Seed the template-title library and a couple of starter templates.
Idempotent: titles are matched by name and templates by name, so running it
twice adds nothing. ``--reset`` empties the three tables first, which is the
way to get back to the seeded baseline after experimenting.
Usage (from ``backend/``)::
.venv/bin/python scripts/seed.py
.venv/bin/python scripts/seed.py --reset
"""
from __future__ import annotations
import argparse
import sys
from decimal import Decimal
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 sqlalchemy import delete, select # noqa: E402
from sqlalchemy.orm import Session # noqa: E402
from app.db.session import SessionLocal # noqa: E402
from app.models import Template, TemplateTitle, TemplateTitlePlacement # noqa: E402
# --- the title library -------------------------------------------------------
#
# (name, level, font_size, font_color)
#
# The number in the name is written by hand and stored verbatim — nothing in
# the system derives or rewrites it. Level is only a rendering hint: it decides
# indentation in the outline, never parentage.
#
# Colours: headings are near-black, running text is black, and the two
# unnumbered front/back sections (Abstract, References) are grey so they read
# as apparatus rather than as body sections.
BODY = "#000000"
HEADING = "#1F1F1F"
SUB = "#404040"
GREY = "#595959"
TITLES: list[tuple[str, int, Decimal, str]] = [
("0 Abstract", 1, Decimal("10.5"), GREY),
("1 Introduction", 1, Decimal("12.0"), HEADING),
("1.1 Research Background", 2, Decimal("10.5"), SUB),
("1.2 Problem Statement", 2, Decimal("10.5"), SUB),
("1.3 Contributions", 2, Decimal("10.5"), SUB),
("2 Related Work", 1, Decimal("12.0"), HEADING),
("2.1 Prior Approaches", 2, Decimal("10.5"), SUB),
("2.2 Limitations of Existing Work", 2, Decimal("10.5"), SUB),
("3 Method", 1, Decimal("12.0"), HEADING),
("3.1 Problem Formulation", 2, Decimal("10.5"), SUB),
("3.2 Framework Overview", 2, Decimal("10.5"), SUB),
("3.3 Implementation Details", 2, Decimal("10.5"), SUB),
("4 Experiments", 1, Decimal("12.0"), HEADING),
("4.1 Datasets", 2, Decimal("10.5"), SUB),
("4.2 Experimental Setup", 2, Decimal("10.5"), SUB),
("4.3 Main Results", 2, Decimal("10.5"), SUB),
("4.4 Ablation Study", 2, Decimal("10.5"), SUB),
("5 Discussion", 1, Decimal("12.0"), BODY),
("6 Conclusion", 1, Decimal("12.0"), BODY),
("7 References", 1, Decimal("10.5"), GREY),
]
# --- starter templates -------------------------------------------------------
#
# Each entry is (template name, abstract, [title names in display order]).
# `sort` is assigned from the list position (1, 2, 3 ...), which is exactly
# what the UI does when the user picks titles and orders them.
TEMPLATES: list[tuple[str, str, list[str]]] = [
(
"标准学术论文(通用)",
"完整的通用学术论文骨架,含摘要、引言、相关工作、方法、实验、讨论与结论。"
"适合期刊或会议长文;先按此模板把结构填满,再按目标期刊微调字段。",
[name for name, *_ in TITLES],
),
(
"四段式短文",
"紧凑的四段式结构,只保留摘要、引言、方法、实验与结论。"
"适合短文、技术报告或初稿阶段的结构搭建。",
[
"0 Abstract",
"1 Introduction",
"3 Method",
"4 Experiments",
"6 Conclusion",
],
),
(
"方法创新型论文",
"以方法贡献为主线的结构,弱化相关工作、强化方法细节与消融实验。"
"适合以新框架、新算法为主要贡献的投稿。",
[
"0 Abstract",
"1 Introduction",
"1.2 Problem Statement",
"1.3 Contributions",
"3 Method",
"3.1 Problem Formulation",
"3.2 Framework Overview",
"3.3 Implementation Details",
"4 Experiments",
"4.2 Experimental Setup",
"4.3 Main Results",
"4.4 Ablation Study",
"6 Conclusion",
],
),
]
def reset(db: Session) -> None:
"""Empty the three tables in dependency order."""
db.execute(delete(TemplateTitlePlacement))
db.execute(delete(Template))
db.execute(delete(TemplateTitle))
db.commit()
def seed_titles(db: Session) -> dict[str, TemplateTitle]:
"""Insert any missing library titles and return name -> title."""
existing = {title.name: title for title in db.scalars(select(TemplateTitle)).all()}
created = 0
for name, level, font_size, font_color in TITLES:
if name in existing:
continue
title = TemplateTitle(
name=name, level=level, font_size=font_size, font_color=font_color
)
db.add(title)
existing[name] = title
created += 1
db.commit()
for title in existing.values():
db.refresh(title)
print(
f" template_title : {created} created, "
f"{len(existing) - created} already present"
)
return existing
def seed_templates(db: Session, titles: dict[str, TemplateTitle]) -> None:
"""Insert any missing starter templates."""
existing = {name for name in db.scalars(select(Template.name)).all()}
created = 0
for name, abstract, title_names in TEMPLATES:
if name in existing:
continue
missing = [title_name for title_name in title_names if title_name not in titles]
if missing:
raise SystemExit(f"template {name!r} references unknown titles: {missing}")
template = Template(name=name, abstract=abstract)
# sort is the list position: 1-based, ascending, with gaps allowed
# because the UI lets the user type any integer.
template.placements = [
TemplateTitlePlacement(title_id=titles[title_name].id, sort=index)
for index, title_name in enumerate(title_names, start=1)
]
db.add(template)
created += 1
db.commit()
print(f" template: {created} created, {len(existing)} already present")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--reset",
action="store_true",
help="delete all titles and templates before seeding",
)
args = parser.parse_args()
with SessionLocal() as db:
if args.reset:
reset(db)
print(" reset : all rows deleted")
titles = seed_titles(db)
seed_templates(db, titles)
print("seed complete")
if __name__ == "__main__":
main()