Fixing invisible endnotes
Claude just surprised me by offering to rewrite a whole epub so the references worked better.
I’m reading an academic biography as an epub on my Kobo reader. Great book and I’m really curious about the sourcing. Unfortunately the book is published in “invisible endnote” form. The text itself has no footnotes at all. There’s 200 pages of endnotes, they reference the main text with small quotes like “(p. 77) a field full of dropsical chickens”. This kind of formatting works OK in a paper book, but it’s a real shame in an ebook.
So I was asking Claude if this is how the original book was published (it is). And then it volunteered on its own “I could fix this”. It never would have occurred to me to ask! 5 minutes later I had a better formatted epub.
Claude’s first pass worked OK but didn’t look great on my Kobo. I worked a bit more to get it to fix some epub formatting problems and to locate some hard-to-correlate quotes back to the original text. The second copy looks great.
I’m flabbergasted. The algorithm it uses is simple enough, as are the technical edits. But it never would have occurred to me to try, nor would I have spent the hours it would take to make it word. Claude/Opus did it with barely a thought.
I think this endnote tool is useful enough it could be turned into a Calibre plugin. I probably won’t bother, it’s a lot of product management and testing. I’m also kind of liking this world of ephemeral software where it’s so easy now to build working code we don’t even bother sharing or keeping it.
I’ve pasted the code Claude generated below just to archive it. I haven’t even looked at it at all. I’m not reviewing most AI generated code anymore.
#!/usr/bin/env python3
"""Add working, visible endnote references to an EPUB with "phrase-keyed" notes.
Many trade non-fiction ebooks have endnotes that look like this:
10 “I own, but not quite”: Marianne Thornton to ..., KCC.
The page number links back to the start of a page in the text, but nothing in
the text links forward to the note. This script:
* finds every note in the Notes section and the cue phrase it glosses,
* locates that phrase in the body text (starting at the page the note cites),
* inserts a bold superscript note number after the phrase (and its closing
quote/punctuation) that links to the note,
* numbers the notes chapter by chapter and makes the number in front of each
note a link back to the exact spot in the text,
* applies a few conservative stylesheet fixes for Kobo's renderer (centered
text that was pushed off-center by indents, hard-coded font families, a
stretched cover image, <br> elements styled as blocks).
Everything else in the book is left as-is. Only the files that change are
re-serialized.
Usage:
python3 link_endnotes.py book.epub [-o out.epub] [--report notes.txt]
Requires lxml.
"""
import argparse
import bisect
import posixpath
import re
import sys
import zipfile
from collections import defaultdict
from urllib.parse import unquote
from lxml import etree
XHTML_NS = "http://www.w3.org/1999/xhtml"
OPF_NS = "http://www.idpf.org/2007/opf"
CONTAINER_NS = "urn:oasis:names:tc:opendocument:xmlns:container"
SVG_NS = "http://www.w3.org/2000/svg"
def X(tag):
return f"{{{XHTML_NS}}}{tag}"
BLOCK_TAGS = {X(t) for t in (
"p", "div", "blockquote", "h1", "h2", "h3", "h4", "h5", "h6",
"li", "td", "th", "table", "tr", "ul", "ol", "dl", "dd", "dt", "body")}
HEADING_TAGS = {X(t) for t in ("h1", "h2", "h3", "h4", "h5", "h6")}
MAJOR_HEADING_TAGS = {X("h1"), X("h2")}
VOID_TAGS = {X(t) for t in (
"area", "base", "br", "col", "embed", "hr", "img", "input", "link",
"meta", "param", "source", "track", "wbr")}
# Characters that the note marker is moved past so it lands after punctuation,
# as in print (Chicago style: after everything except dashes).
TRAILING_PUNCT = set(".,;:!?)]’”'\"")
# Classes and ids this script adds. Short names keep the markup light.
MARKER_CLASS = "nref" # <sup class="nref"><a ...>12</a></sup> in the text
NOTE_NUM_CLASS = "nnum" # <a class="nnum">12.</a> at the start of a note
REF_ID = "nref{}"
NOTE_ID = "note{}"
EXTRA_CSS = f"""
/* ---- Added by link_endnotes.py ---- */
/* Note numbers in the text: bold superscript, no underline, so they read
clearly on e-ink. line-height: 0 keeps them from spreading lines apart. */
sup.{MARKER_CLASS} {{
font-size: 0.7em;
font-style: normal;
font-weight: bold;
line-height: 0;
vertical-align: super;
text-indent: 0;
}}
sup.{MARKER_CLASS} a {{
color: inherit;
text-decoration: none;
}}
/* Note number at the start of each note, linking back to the text. */
a.{NOTE_NUM_CLASS} {{
color: inherit;
font-weight: bold;
font-style: normal;
text-decoration: none;
}}
img {{
max-width: 100%;
}}
"""
# --------------------------------------------------------------------------
# EPUB container helpers
class Book:
def __init__(self, path):
with zipfile.ZipFile(path) as z:
self.names = z.namelist()
self.data = {n: z.read(n) for n in self.names}
container = etree.fromstring(self.data["META-INF/container.xml"])
self.opf_path = container.find(f".//{{{CONTAINER_NS}}}rootfile").get("full-path")
self.opf_dir = posixpath.dirname(self.opf_path)
self.opf = etree.fromstring(self.data[self.opf_path])
manifest = {}
for item in self.opf.iter(f"{{{OPF_NS}}}item"):
manifest[item.get("id")] = (self.resolve(self.opf_dir, item.get("href")),
item.get("media-type"))
self.manifest = manifest
self.spine = [manifest[ref.get("idref")][0]
for ref in self.opf.iter(f"{{{OPF_NS}}}itemref")]
self.stylesheets = [p for p, mt in manifest.values() if mt == "text/css"]
self._trees = {}
self.dirty = set()
@staticmethod
def resolve(base_dir, href):
return posixpath.normpath(posixpath.join(base_dir, unquote(href)))
def tree(self, path):
if path not in self._trees:
parser = etree.XMLParser(resolve_entities=False, strip_cdata=False)
self._trees[path] = etree.fromstring(self.data[path], parser).getroottree()
return self._trees[path]
def href(self, from_path, to_path, fragment=None):
rel = posixpath.relpath(to_path, posixpath.dirname(from_path) or ".")
return f"{rel}#{fragment}" if fragment else rel
def split_href(self, from_path, href):
path, _, frag = href.partition("#")
if not path:
return from_path, frag
return self.resolve(posixpath.dirname(from_path), path), frag
def write(self, out_path):
for path in self.dirty:
if path in self._trees:
tree = self._trees[path]
# Keep <a id="x"></a> from becoming <a id="x"/>, which an
# HTML parser (these files are named .html) reads as an
# unclosed link swallowing the rest of the paragraph.
for el in tree.iter():
if isinstance(el.tag, str) and el.tag.startswith(f"{{{XHTML_NS}}}") \
and el.tag not in VOID_TAGS and el.text is None and len(el) == 0:
el.text = ""
self.data[path] = etree.tostring(
tree, xml_declaration=True, encoding="utf-8",
doctype=tree.docinfo.doctype or None)
with zipfile.ZipFile(out_path, "w") as z:
# mimetype must be first and stored uncompressed.
z.writestr(zipfile.ZipInfo("mimetype"), self.data["mimetype"],
compress_type=zipfile.ZIP_STORED)
for name in self.names:
if name == "mimetype" or name.endswith("/"):
continue
z.writestr(name, self.data[name], compress_type=zipfile.ZIP_DEFLATED)
# --------------------------------------------------------------------------
# Text normalization and a flat, searchable view of a document's body text
_CHAR_MAP = {
"‘": "'", "’": "'", "ʼ": "'", "′": "'", "`": "'",
"“": '"', "”": '"', "„": '"', "″": '"',
"–": "-", "—": "-", "‒": "-", "‐": "-", "‑": "-",
"…": "...",
}
_DROP = {"", "", "", "", ""}
def normalize(s, keep_map=False):
"""Lowercase, unify quotes/dashes, collapse whitespace.
With keep_map, also return a list mapping each output index to the index
of the input character it came from.
"""
out, idx = [], []
for i, ch in enumerate(s):
if ch in _DROP:
continue
if ch.isspace():
if out and out[-1] == " ":
continue
rep = " "
else:
rep = _CHAR_MAP.get(ch, ch).lower()
for r in rep:
out.append(r)
idx.append(i)
return ("".join(out), idx) if keep_map else "".join(out)
class TextStream:
"""The body text of one document as a single string, with enough
bookkeeping to map string offsets back to text/tail slots in the tree."""
def __init__(self, root):
self.segments = [] # (start, element, "text" | "tail")
self.id_offsets = {} # id attribute -> raw offset
self.block_starts = [] # raw offsets where block elements begin/end
parts = []
pos = 0
def add(el, kind, s):
nonlocal pos
self.segments.append((pos, el, kind))
parts.append(s)
pos += len(s)
def walk(el):
is_elem = isinstance(el.tag, str)
if is_elem:
if el.get("id"):
self.id_offsets[el.get("id")] = pos
if el.tag in BLOCK_TAGS:
self.block_starts.append(pos)
if el.text:
add(el, "text", el.text)
for child in el:
walk(child)
if child.tail:
add(child, "tail", child.tail)
if el.tag in BLOCK_TAGS:
self.block_starts.append(pos)
body = root.find(X("body"))
walk(body)
self.raw = "".join(parts)
self.norm, self.norm_map = normalize(self.raw, keep_map=True)
self._seg_starts = [s[0] for s in self.segments]
def raw_offset(self, norm_index):
return self.norm_map[norm_index] if norm_index < len(self.norm_map) else len(self.raw)
def norm_offset(self, raw_index):
# First normalized index whose source is at or after raw_index.
lo, hi = 0, len(self.norm_map)
while lo < hi:
mid = (lo + hi) // 2
if self.norm_map[mid] < raw_index:
lo = mid + 1
else:
hi = mid
return lo
def block_end_after(self, raw_index):
for b in self.block_starts:
if b > raw_index:
return b
return len(self.raw)
def segment_before(self, raw_index):
"""The segment containing the character just before raw_index."""
i = bisect.bisect_right(self._seg_starts, raw_index - 1) - 1
return self.segments[i]
# --------------------------------------------------------------------------
# Finding the notes
class Note:
def __init__(self, para, notes_path, link, target_path, target_frag, cue, section):
self.para = para
self.notes_path = notes_path
self.link = link # the page-number <a>
self.target_path = target_path # body document the note refers to
self.target_frag = target_frag # page anchor in that document
self.cue = cue # the glossed phrase, as printed
self.section = section # index of the notes subsection
self.number = None # number within its section
self.gid = None # book-wide unique id number
self.match = None # (raw_start, raw_end) in target stream
self.how = None # how the match was found
self.insert_at = None # raw offset of the marker
def text_of(el):
return "".join(el.itertext())
def find_notes(book):
"""Walk the spine from the 'Notes' heading to the next major heading and
collect every paragraph that starts with a link into the body text."""
notes = []
in_notes = False
section, section_title = -1, ""
spine_set = set(book.spine)
for path in book.spine:
root = book.tree(path).getroot()
body = root.find(X("body"))
for el in body.iter():
if not isinstance(el.tag, str):
continue
if el.tag in MAJOR_HEADING_TAGS:
title = normalize(text_of(el)).strip()
if title == "notes":
in_notes = True
continue
if in_notes and title:
return notes
if not in_notes:
continue
if el.tag in HEADING_TAGS:
section += 1
section_title = " ".join(text_of(el).split())
continue
if el.tag != X("p"):
continue
link = next((a for a in el.iter(X("a")) if a.get("href")), None)
if link is None:
continue
link_text = text_of(link).strip()
full = text_of(el)
if not link_text or not full.lstrip().startswith(link_text):
continue
target_path, frag = book.split_href(path, link.get("href"))
if target_path not in spine_set or target_path == path:
continue
after = full.lstrip()[len(link_text):]
cue = after.split(":", 1)[0].strip() if ":" in after[:300] else ""
note = Note(el, path, link, target_path, frag, cue, max(section, 0))
note.section_title = section_title
notes.append(note)
return notes
# --------------------------------------------------------------------------
# Matching cue phrases in the text
_ELLIPSIS = re.compile(r"\s*(?:\.\s*){3,}\s*")
_BRACKETED = re.compile(r"\[[^\]]*\]")
def cue_patterns(cue):
"""(regex, strict) pairs for a cue, from strictest to loosest. Each
matches in the normalized text. Non-strict patterns are only tried near
the cited page."""
core = normalize(cue).strip(" \"'.,;")
if not core:
return []
def rx(s, loose_brackets=False):
chunks = _ELLIPSIS.split(s)
out = []
for chunk in chunks:
chunk = chunk.strip()
if not chunk:
continue
if loose_brackets:
# "[S]he" in the note may be "She" or "[S]he" in the text.
pieces = _BRACKETED.split(chunk)
brackets = _BRACKETED.findall(chunk)
p = re.escape(pieces[0])
for b, piece in zip(brackets, pieces[1:]):
inner = re.escape(b[1:-1])
p += rf"(?:\[?{inner}\]?)?" + re.escape(piece)
out.append(p)
else:
out.append(re.escape(chunk))
# Elided text between the pieces of a quotation.
return re.compile(r".{0,600}?".join(out), re.S) if out else None
pats = [(rx(core), True), (rx(core, loose_brackets=True), True)]
# Looser: the same words, ignoring punctuation ("‘nice,’ and" vs.
# "‘nice’ and", "re-emphasise" vs. "reemphasise").
words = re.findall(r"\w+", _ELLIPSIS.split(core)[0])
if len(words) >= 2:
pats.append((re.compile(r"\W*".join(words)), False))
# Words inserted by the text: "Oh Florence,” he wrote, “what a mean".
if len(words) >= 3:
pats.append((re.compile(r"\W+(?:\w+\W+){0,3}?".join(words)), False))
# The first or last few words, e.g. for a typo in the note ("Ihave").
if len(words) >= 4:
pats.append((re.compile(r"\W*".join(words[:3])), False))
pats.append((re.compile(r"\W*".join(words[-3:])), False))
# A quotation within the cue: the “oddities and the crudities”.
for quoted in re.findall(r'"([^"]+)"?', core):
qwords = re.findall(r"\w+", quoted)
if len(qwords) >= 2 and len(qwords) < len(words):
pats.append((re.compile(r"\W*".join(qwords)), False))
return [(p, strict) for p, strict in pats if p is not None]
def match_notes(book, notes, streams):
"""Find each note's cue in its target document, near its page anchor and
in note order."""
last_start = {} # target path -> norm offset of previous match
for note in notes:
stream = streams[note.target_path]
anchor_raw = stream.id_offsets.get(note.target_frag)
anchor = stream.norm_offset(anchor_raw) if anchor_raw is not None else 0
prev = last_start.get(note.target_path, 0)
# Notes appear in text order, and a cue starts on (or just before)
# the page the note cites.
windows = [
("page", max(anchor - 400, prev), anchor + 12000),
("near", max(anchor - 4000, 0), anchor + 30000),
("file", 0, len(stream.norm)),
]
for pi, (pat, strict) in enumerate(cue_patterns(note.cue)):
for wname, lo, hi in windows if strict else windows[:1]:
m = pat.search(stream.norm, lo, hi)
if m:
note.match = (stream.raw_offset(m.start()),
stream.raw_offset(m.end() - 1) + 1)
note.how = wname if pi == 0 else f"{wname}/loose{pi}"
if wname == "page":
last_start[note.target_path] = m.start()
break
if note.match:
break
def choose_insert_points(notes, streams):
"""Decide where each marker goes: after the cue, extended to the end of
the quotation it starts (if any), then past trailing punctuation. Never
past the start of the next cue in the same document or out of the
paragraph."""
by_doc = defaultdict(list)
for n in notes:
if n.match:
by_doc[n.target_path].append(n)
for path, doc_notes in by_doc.items():
stream = streams[path]
raw = stream.raw
starts = sorted(n.match[0] for n in doc_notes)
for n in doc_notes:
start, end = n.match
limit = stream.block_end_after(start)
later = [s for s in starts if s > start]
if later:
limit = min(limit, later[0])
pos = end
# If the cue ends inside a quotation, move to the end of it.
para_start = max((b for b in stream.block_starts if b <= start), default=0)
through = raw[para_start:end]
if through.count("“") > through.count("”"):
close = raw.find("”", pos, limit)
reopen = raw.find("“", pos, limit)
if close != -1 and (reopen == -1 or reopen > close) and close - pos < 400:
pos = close + 1
elif normalize(n.cue).lstrip().startswith('"'):
# A quoted cue with no quotation marks in the text is usually
# from a block quote: go to the end of the sentence.
m = re.compile(r"[.?!](?=[\s”’]|$)").search(raw, pos, limit)
if m and m.end() - pos < 300:
pos = m.end()
while pos < limit and raw[pos] in TRAILING_PUNCT:
pos += 1
n.insert_at = pos
# --------------------------------------------------------------------------
# Rewriting the documents
def make_marker(notes, stream_path, book):
sup = etree.Element(X("sup"))
sup.set("class", MARKER_CLASS)
for i, n in enumerate(notes):
a = etree.SubElement(sup, X("a"))
a.set("id", REF_ID.format(n.gid))
a.set("href", book.href(stream_path, n.notes_path, NOTE_ID.format(n.gid)))
a.text = str(n.number)
if i < len(notes) - 1:
a.tail = ","
return sup
def insert_markers(book, notes, streams):
by_doc = defaultdict(lambda: defaultdict(list))
for n in notes:
if n.insert_at is not None:
by_doc[n.target_path][n.insert_at].append(n)
for path, points in by_doc.items():
stream = streams[path]
# Back to front, so earlier offsets stay valid.
for pos in sorted(points, reverse=True):
group = sorted(points[pos], key=lambda n: n.gid)
marker = make_marker(group, path, book)
seg_start, el, kind = stream.segment_before(pos)
host = el if kind == "text" else el.getparent()
link = next((a for a in host.iterancestors(X("a")) if a.get("href")),
host if host.tag == X("a") and host.get("href") else None)
if link is not None:
# Don't nest links: put the marker right after the link.
marker.tail = link.tail
link.tail = None
link.addnext(marker)
continue
k = pos - seg_start
if kind == "text":
marker.tail = el.text[k:]
el.text = el.text[:k]
el.insert(0, marker)
else:
marker.tail = el.tail[k:]
el.tail = el.tail[:k]
el.addnext(marker)
book.dirty.add(path)
def rewrite_notes(book, notes):
for n in notes:
num = etree.Element(X("a"))
num.set("class", NOTE_NUM_CLASS)
num.text = f"{n.number}."
num.tail = " "
n.link.addprevious(num)
if n.para.get("id"):
num.set("id", NOTE_ID.format(n.gid))
else:
n.para.set("id", NOTE_ID.format(n.gid))
if n.insert_at is not None:
# The number and the page number both return to the exact spot
# in the text, not the top of the page.
back = book.href(n.notes_path, n.target_path, REF_ID.format(n.gid))
num.set("href", back)
n.link.set("href", back)
# "(p. 12)" so the page isn't mistaken for the note number.
page = text_of(n.link).strip()
if page.isdigit() and len(n.link) == 0:
n.link.text = f"(p. {page})"
book.dirty.add(n.notes_path)
def fix_stylesheets(book):
"""Kobo-oriented CSS fixes that don't change the book's design."""
for path in book.stylesheets:
css = book.data[path].decode("utf-8")
def fix_rule(m):
selector, body = m.group(1), m.group(2)
decls = [d.strip() for d in body.split(";") if d.strip()]
props = {d.split(":", 1)[0].strip().lower(): d for d in decls}
out = []
for d in decls:
prop = d.split(":", 1)[0].strip().lower()
# A hard-coded font the device doesn't have; let the reader's
# font setting apply instead.
if prop == "font-family":
continue
# An indent on centered text pushes it off-center.
if prop == "text-indent" and "text-align" in props and \
"center" in props["text-align"]:
continue
out.append(d)
if "text-align" in props and "center" in props["text-align"]:
out.append("text-indent: 0")
if not out:
return f"{selector} {{\n }}"
return f"{selector} {{\n " + ";\n ".join(out) + "\n }"
css = re.sub(r"([^{}]+?)\s*\{([^{}]*)\}", fix_rule, css)
# Headings such as chapter titles are wrapped in a block (originally
# a <blockquote>, see fix_markup) with a left margin, which shifts
# centered titles right.
centered = re.findall(r"(\.[\w-]+)\s*\{[^}]*text-align:\s*center", css)
if centered:
css += "\n" + ",\n".join(f"{c} > span" for c in centered) + \
" {\n margin-left: 0;\n margin-right: 0\n }\n"
css += EXTRA_CSS
book.data[path] = css.encode("utf-8")
def fix_markup(book):
"""Small markup fixes across all content documents."""
for path in book.spine:
root = book.tree(path).getroot()
changed = False
# <br class="..."> where the class says display: block renders as an
# extra blank line (or nothing) depending on the reader.
for br in root.iter(X("br")):
if br.get("class"):
del br.attrib["class"]
changed = True
# <h3><blockquote>...</blockquote></h3> isn't valid XHTML and strict
# renderers may mishandle it. A <span> with the same class (the
# class already says display: block) renders the same and is valid.
for heading in [e for e in root.iter() if e.tag in HEADING_TAGS]:
for bq in heading.iter(X("blockquote")):
bq.tag = X("span")
changed = True
# Cover pages stretched to the screen with preserveAspectRatio="none".
for svg in root.iter(f"{{{SVG_NS}}}svg"):
if svg.get("preserveAspectRatio") == "none":
svg.set("preserveAspectRatio", "xMidYMid meet")
changed = True
if changed:
book.dirty.add(path)
# --------------------------------------------------------------------------
def context(stream, pos, width=60):
s = stream.raw[max(0, pos - width):pos] + "⟦*⟧" + stream.raw[pos:pos + 25]
return " ".join(s.split())
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("epub")
ap.add_argument("-o", "--output", help="output path (default: '<name> - linked notes.epub')")
ap.add_argument("--report", help="write a line per note showing where its marker went")
args = ap.parse_args()
out = args.output or re.sub(r"\.epub$", "", args.epub, flags=re.I) + " - linked notes.epub"
book = Book(args.epub)
notes = find_notes(book)
if not notes:
sys.exit("No notes found (looked for a 'Notes' heading followed by "
"paragraphs starting with page links).")
# Number notes within each notes subsection (i.e. per chapter).
counters = defaultdict(int)
for gid, n in enumerate(notes, 1):
counters[n.section] += 1
n.number = counters[n.section]
n.gid = gid
streams = {p: TextStream(book.tree(p).getroot()) for p in {n.target_path for n in notes}}
match_notes(book, notes, streams)
choose_insert_points(notes, streams)
if args.report:
with open(args.report, "w", encoding="utf-8") as f:
for n in notes:
where = (context(streams[n.target_path], n.insert_at)
if n.insert_at is not None else "NOT FOUND")
f.write(f"[{n.section_title} / {n.number}] ({n.how or '-'}) {n.cue}\n"
f" {where}\n")
insert_markers(book, notes, streams)
rewrite_notes(book, notes)
fix_markup(book)
fix_stylesheets(book)
book.write(out)
found = sum(1 for n in notes if n.insert_at is not None)
loose = sum(1 for n in notes if n.how and n.how != "page")
print(f"{len(notes)} notes, {found} linked into the text "
f"({loose} needed a looser match - worth a glance in the report).")
for n in notes:
if n.insert_at is None:
print(f" not found: {n.section_title}, note {n.number}: {n.cue!r}")
print(f"Wrote {out}")
if __name__ == "__main__":
main()
