diff --git a/AGENTS.md b/AGENTS.md
index 3d44beb..7881615 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -84,11 +84,18 @@ Where a spelling is ambiguous, the Bible's shape decides — a book must have th
cited — never a per-module rule in code. Text is never rewritten to make a citation
easier to recognise.
-Text is SWORD's `stripped` projection, except for ThML modules, whose source is projected
-by `src/study_builder/content.py` because SWORD's ThML plain filter discards every line
-break. The projection keeps SWORD's conventions; a change to it changes the words of every
-ThML module and needs the smoke builds. Every text is normalised the same way. Module bytes
-UTF-8 cannot read are decoded as Windows-1252, never replaced.
+ThML, TEI, and OSIS text is projected from the verified source markup through
+`src/study_builder/content.py`. SWORD's stripped projections can discard structural
+breaks and XML character references. Keep the source format's paragraph, line, sense,
+note, and reference semantics, and decode character references once while reading
+markup. Already-plain text must not be HTML-unescaped again. Other formats keep
+SWORD's stripped projection. The extractor's `rendered_default` value (internally
+named `html`) is not guaranteed to be HTML; it can still contain source markup.
+Never use that name to infer its format. These rules apply to dictionaries and
+commentaries alike; shared projection changes need both resources' smoke builds.
+Preserve source wording and scripts without per-entry replacements or language
+filters. Every text is normalised the same way. Module bytes UTF-8 cannot read are
+decoded as Windows-1252, never replaced. Public schemas and paths stay unchanged.
Dictionary Strong's keys remain compatible with Bible API v3 (`G3056`, `H0430`).
Repeated dictionary keys retain the unsuffixed direct path for their first
diff --git a/README.md b/README.md
index ab981a5..2592417 100644
--- a/README.md
+++ b/README.md
@@ -324,14 +324,25 @@ clients that would otherwise read every word individually.
## Plain text
-Every document is plain text, and the text is laid out the way the module laid it out.
-SWORD's own plain-text reading of a ThML module collapses every line and paragraph
-break, so Torrey's lists and Smith's paragraphs would arrive as one unbroken line; for
-ThML modules the builder reads the source markup itself, keeping SWORD's conventions
-(entities, `` Strong's markers, `[bracketed]` notes) and keeping the breaks. The
-other markup families keep their breaks in SWORD's reading already. Whatever the family,
-the published text has one space between words, no leading or trailing space on a line,
-and at most one blank line between blocks.
+Every document is plain text. For ThML, TEI, and OSIS modules, the builder projects the
+verified source markup into readable text. SWORD's stripped projections can discard
+line breaks and character references: a TEI `
` can disappear between words, and
+a Greek letter written as `α` can be lost. The source-aware projections preserve
+paragraphs, line breaks, senses, notes, reference labels, and Unicode characters for
+both dictionaries and commentaries. Other source formats retain SWORD's stripped text.
+
+Character references are decoded once, when markup is read. Text that is already plain
+is only whitespace-normalised, so literal ampersands and entity-like examples are not
+interpreted a second time. The extractor's `rendered_default` field is not necessarily
+HTML; the builder does not select a projection based on that field's name.
+
+The conversion preserves source wording, including multilingual text; it does not
+translate, substitute dictionary entries, or remove characters by language. These
+rendering corrections keep the existing v1 schemas, paths, identifiers, reference
+shapes, and complete-download structure. The public `text` remains a string, with one
+space between words, no leading or trailing space on a line, and at most one blank
+line between blocks. Standalone documents and the corresponding entries embedded in
+complete downloads contain identical text.
Bytes the module wrote in Windows-1252 — the `’` of "David’s", the non-breaking space of
"1 Chronicles" — are read as such rather than replaced with `�`.
diff --git a/src/study_builder/commentaries.py b/src/study_builder/commentaries.py
index 3b2bea6..31f3612 100644
--- a/src/study_builder/commentaries.py
+++ b/src/study_builder/commentaries.py
@@ -216,7 +216,9 @@ def _entry(self, source: dict[str, Any]) -> dict[str, Any] | None:
related = self.references.extract(
content["text"],
markup=extract_markup_references(
- str(source.get("raw", "")), str(source.get("html", ""))
+ str(source.get("raw", "")),
+ str(source.get("html", "")),
+ source_type=self.source_type,
),
book=book.number,
chapter=chapter if chapter > 0 else None,
diff --git a/src/study_builder/content.py b/src/study_builder/content.py
index 7cdc257..562e355 100644
--- a/src/study_builder/content.py
+++ b/src/study_builder/content.py
@@ -5,12 +5,11 @@
needs no HTML sanitizer and the generated API carries no markup that a consuming
application could inject into a page.
-The text comes from the extractor's ``stripped`` projection — SWORD's own plain-text
-reading of the module — with one exception. SWORD's ThML plain filter collapses every
-line and paragraph break into a space, so a ThML dictionary or commentary would publish
-each entry as one unbroken paragraph however its source was laid out. For ThML modules
-the builder therefore reads the source markup itself, keeping SWORD's conventions
-(entities, Strong's and morphology markers, bracketed notes) and keeping the breaks.
+ThML, TEI and OSIS source is projected after the extractor contract has verified its
+bytes. SWORD's stripped projections lose structure and, for some formats, character
+references. Source-aware projection keeps readable blocks, labels, notes and references
+without adding markup to the public contract. Other formats retain SWORD's stripped
+projection. Entity decoding happens only while reading markup, never on plain text.
Whatever the source, the published text is normalised the same way: one space between
words, no leading or trailing space on a line, at most one blank line between blocks.
@@ -20,11 +19,14 @@
import html
import re
+from functools import partial
from html.parser import HTMLParser
from typing import Any
from urllib.parse import parse_qs, unquote, urlsplit
+from study_builder.osis import osis_text
from study_builder.references import MarkupReference
+from study_builder.xmltext import decode_xml_entities, xml_attributes, xml_character_reference
_SUPPRESSED_TAGS = {"script", "style"}
# A block stands apart from what surrounds it: a break before and after.
@@ -57,6 +59,11 @@
_LINE_TAGS = {"br", "dd", "dt", "li", "tr"}
# Cells of a table row stay on one line, separated by a space.
_CELL_TAGS = {"td", "th"}
+# TEI dictionaries share HTML's paragraph tags but use their own list/table names.
+# In TEI, ``tr`` is a translation, not an HTML table row.
+_TEI_BLOCK_TAGS = _BLOCK_TAGS | {"entry", "entryfree", "head", "lg", "list", "sense"}
+_TEI_LINE_TAGS = (_LINE_TAGS - {"tr"}) | {"item", "l", "lb", "row"}
+_TEI_CELL_TAGS = _CELL_TAGS | {"cell"}
_OSIS_REF = re.compile(
r"(?P[1-4]?[A-Za-z][A-Za-z0-9]+)\.(?P\d+)(?:\.(?P\d+))?"
@@ -72,14 +79,15 @@
# and the sword://Bible/ link any of them may use. The rendered form spells them all
# one way, as passagestudy.jsp showRef anchors, which is read as well.
_REFERENCE_TAG = re.compile(
- r"<(?Preference|ref|scripRef)\b(?P[^>]*?)(?:/>|>(?P.*?)(?P=tag)\s*>)",
+ r"<(?P(?:[A-Za-z_][\w.-]*:)?(?:reference|ref|scripRef))\b"
+ r"(?P[^>]*?)(?:/>|>(?P.*?)(?P=tag)\s*>)",
re.IGNORECASE | re.DOTALL,
)
_ANCHOR = re.compile(
- r"[^>]*?)(?:/>|>(?P.*?))",
+ r"<(?P(?:[A-Za-z_][\w.-]*:)?a)\b"
+ r"(?P[^>]*?)(?:/>|>(?P.*?)(?P=tag)\s*>)",
re.IGNORECASE | re.DOTALL,
)
-_COMMENT = re.compile(r"", re.DOTALL)
_ATTRIBUTE = re.compile(
r"""(?P[A-Za-z][A-Za-z0-9:_-]*)\s*=\s*(?:"(?P[^"]*)"|'(?P[^']*)')"""
)
@@ -88,12 +96,13 @@
class _MarkupStripper(HTMLParser):
"""Reduce rendered markup to readable text without republishing any of it."""
- def __init__(self) -> None:
- super().__init__(convert_charrefs=True)
+ def __init__(self, *, convert_charrefs: bool = True) -> None:
+ super().__init__(convert_charrefs=convert_charrefs)
self._parts: list[str] = []
self._suppressed = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ tag = tag.rsplit(":", 1)[-1]
if tag in _SUPPRESSED_TAGS:
self._suppressed += 1
elif tag in _BLOCK_TAGS or tag in _LINE_TAGS:
@@ -102,12 +111,14 @@ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None
self._parts.append(" ")
def handle_endtag(self, tag: str) -> None:
+ tag = tag.rsplit(":", 1)[-1]
if tag in _SUPPRESSED_TAGS:
self._suppressed = max(0, self._suppressed - 1)
elif tag in _BLOCK_TAGS:
self._parts.append("\n")
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ tag = tag.rsplit(":", 1)[-1]
if tag in _BLOCK_TAGS or tag in _LINE_TAGS:
self._parts.append("\n")
@@ -115,6 +126,10 @@ def handle_data(self, data: str) -> None:
if not self._suppressed:
self._parts.append(data)
+ def unknown_decl(self, data: str) -> None:
+ if data.startswith("CDATA["):
+ self.handle_data(data[len("CDATA[") :])
+
def text(self) -> str:
return "".join(self._parts)
@@ -165,6 +180,144 @@ def _sync(self, attrs: list[tuple[str, str | None]]) -> None:
self._parts.append(f" ({value})")
+class _TeiToText(_MarkupStripper):
+ """Read TEI's visible structure while retaining all unsuppressed text.
+
+ The entry/sense labels and line, paragraph, table and list boundaries follow
+ SWORD's TEI rendering conventions. Notes are kept in brackets because a text API
+ has no separate popup in which to display their contents. Unknown elements keep
+ their text; no dictionary-specific entries or language-specific rules are used.
+ """
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=False)
+ self._notes: list[int] = []
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ tag = tag.rsplit(":", 1)[-1]
+ if tag in _SUPPRESSED_TAGS:
+ self._suppressed += 1
+ return
+ if self._suppressed:
+ return
+ if tag in _TEI_BLOCK_TAGS or tag in _TEI_LINE_TAGS:
+ self._parts.append("\n")
+ elif tag in _TEI_CELL_TAGS:
+ self._parts.append(" ")
+ elif tag == "note":
+ self._notes.append(len(self._parts))
+ self._parts.append(" [")
+ if tag in {"entry", "entryfree", "sense", "item"}:
+ label = xml_attributes(self.get_starttag_text() or "").get("n")
+ if label:
+ self._parts.append(label + " ")
+
+ def handle_endtag(self, tag: str) -> None:
+ tag = tag.rsplit(":", 1)[-1]
+ if tag in _SUPPRESSED_TAGS:
+ self._suppressed = max(0, self._suppressed - 1)
+ elif self._suppressed:
+ return
+ elif tag in _TEI_BLOCK_TAGS or tag in {"item", "l", "row"}:
+ self._parts.append("\n")
+ elif tag in _TEI_CELL_TAGS:
+ self._parts.append(" ")
+ elif tag == "note" and self._notes:
+ start = self._notes.pop()
+ if "".join(self._parts[start + 1 :]).strip():
+ self._parts.append("] ")
+ else:
+ del self._parts[start:]
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ # Process empty XML elements as a pair. In particular, an empty note or
+ # script must never suppress the rest of the entry.
+ self.handle_starttag(tag, attrs)
+ self.handle_endtag(tag)
+
+ def handle_data(self, data: str) -> None:
+ if not self._suppressed:
+ # XML formatting whitespace is not a displayed line break.
+ self._parts.append(data.replace("\r", " ").replace("\n", " "))
+
+ def unknown_decl(self, data: str) -> None:
+ if data.startswith("CDATA["):
+ # CDATA is already literal text, including any entity-looking words.
+ self.handle_data(data[len("CDATA[") :])
+
+ def handle_entityref(self, name: str) -> None:
+ # Accept complete named entities, retaining unknown names literally.
+ # HTML's permissive partial decoding would turn ``¬it;`` into ``¬it;``.
+ if not self._suppressed:
+ self._parts.append(decode_xml_entities(f"&{name};"))
+
+ def handle_charref(self, name: str) -> None:
+ if not self._suppressed:
+ self._parts.append(xml_character_reference(name))
+
+
+class _ReferenceSource(_MarkupStripper):
+ """Keep active reference markup separate from literal examples and hidden text."""
+
+ def __init__(self, source_type: str) -> None:
+ super().__init__(convert_charrefs=False)
+ self._osis = source_type.strip().casefold() == "osis"
+ self._hidden: list[str] = []
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ local = tag.rsplit(":", 1)[-1]
+ if self._hidden:
+ if local in _SUPPRESSED_TAGS or local == "note":
+ self._hidden.append(local)
+ return
+ values = xml_attributes(self.get_starttag_text() or "")
+ if local in _SUPPRESSED_TAGS or (
+ self._osis
+ and local == "note"
+ and values.get("type", "").casefold() in {"strongsmarkup", "x-strongsmarkup"}
+ ):
+ self._hidden.append(local)
+ else:
+ self._parts.append(self.get_starttag_text() or "")
+
+ def handle_endtag(self, tag: str) -> None:
+ if self._hidden:
+ if self._hidden[-1] == tag.rsplit(":", 1)[-1]:
+ self._hidden.pop()
+ else:
+ self._parts.append(f"{tag}>")
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ if not self._hidden and tag.rsplit(":", 1)[-1] not in _SUPPRESSED_TAGS:
+ self._parts.append(self.get_starttag_text() or "")
+
+ def handle_data(self, data: str) -> None:
+ if not self._hidden:
+ self._parts.append(data)
+
+ def handle_entityref(self, name: str) -> None:
+ self.handle_data(f"&{name};")
+
+ def handle_charref(self, name: str) -> None:
+ self.handle_data(f"{name};")
+
+ def handle_comment(self, data: str) -> None:
+ self.handle_data(" ")
+
+ def unknown_decl(self, data: str) -> None:
+ if data.startswith("CDATA["):
+ # The visible example still contributes to reference occurrence counts,
+ # but literal [ characters must not be mistaken for an active tag.
+ self.handle_data(html.escape(data[len("CDATA[") :], quote=False))
+
+
+def _reference_source(value: str, source_type: str) -> str:
+ parser = _ReferenceSource(source_type)
+ parser.feed(value)
+ parser.close()
+ return parser.text()
+
+
def strip_markup(value: str) -> str:
parser = _MarkupStripper()
parser.feed(value)
@@ -180,6 +333,14 @@ def thml_text(value: str) -> str:
return _NOTE_SPACE.sub(" ", parser.text())
+def tei_text(value: str) -> str:
+ """The plain text of validated TEI source, including its visible structure."""
+ parser = _TeiToText()
+ parser.feed(value)
+ parser.close()
+ return parser.text()
+
+
def normalize_text(value: str) -> str:
"""One space between words, trimmed lines, at most one blank line between blocks."""
value = value.replace("\x00", "").replace("\r\n", "\n").replace("\r", "\n")
@@ -187,9 +348,8 @@ def normalize_text(value: str) -> str:
return _BLANK_LINES.sub("\n\n", "\n".join(lines)).strip()
-def clean_text(value: str, *, unescape: bool = True) -> str:
- if unescape:
- value = html.unescape(value)
+def clean_text(value: str) -> str:
+ """Normalize already-plain text without interpreting it as escaped markup."""
return normalize_text(value)
@@ -206,16 +366,19 @@ def extract_osis_references(*values: str) -> list[str]:
return sorted(references)
-def _attributes(value: str) -> dict[str, str]:
+def _attributes(value: str, source_type: str = "") -> dict[str, str]:
+ if source_type.strip().casefold() in {"tei", "osis"}:
+ return xml_attributes(value)
return {
match.group("name").casefold(): html.unescape(match.group("dq") or match.group("sq") or "")
for match in _ATTRIBUTE.finditer(value)
}
-def _display(inner: str | None) -> str:
+def _display(inner: str | None, source_type: str = "") -> str:
"""The words a reference shows, projected as the text is so they can be found in it."""
- return " ".join(thml_text(inner or "").split())
+ projector = {"tei": tei_text, "osis": osis_text}.get(source_type.strip().casefold(), thml_text)
+ return " ".join(projector(inner or "").split())
def _bible_target(value: str) -> str | None:
@@ -243,7 +406,7 @@ def _is_osis(reference: str) -> bool:
return bool(tokens) and all(_OSIS_REF.fullmatch(token.split("-")[0]) for token in tokens)
-def extract_markup_references(*values: str) -> list[MarkupReference]:
+def extract_markup_references(*values: str, source_type: str = "") -> list[MarkupReference]:
"""Every scripture reference the markup carries, in document order, with its display text.
The source markup is read first and the rendered form only when the source carries
@@ -264,12 +427,12 @@ def kind_of(reference: str) -> str:
for value in values:
# Comments carry no live markup, and every kind of tag is read in the order the
# document has them, so their display texts are located in the text in turn.
- value = _COMMENT.sub(" ", value)
+ value = _reference_source(value, source_type)
located: list[tuple[int, int, str, str, str]] = []
for match in _REFERENCE_TAG.finditer(value):
- attrs = _attributes(match.group("attrs"))
- display = _display(match.group("inner"))
- tag = match.group("tag").casefold()
+ attrs = _attributes(match.group("attrs"), source_type)
+ display = _display(match.group("inner"), source_type)
+ tag = match.group("tag").rsplit(":", 1)[-1].casefold()
span = (match.start(), match.end())
if tag == "scripref":
parsed = attrs.get("parsed", "").replace("|", " ").strip()
@@ -288,9 +451,9 @@ def kind_of(reference: str) -> str:
if target:
located.append((*span, kind_of(target), target, display))
for match in _ANCHOR.finditer(value):
- attrs = _attributes(match.group("attrs"))
+ attrs = _attributes(match.group("attrs"), source_type)
href = attrs.get("href", "")
- display = _display(match.group("inner"))
+ display = _display(match.group("inner"), source_type)
lowered = href.casefold()
span = (match.start(), match.end())
if lowered.startswith("sword://"):
@@ -307,7 +470,7 @@ def kind_of(reference: str) -> str:
before = ""
cursor = 0
for start, end, kind, reference, display in sorted(located, key=lambda item: item[0]):
- before += " ".join(strip_markup(value[cursor:start]).split()) + " "
+ before += _display(value[cursor:start], source_type) + " "
cursor = end
occurrence = before.count(display) if display else 0
before += display + " "
@@ -322,15 +485,32 @@ def kind_of(reference: str) -> str:
return found
+class ContentProjectionError(ValueError):
+ """A source entry contains text but its public projection would discard it."""
+
+
def public_content(entry: dict[str, Any], *, source_type: str = "") -> dict[str, str]:
- """Project a validated contract entry onto the published text-only shape."""
- if source_type.strip().casefold() == "thml":
- text = clean_text(thml_text(str(entry.get("raw", ""))), unescape=False)
+ """Project a validated contract entry onto the unchanged v1 text-only shape."""
+ projector = {"thml": thml_text, "tei": tei_text, "osis": osis_text}.get(
+ source_type.strip().casefold()
+ )
+ if source_type.strip().casefold() == "osis":
+ projector = partial(osis_text, testament=entry.get("verse", {}).get("testament"))
+ raw = str(entry.get("raw", ""))
+ rendered = str(entry.get("html", ""))
+ if projector and raw:
+ text = clean_text(projector(raw))
else:
text = clean_text(str(entry.get("plain", "")))
if not text:
- # A few modules leave the extractor's stripped field empty and carry the
- # definition only in the rendered form. Deriving text keeps those entries
- # addressable instead of dropping them when markup is not republished.
- text = clean_text(strip_markup(str(entry.get("html", ""))), unescape=False)
+ # rendered_default may still be source markup, not HTML: use the same
+ # format-aware reader so a fallback cannot reintroduce flattened TEI/OSIS.
+ text = clean_text((projector or strip_markup)(rendered))
+ if not text and clean_text(strip_markup(_reference_source(raw, source_type))):
+ key = entry.get("key", entry.get("osis_id", "unknown"))
+ raise ContentProjectionError(
+ f"Entry {key!r} ({source_type or 'unspecified SourceType'}) contains source text "
+ "but its public text projection is empty; inspect the validated raw, stripped "
+ "and rendered fields before publishing this module"
+ )
return {"text": text}
diff --git a/src/study_builder/contract.py b/src/study_builder/contract.py
index dfd0288..1c03307 100644
--- a/src/study_builder/contract.py
+++ b/src/study_builder/contract.py
@@ -383,6 +383,9 @@ def _adapt_entry(record: dict[str, Any], sequence: int, encoding: str = "") -> d
return {
"key": key,
"raw": raw,
+ # Historical internal name: rendered_default can still be source
+ # markup when the extractor has no display filter installed. Select
+ # the public projection using SourceType, never this field's name.
"html": (
_text(rendered, f"record[{sequence}].rendered_default", encoding)
if rendered is not None
diff --git a/src/study_builder/dictionaries.py b/src/study_builder/dictionaries.py
index 8fa905a..0b040ef 100644
--- a/src/study_builder/dictionaries.py
+++ b/src/study_builder/dictionaries.py
@@ -347,7 +347,9 @@ def _document(
references = self.references.extract(
content["text"],
markup=extract_markup_references(
- str(source.get("raw", "")), str(source.get("html", ""))
+ str(source.get("raw", "")),
+ str(source.get("html", "")),
+ source_type=self.source_type,
),
book=self.references.aliases.resolve(item.key),
)
diff --git a/src/study_builder/osis.py b/src/study_builder/osis.py
new file mode 100644
index 0000000..1caa60d
--- /dev/null
+++ b/src/study_builder/osis.py
@@ -0,0 +1,200 @@
+# SPDX-License-Identifier: GPL-2.0-only
+"""Readable plain text from validated OSIS markup, without flattening its structure.
+
+This is a presentation adapter, not a SWORD module reader. It reads only the Unicode
+source that the extractor contract has already verified. The word annotations and
+bracketed notes follow SWORD's OSISPlain conventions; paragraph, poetry, list and
+milestone boundaries follow its display filters. Unknown inline elements retain
+their text, so an unrecognised presentation tag cannot discard a definition.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from html.parser import HTMLParser
+
+from study_builder.xmltext import decode_xml_entities, xml_attributes, xml_character_reference
+
+_BLOCKS = {"chapter", "div", "lg", "list", "p", "table", "title"}
+_LINES = {"item", "l", "row", "verse"}
+_FRAMED = {"divinename", "hi", "note", "q", "w"}
+_SUPPRESSED = {"script", "style"}
+_OVERLINE = {"ol", "overline", "x-overline"}
+
+
+@dataclass
+class _Frame:
+ tag: str
+ attrs: dict[str, str]
+ start: int
+
+
+def _local(tag: str) -> str:
+ return tag.rsplit(":", 1)[-1].casefold()
+
+
+def _unprefixed(value: str) -> str:
+ return value.partition(":")[2] if ":" in value else value
+
+
+class _OsisToText(HTMLParser):
+ def __init__(self, testament: int | None) -> None:
+ # OSIS is XML: numeric references name Unicode codepoints. HTML's automatic
+ # decoding remaps C1 references through Windows-1252, changing source text.
+ super().__init__(convert_charrefs=False)
+ self._testament = testament
+ self._parts: list[str] = []
+ self._frames: list[_Frame] = []
+ self._suppressed = 0
+
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ self._start(_local(tag), xml_attributes(self.get_starttag_text() or ""), False)
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ self._start(_local(tag), xml_attributes(self.get_starttag_text() or ""), True)
+
+ def _start(self, tag: str, attrs: dict[str, str], empty: bool) -> None:
+ if tag in _SUPPRESSED:
+ if not empty:
+ self._suppressed += 1
+ return
+ if self._suppressed:
+ return
+ if tag in _BLOCKS:
+ self._parts.append("\n")
+ elif tag in _LINES:
+ self._line_break()
+ elif tag in {"lb", "br"}:
+ # Optional breaks are layout hints, not a break in the source prose.
+ if attrs.get("type") != "x-optional":
+ self._parts.append("\n")
+ elif tag == "cell":
+ self._parts.append(" ")
+ elif tag == "milestone":
+ kind = attrs.get("type", "").casefold()
+ if kind in {"line", "x-p", "paragraph"}:
+ self._parts.append("\n")
+ if "marker" in attrs:
+ self._parts.append(attrs["marker"])
+ elif tag == "q" and empty:
+ if "sid" in attrs or "eid" in attrs:
+ self._parts.append(attrs.get("marker", ""))
+ elif tag == "w" and empty:
+ self._parts.append(self._word_annotations(attrs))
+ elif tag in _FRAMED and not empty:
+ self._frames.append(_Frame(tag, attrs, len(self._parts)))
+
+ def handle_endtag(self, tag: str) -> None:
+ tag = _local(tag)
+ if tag in _SUPPRESSED:
+ self._suppressed = max(0, self._suppressed - 1)
+ return
+ if self._suppressed:
+ return
+ if tag in _BLOCKS:
+ self._parts.append("\n")
+ elif tag in _LINES:
+ self._line_break()
+ elif tag == "cell":
+ self._parts.append(" ")
+ elif tag in _FRAMED:
+ for index in range(len(self._frames) - 1, -1, -1):
+ if self._frames[index].tag == tag:
+ # Entry fragments need not have all surrounding container tags.
+ # Finish any nested frame rather than dropping its text.
+ while len(self._frames) > index:
+ self._finish(self._frames.pop())
+ break
+
+ def _line_break(self) -> None:
+ # A poetry line or list item ends on the same boundary on which the next
+ # begins. XML indentation between tags must not create a blank line.
+ for part in reversed(self._parts):
+ if part.strip(" \t"):
+ if not part.rstrip(" \t").endswith("\n"):
+ self._parts.append("\n")
+ return
+
+ def _finish(self, frame: _Frame) -> None:
+ text = "".join(self._parts[frame.start :])
+ del self._parts[frame.start :]
+ if frame.tag == "w":
+ text += self._word_annotations(frame.attrs)
+ elif frame.tag == "note":
+ if frame.attrs.get("type", "").casefold() in {"strongsmarkup", "x-strongsmarkup"}:
+ # SWORD reserves these notes for annotation bookkeeping; they are
+ # not visible footnotes. Ordinary explanatory notes remain intact.
+ text = ""
+ elif text.strip():
+ text = f" [{text.strip()}] "
+ elif frame.tag == "divinename":
+ text = text.upper()
+ elif frame.tag == "hi" and text.strip():
+ kind = frame.attrs.get("type") or frame.attrs.get("rend", "")
+ if kind.casefold() in _OVERLINE:
+ text = "".join(character + "\u0305" for character in text)
+ else:
+ text = f"* {text} *"
+ elif frame.tag == "q":
+ # Explicit markers are source content. Do not invent default quotation
+ # marks: the OSISqToTick display setting is not part of this projection.
+ marker = frame.attrs.get("marker", "")
+ text = marker + text + marker
+ self._parts.append(text)
+
+ def _word_annotations(self, attrs: dict[str, str]) -> str:
+ parts: list[str] = []
+ if attrs.get("xlit"):
+ parts.append(f" <{_unprefixed(attrs['xlit'])}>")
+ if attrs.get("gloss"):
+ parts.append(f" <{attrs['gloss']}>")
+ for lemma in attrs.get("lemma", "").split():
+ value = _unprefixed(lemma)
+ if value.isascii() and value.isdigit() and self._testament in {1, 2}:
+ value = ("H" if self._testament == 1 else "G") + value
+ if value:
+ parts.append(f" <{value}>")
+ for morph in attrs.get("morph", "").split():
+ value = _unprefixed(morph)
+ if len(value) > 2 and value[:2] in {"TG", "TH"} and value[2].isdigit():
+ value = value[2:]
+ if value:
+ parts.append(f" ({value})")
+ if attrs.get("pos"):
+ parts.append(f" <{_unprefixed(attrs['pos'])}>")
+ return "".join(parts)
+
+ def handle_data(self, data: str) -> None:
+ if not self._suppressed:
+ # Newlines used to lay out the XML itself are ordinary whitespace.
+ self._parts.append(data.replace("\r", " ").replace("\n", " "))
+
+ def handle_entityref(self, name: str) -> None:
+ if not self._suppressed:
+ self._parts.append(decode_xml_entities(f"&{name};"))
+
+ def handle_charref(self, name: str) -> None:
+ if not self._suppressed:
+ self._parts.append(xml_character_reference(name))
+
+ def unknown_decl(self, data: str) -> None:
+ if data.startswith("CDATA["):
+ self.handle_data(data[6:])
+
+ def text(self) -> str:
+ while self._frames:
+ self._finish(self._frames.pop())
+ return "".join(self._parts)
+
+
+def osis_text(value: str, *, testament: int | None = None) -> str:
+ """Project OSIS source into unnormalised plain text, decoding entities once.
+
+ ``testament`` is the extractor's verified verse context (1 = OT, 2 = NT), used
+ only for Strong's lemma numbers that omit their G/H prefix. Without context,
+ retain the source number rather than guessing its language.
+ """
+ parser = _OsisToText(testament)
+ parser.feed(value)
+ parser.close()
+ return parser.text()
diff --git a/src/study_builder/xmltext.py b/src/study_builder/xmltext.py
new file mode 100644
index 0000000..90e4ae4
--- /dev/null
+++ b/src/study_builder/xmltext.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: GPL-2.0-only
+"""Decode XML presentation text without HTML's lossy entity substitutions."""
+
+from __future__ import annotations
+
+import re
+from html.entities import html5
+
+_ENTITY = re.compile(r"&(?P\#[xX][0-9A-Fa-f]+|\#[0-9]+|[A-Za-z][A-Za-z0-9]*);")
+_ATTRIBUTE = re.compile(
+ r"""(?P[A-Za-z_:][A-Za-z0-9_.:-]*)\s*=\s*(?:"(?P[^"]*)"|'(?P[^']*)')"""
+)
+
+
+def xml_character_reference(name: str) -> str:
+ """Decode a numeric reference, preserving invalid XML characters literally."""
+ try:
+ codepoint = int(name[1:], 16) if name[:1].casefold() == "x" else int(name, 10)
+ if (
+ (codepoint < 0x20 and codepoint not in {9, 10, 13})
+ or 0xD800 <= codepoint <= 0xDFFF
+ or codepoint in {0xFFFE, 0xFFFF}
+ ):
+ raise ValueError("Not a valid XML character")
+ return chr(codepoint)
+ except (ValueError, OverflowError):
+ return f"{name};"
+
+
+def decode_xml_entities(value: str) -> str:
+ """Decode complete references exactly once, never a prefix of an unknown name.
+
+ Legacy TEI/OSIS sources also use named entities such as `` `` and
+ ``Α``. Accept those exact names without HTML's permissive partial-name
+ matching or its Windows-1252 remapping of numeric references.
+ """
+
+ def replace(match: re.Match[str]) -> str:
+ name = match.group("name")
+ if name.startswith("#"):
+ return xml_character_reference(name[1:])
+ return html5.get(name + ";", match.group(0))
+
+ return _ENTITY.sub(replace, value)
+
+
+def xml_attributes(tag_source: str) -> dict[str, str]:
+ """Read quoted XML attributes directly from the original start tag.
+
+ HTMLParser always decodes attribute values using HTML rules, including when
+ ``convert_charrefs=False``. Reading its original tag text avoids that earlier,
+ irreversible conversion. Names are case-folded just as in HTMLParser's API.
+ """
+ return {
+ match.group("name").casefold(): decode_xml_entities(
+ match.group("dq") if match.group("dq") is not None else match.group("sq")
+ )
+ for match in _ATTRIBUTE.finditer(tag_source)
+ }
diff --git a/tests/test_commentaries.py b/tests/test_commentaries.py
index bfc4c26..cab94de 100644
--- a/tests/test_commentaries.py
+++ b/tests/test_commentaries.py
@@ -1,4 +1,5 @@
import json
+from dataclasses import replace
import pytest
@@ -73,7 +74,7 @@ def test_commentary_matches_v3_book_chapter_verse_contract(
1,
1,
"A comment on creation.",
- raw='John 1:1',
+ raw=']A comment on creation.
',
html="A comment on creation.
",
)
],
@@ -263,10 +264,20 @@ def test_collapsed_entry_keeps_every_reference_from_the_range(
commentary_module,
[
entry(
- "Gen.1.1", 1, 1, 1, shared, raw='see it'
+ "Gen.1.1",
+ 1,
+ 1,
+ 1,
+ shared,
+ raw='A comment on the passage.',
),
entry(
- "Gen.1.2", 1, 1, 2, shared, raw='see it'
+ "Gen.1.2",
+ 1,
+ 1,
+ 2,
+ shared,
+ raw='A comment on the passage.',
),
],
)
@@ -333,3 +344,71 @@ def test_prose_references_inherit_the_commented_book_and_chapter(
assert introduction["entries"][0]["references"] == [
{"text": "1:1", "ref": "John 1:1", "osis": "John.1.1", "book": 43, "chapter": 1, "verse": 1}
]
+
+
+@pytest.mark.parametrize("source_type", ["TEI", "OSIS"])
+def test_source_projection_keeps_commentary_introductions_and_composed_documents(
+ tmp_path, project_root, commentary_module, source_type
+) -> None:
+ module = replace(
+ commentary_module,
+ fields={**commentary_module.fields, "sourcetype": (source_type,)},
+ )
+ reference = (
+ '[John 1:1](John.1.1)'
+ if source_type == "TEI"
+ else 'John 1:1'
+ )
+ raw = f"α & word
中文; שָׁלוֹם.
See {reference}.
"
+ record, _ = write(
+ tmp_path,
+ project_root,
+ module,
+ [
+ entry("John.0.0", 43, 0, 0, "", raw="α"),
+ entry(
+ "John.1.0",
+ 43,
+ 1,
+ 0,
+ "Flattened chapter introduction",
+ raw="Introduction & literal β.
",
+ ),
+ entry("John.1.1", 43, 1, 1, "Lossy flattened projection", raw=raw),
+ entry("John.1.2", 43, 1, 2, "Lossy flattened projection", raw=raw),
+ ],
+ )
+ chapters = [
+ json.loads((tmp_path / f"testcom/43/{number}.json").read_text(encoding="utf-8"))
+ for number in (0, 1)
+ ]
+ introduction, chapter = chapters
+ assert introduction["entries"][0]["text"] == "α"
+ assert introduction["entries"][0]["verse"] == 0
+ assert chapter["entries"][0]["text"] == "Introduction & literal β."
+ assert chapter["entries"][0]["verse"] == 0
+ published = chapter["entries"][1]
+ assert [line for line in published["text"].splitlines() if line] == [
+ "α & word",
+ "中文; שָׁלוֹם.",
+ "See John 1:1.",
+ ]
+ assert (published["verse"], published["verses"], published["osis"]) == (1, [1, 2], "John.1.1")
+ assert published["references"] == [
+ {
+ "text": "John 1:1",
+ "ref": "John 1:1",
+ "osis": "John.1.1",
+ "book": 43,
+ "chapter": 1,
+ "verse": 1,
+ }
+ ]
+ assert set(published) == {"book", "chapter", "verse", "verses", "osis", "text", "references"}
+ book = json.loads((tmp_path / "testcom/43.json").read_text(encoding="utf-8"))
+ complete = json.loads((tmp_path / "testcom.json").read_text(encoding="utf-8"))
+ assert book["schema"] == "getbible-commentary-book-v1"
+ assert book["chapters"] == chapters
+ assert complete["schema"] == "getbible-commentary-v1"
+ assert complete["books"] == [book]
+ assert (record["book_count"], record["chapter_count"], record["entry_count"]) == (1, 2, 3)
diff --git a/tests/test_content.py b/tests/test_content.py
index 6a76085..5ef3e79 100644
--- a/tests/test_content.py
+++ b/tests/test_content.py
@@ -1,9 +1,14 @@
+import pytest
+
from study_builder.content import (
+ ContentProjectionError,
+ clean_text,
extract_markup_references,
extract_osis_references,
normalize_text,
public_content,
strip_markup,
+ tei_text,
thml_text,
)
from study_builder.references import MarkupReference
@@ -60,12 +65,142 @@ def test_thml_text_keeps_breaks_and_swords_conventions() -> None:
def test_thml_modules_are_projected_from_their_source_not_the_flattened_form() -> None:
entry = {"raw": "First
Second", "plain": "First Second", "html": ""}
assert public_content(entry, source_type="ThML") == {"text": "First\nSecond"}
- assert public_content(entry, source_type="TEI") == {"text": "First Second"}
+ assert public_content(entry, source_type="TEI") == {"text": "First\nSecond"}
assert public_content(
{"raw": "", "plain": "", "html": "Rendered
"}, source_type="ThML"
) == {"text": "Rendered"}
+def test_tei_preserves_dictionary_fields_senses_and_scripture_labels() -> None:
+ raw = (
+ 'ἀήρ
'
+ 'ajhvr aer '
+ "{ah-ayr'}Air: α α & <literal>.
"
+ 'The air. '
+ '[John]
3:8'
+ 'The sky.Usage note.'
+ )
+ content = public_content({"raw": raw, "plain": "109. flattened"}, source_type=" TEI ")
+ assert content == {
+ "text": "109 ἀήρ\najhvr aer {ah-ayr'}\nAir: α α & .\n\n"
+ "1 The air. John\n3:8\n\n2 The sky. [Usage note.]"
+ }
+ assert extract_markup_references(raw, source_type="TEI") == [
+ MarkupReference("osis", "John.3.8", "John 3:8")
+ ]
+
+
+def test_tei_source_newlines_are_whitespace_and_explicit_breaks_are_preserved() -> None:
+ assert normalize_text(tei_text("wrapped\r\n definition\n continues
next")) == (
+ "wrapped definition continues\nnext"
+ )
+
+
+def test_tei_lists_tables_and_unknown_elements_keep_their_text() -> None:
+ raw = (
+ 'Forms- First
- Second
'
+ ""
+ 'Retained words.'
+ "translation
follows"
+ )
+ lines = normalize_text(tei_text(raw)).splitlines()
+ assert [line for line in lines if line] == [
+ "Forms",
+ "a First",
+ "b Second",
+ "α a",
+ "β b",
+ "Retained words.translation follows",
+ ]
+
+
+def test_tei_namespaces_notes_and_cdata_do_not_discard_content() -> None:
+ raw = (
+ "Text continues."
+ "Actual note"
+ " content]]> survives"
+ "suppressed"
+ )
+ assert public_content({"raw": raw}, source_type="TEI") == {
+ "text": "Text continues.\n[Actual note]\nliteral & content survives"
+ }
+
+
+def test_tei_empty_note_cleanup_never_removes_literal_empty_brackets() -> None:
+ raw = (
+ "Use [] for an empty list. "
+ " "
+ )
+ assert public_content({"raw": raw}, source_type="TEI") == {
+ "text": "Use [] for an empty list. literal [] text"
+ }
+
+
+def test_tei_visible_attribute_values_follow_xml_entity_rules() -> None:
+ raw = 'firstsecond'
+ assert public_content({"raw": raw}, source_type="TEI") == {
+ "text": "\x80 first\n\n¬it; α second"
+ }
+
+
+@pytest.mark.parametrize("source_type", ["TEI", "ThML", "OSIS"])
+def test_markup_entities_are_decoded_once(source_type: str) -> None:
+ raw = "α α β <literal>
"
+ assert public_content({"raw": raw}, source_type=source_type) == {
+ "text": "α α β <literal>"
+ }
+
+
+def test_tei_preserves_unknown_entities_and_xml_numeric_codepoints() -> None:
+ raw = "¬it; Α
next"
+ assert public_content({"raw": raw}, source_type="TEI") == {
+ "text": "¬it; Α \x80 \nnext"
+ }
+
+
+def test_plain_text_is_never_reinterpreted_as_entities_or_markup() -> None:
+ text = "literal 中 ¬it; & ordinary text"
+ assert clean_text(text) == text
+ assert public_content({"plain": text}, source_type="Plain") == {"text": text}
+
+
+def test_tei_projection_preserves_every_source_language() -> None:
+ text = "ὅς 包括阴性的 he שלום"
+ assert public_content({"raw": f"{text}"}, source_type="TEI") == {"text": text}
+
+
+@pytest.mark.parametrize("source_type", ["TEI", "OSIS"])
+def test_rendered_fallback_can_still_be_source_markup(source_type: str) -> None:
+ assert public_content(
+ {"raw": "", "plain": "", "html": "α
β α
"}, source_type=source_type
+ ) == {"text": "α\nβ α"}
+
+
+@pytest.mark.parametrize("source_type", ["TEI", "ThML", "OSIS", ""])
+def test_empty_or_suppressed_source_is_not_a_projection_failure(source_type: str) -> None:
+ raw = "
"
+ assert public_content({"raw": raw}, source_type=source_type) == {"text": ""}
+
+
+@pytest.mark.parametrize("source_type", ["TEI", "OSIS"])
+def test_namespaced_suppressed_source_does_not_trigger_content_loss(source_type: str) -> None:
+ raw = "hiddenhidden"
+ assert public_content({"raw": raw}, source_type=source_type) == {"text": ""}
+
+
+def test_osis_metadata_only_notes_are_not_lost_visible_content() -> None:
+ raw = 'internal metadata'
+ assert public_content({"raw": raw}, source_type="OSIS") == {"text": ""}
+
+
+def test_nonempty_source_cannot_be_silently_omitted_when_projections_are_empty() -> None:
+ with pytest.raises(ContentProjectionError, match="Entry 'lost'.*GBF.*source text"):
+ public_content(
+ {"key": "lost", "raw": "A definition", "plain": "", "html": ""}, source_type="GBF"
+ )
+
+
def test_osis_references_are_extracted_from_markup_and_sword_uris() -> None:
references = extract_osis_references(
'a', "sword://Bible/Gen.2.3"
@@ -146,3 +281,43 @@ def test_empty_reference_tags_comments_and_order_are_read_as_the_document_has_th
MarkupReference("passage", "John 3:16", "John 3:16"),
MarkupReference("passage", "Gen 3:1", "Gen 3:1 [n]"),
]
+
+
+@pytest.mark.parametrize(
+ ("source_type", "tag", "attribute"),
+ [
+ ("TEI", "tei:ref", 'target="Bible:John.3.16"'),
+ ("OSIS", "osis:reference", 'osisRef="John.3.16"'),
+ ],
+)
+def test_namespaced_markup_references_keep_displayed_labels(
+ source_type: str, tag: str, attribute: str
+) -> None:
+ raw = f"<{tag} {attribute}>John
3:16{tag}>"
+ assert extract_markup_references(raw, source_type=source_type) == [
+ MarkupReference("osis", "John.3.16", "John 3:16")
+ ]
+
+
+def test_literal_or_hidden_markup_is_not_extracted_as_a_reference() -> None:
+ raw = (
+ '1:1]]>'
+ ''
+ '[1:1]'
+ '1:1'
+ ' tail
") == "word tail"
+
+
+def test_fragment_closure_does_not_discard_nested_annotation_text() -> None:
+ assert text('First\nline
endA note') == (
+ "First line end [A * note *]"
+ )