Skip to content

Keep character-normalization repairs to whole symbols and check them part by part - #149

Merged
caufieldjh merged 10 commits into
mainfrom
fix-char-normalization-128-129
Oct 27, 2026
Merged

caufieldjh merged 10 commits into
mainfrom
fix-char-normalization-128-129

Conversation

@caufieldjh

@caufieldjh caufieldjh commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #128 and #129. Both are in Strategy 1 (character normalization) of SupportingTextRepairer.attempt_repair.

#128: mappings rewrote parts of other symbols

  • apply_character_mappings now applies every mapping in one regex pass, longest key first. Where a key starts or ends with a letter or digit, no letter or digit (Unicode included) may sit directly next to it on that side. So CDKN2A, N2a, HEK293N2 and µO2 are left alone. A key that starts and ends with punctuation, such as +/-, applies anywhere, so 5 +- 2, 5+/-2 and +/-5 all become ±. Because there is only one pass, one mapping's output can't be rewritten by another. The compiled regex is cached.
  • New default mapping H2O2 → H₂O₂.
  • RepairConfig now rejects an empty character_mappings key, which would otherwise match between every character.
  • New skip_unverifiable option. Validation's normalization ignores punctuation, spells out Greek letters and folds ligatures, so it can't confirm a mapping that changes only those, such as +- → ± or a custom alpha → α. When such a mapping fires, Strategy 1 keeps it only if the repaired quote is in the reference as written, ignoring only case and whitespace. Otherwise it retries without those mappings. This is what keeps Ca2+-dependent and NAD+-linked intact. The check covers the whole quote, so any other differing punctuation (a curly quote, an en dash) also drops a correct ±. That is deliberate: every change in an accepted repair has been checked against the reference, so HIGH confidence still means it is safe to auto-apply.

#129: quotes with ... or [brackets] never repaired

  • New helper _all_parts_found splits a quote with _split_query and checks each part against the searchable texts, so SVG figures are still checked label by label. Strategy 1 and Strategy 2 (ellipsis) both use it now, so the two can't drift apart. attempt_repair normalizes the reference texts once and passes them in.

Tests

  • tests/test_repair.py: the reproduction cases from both issues and their comments. That covers ion charges, gene symbols, H2O2, 5+/-2, Unicode neighbours, a single pass, a single-letter user key, an empty key being rejected, a punctuation-only mapping both rejected and kept, the default +- mapping end to end, a Greek-letter mapping, a fallback that still fails, ..., brackets, both together, SVG parts in separate labels and across labels, and an ellipsis repair across SVG labels. Doctests were added for the new behaviour.
  • I added a note on mapping behaviour to docs/how-to/repair-validation-errors.md.
  • just test passes: 2068 tests, 288 doctests, ruff check and mypy.

Change in behaviour

Formulas joined directly to a coefficient or prefix are no longer mapped: 6CO2, 2H2O2, pCO2, 13CO2. The rule that protects CDKN2A and HEK293N2 also skips these. N2O isn't mapped either: it has no mapping of its own, and N2 and O2 are joined to other letters inside it. Tests pin these cases and the docs list them.

🤖 Generated with Claude Code

…part by part

Mappings now apply in one pass, longest first, and only where no ASCII
letter or digit adjoins them, so O2 is left alone in CDKN2A and +- in
Ca2+-dependent. H2O2 gets its own default mapping.

Validation ignores punctuation, so a mapping that changes only
punctuation is kept only when the reference has the repaired text as
written. The repaired quote is checked part by part, split on ... and
editorial brackets as validation splits it, through a helper shared
with the ellipsis strategy.

Fixes #128
Fixes #129

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 1m 20s —— View job


PR review: whole-symbol character mappings + part-by-part checks (#128, #129)

  • Read diff
  • Check helpers (normalize_text, normalize_whitespace, _split_query, searchable_texts)
  • Run tests: not done. Running uv run … needs approval in this job, so I could not run pytest or the doctests. My edge-case notes below come from reading the code, not from running it.
  • Post review

Overall: This is a good, focused fix. The single-pass, longest-first regex removes the chained-replacement bug. Moving the part-by-part check into _all_parts_found and using it in both Strategy 1 and Strategy 2 removes duplicated code that could drift apart. The literal fallback for punctuation-only mappings keeps HIGH confidence meaning "safe to auto-apply". The tests cover the reproduction cases from both issues well. I found no security concerns. My comments are mostly about edge cases of the new boundary rule.


1. The boundary rule now skips some common chemistry forms (behaviour change, worth deciding on)

repairer.py apply_character_mappings: (?<![A-Za-z0-9])…(?![A-Za-z0-9]) protects CDKN2A and Ca2+-, but it also stops these cases, which str.replace used to repair correctly:

Input Before After
6CO2 + 6H2O 6CO₂ + 6H₂O unchanged
2H2O2 2H₂O₂ unchanged
pCO2, 13CO2 pCO₂, 13CO₂ unchanged
N2O N₂O unchanged
5+/-2, 5+-2 5±2 unchanged

The PR body only lists +/-5. Stoichiometric coefficients and pCO2 are common in biomedical text, so I suggest at least listing these in the "Change in behaviour" section and the docs. Pinning one or two of them in tests would also make the trade-off explicit.

Possible refinement: the boundary rule exists to protect punctuation mappings like +- inside Ca2+-. But punctuation-only mappings are now checked literally against the reference anyway. You could therefore drop the boundary for those mappings, or only require it on edges where the key itself starts or ends with a letter or digit. That would bring back 5+/-2 → 5±2, and the literal check would still reject a wrong rewrite of Ca2+-. That is optional, but it removes most of the +/-5 regression at no cost to safety.

2. skip_punctuation covers more than punctuation

normalize(original) == normalize(replacement) really tests whether the validator can tell the two strings apart, and that is the right test. However, normalize_text also spells out Greek letters, so a user mapping such as "alpha": "α" or "beta": "β" counts as "punctuation-only" too. Ligatures fold the same way. The behaviour is correct, but the name and the docstring ("mappings that change only punctuation") are misleading. Consider a name like skip_unverifiable, or rewording the docstring and the docs paragraph to say "mappings that normalization cannot distinguish (punctuation, Greek letters spelled out, ligatures)".

3. The literal check is all-or-nothing across the whole quote

attempt_repair Strategy 1: if any unrelated punctuation in the quote differs from the reference, the literal check fails and every punctuation mapping is dropped, even a ± that is correct. Examples are " vs “, - vs –, or a missing comma. That errs on the safe side, so I would not block on it. It does mean +- → ± will rarely fire on real PDF-extracted text. A short comment noting this is deliberate would help future readers.

4. Performance (minor)

_all_parts_found normalizes every searchable text on each call. attempt_repair can now call it three times: literal, normalized, then the ellipsis strategy. Before this PR, searchable was computed once. For full-text references, each call runs a full pass of normalize_text and normalize_whitespace over the whole article, which can be hundreds of KB. One fix is to compute the normalized texts once in attempt_repair and pass them in. Another is to have the helper take already-normalized searchable and literal_searchable lists. The regex is also rebuilt on each apply_character_mappings call. That is negligible, but it could be cached per (mappings, skip_punctuation).

5. Test coverage gaps (small)

  • Fallback that still fails: no test covers the literal check failing and the retry without punctuation mappings also not validating. The expected result is no CHARACTER_NORMALIZATION action and no crash.
  • Documented behaviour change: no test covers it, e.g. "+/-5" stays unchanged. Adding one turns it into an intentional, regression-tested decision.
  • Strategy 2 through the shared helper: the ellipsis path with an SVG reference whose parts sit in different labels isn't tested. It now uses the shared helper, so a quick test would protect the refactor.
  • test_mappings_apply_in_one_pass: this is a good test. Consider also asserting that the boundary rule still holds for user-supplied single-letter keys. For example, with {"a": "b"}, "cat" should stay unchanged, because users may not expect that.

Nits

  • _all_parts_found is a private method, but its doctest has 4 examples. That's fine, and it matches the project's doctest-heavy style.
  • The docs say "no letter or digit". The regex only checks ASCII ([A-Za-z0-9]), so αO2 or µO2 would still be mapped. Either say "ASCII letter or digit", as the docstring already does, or switch to (?<![^\W_]) / (?!\w) if you want Unicode word characters.

Summary: The approach is sound and safe. The main thing to decide is whether the losses in point 1 (6CO2, pCO2, N2O, 5+/-2) are acceptable. If they are, document and test them. If not, the optional refinement in point 1 recovers the 5+/-2 case cheaply. The rest are naming, docs and small performance or test improvements.

The whole-symbol rule now only guards a mapping's letter or digit edges,
and treats Unicode letters and digits as neighbours too. Punctuation
mappings such as +/- apply anywhere again, so 5+/-2 becomes 5±2; the
literal check in attempt_repair is what keeps Ca2+-dependent intact.
Pin and document the formulas the rule still skips (6CO2, pCO2, N2O).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
The option leaves out every mapping that validation's normalization
cannot tell apart from the original, which includes spelled-out Greek
letters and ligatures as well as punctuation. Name and document it as
such, and test the Greek-letter case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
attempt_repair now normalizes the searchable texts once, both ways, and
passes them to _all_parts_found, instead of renormalizing a full-text
reference on each of up to three checks. The regex for a set of
mappings is compiled once and cached.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
Cover a normalization whose fallback still fails, an ellipsis repair
whose parts sit in separate SVG labels (Strategy 2 through the shared
helper), and a single-letter user key inside a word.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 1m 8s —— View job


PR review (re-review after the latest commits)

  • Read the diff (git diff origin/main...HEAD)
  • Check helpers (normalize_text, normalize_whitespace, _split_query, searchable_texts) and the callers of apply_character_mappings
  • Run tests: not done. uv run pytest needs approval in this job, so none of the notes below come from running the code.
  • Post review

Overall: The new commits deal with every point from the previous review:

  • Punctuation keys now ignore their neighbours, so 5+/-2 → 5±2 works again.
  • The boundary check uses Unicode letters and digits ([^\W_]), so µO2 and αCO2 are left alone.
  • skip_punctuation is renamed to skip_unverifiable.
  • A comment explains that the literal check covers the whole quote on purpose.
  • Reference texts are normalized once per repair, and the mapping regex is cached.
  • New tests cover a fallback that still fails, Strategy 2 across SVG labels, single-letter keys, and the formulas the boundary rule now skips (6CO2, pCO2, N2O).

The design is sound: punctuation mappings can now match anywhere, and the literal check against the reference stops them from damaging text like Ca2+-. I found no correctness bugs or security concerns. The remaining points are small.


1. The PR description is out of date

  • It still calls the option skip_punctuation. The code now calls it skip_unverifiable.
  • "Change in behaviour" says +/-5 is no longer mapped. That is no longer true: test_mappings_apply_only_to_whole_symbols checks "+/-5" → "±5". The real behaviour change is that letter and digit keys are now skipped when joined to another symbol: 6CO2, 2H2O2, pCO2, 13CO2, N2O. The docs and the tests already say this; only the PR body is stale. Worth fixing, because the squash commit message usually comes from the PR body.

2. The literal pass runs on every quote, even when it can't change anything (performance, minor)

repairer.py:473 builds literal_searchable, a lowercased copy of the whole reference, on every call. Lines 476–477 then always run the literal check. In the common case, no unverifiable mapping fires (for example, the quote has only CO2). The fallback at line 485 then returns the same string, so that work is wasted. For full-text references it is one extra pass over the article for every quote.

A cheap restructure:

verifiable = self.apply_character_mappings(supporting_text, skip_unverifiable=True)
normalized = self.apply_character_mappings(supporting_text)
if normalized != verifiable:
    literal_searchable = [normalize_whitespace(t) for t in texts]
    if not self._all_parts_found(normalized, literal_searchable, literal=True):
        normalized = verifiable

This only builds literal_searchable when there is a punctuation, Greek-letter or ligature change to check. It also makes the intent easier to read. Fix this →

3. Docs formatting nit

In docs/how-to/repair-validation-errors.md, the line whitespace. That is what keeps … Quotes with \...` or `[editorial brackets]` are checked part by` is much longer than the lines around it. It also joins the part-by-part sentence (the #129 fix) onto the end of the paragraph about unverifiable mappings. Splitting it into its own paragraph would read better.

4. Small edge cases (optional)

  • Empty mapping key: a key of "" now produces a regex that matches everywhere and inserts the replacement between every character. The old str.replace code had the same problem, so this isn't a regression. A field_validator on RepairConfig.character_mappings that rejects empty keys would be cheap.
  • Cache key: _mappings_pattern is cached on the mapping keys only, and the replacements are looked up per call. That is correct, and worth keeping in mind if anyone refactors it.
  • Redundant check: when the literal check passes, line 487 runs the normalized check as well. It can't fail at that point, but it is cheap and it states the invariant, so leaving it is fine.

Test coverage

Coverage is good. It covers the reproduction cases for #128 and #129, both outcomes of the punctuation-only mapping (rejected and kept), Greek letters counted as unverifiable, the single pass, SVG labels in both strategies, and the fallback that still fails. One gap: no attempt_repair test uses one of the default punctuation mappings, so the Ca2+- protection is only tested together with CO2. A test with a reference containing 5 ± 2 mM and the quote 5 +- 2 mM would cover the default +- mapping being kept end to end.


Summary: This is ready to merge from a correctness standpoint. Please update the PR description (point 1). Points 2–4 are optional polish. I couldn't run the tests, so please confirm CI is green.

When every mapping that applied is one validation can confirm, the
literal check cannot change the result, so skip it and the extra pass
over the reference it needs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
An empty key compiles to a pattern that matches between every
character, inserting its replacement throughout the quote.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Qm4PkPDe4fb4TDFQVmQJnq
@claude

claude Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @caufieldjh's task in 54s —— View job


PR review (after the latest commits)

  • Read the diff (git diff origin/main...HEAD)
  • Check what changed since the last review (commits 507a968…5d4ea8f)
  • Run tests: not done. uv run pytest needs approval in this job, so I read the code but did not run it. I did check pytest.ini: it sets ELLIPSIS, so the new ValidationError doctest should match.
  • Post review

Overall: The new commits deal with every point from my last review, and the PR description is now up to date:

  • The literal check only runs when an unverifiable mapping fired (normalized != verifiable). Otherwise literal_searchable is never built.
  • The part-by-part sentence in the docs now has its own paragraph.
  • RepairConfig rejects empty character_mappings keys, with a doctest.
  • test_default_plus_minus_mapping_repairs_end_to_end tests the default +- → ± mapping through attempt_repair.

I found no correctness bugs and no security concerns. I think this is ready to merge once CI is green.


Things I checked

  • Overlapping keys: the patterns are tried longest first, and the boundaries hold. In H2O2x, H2O2 fails its trailing check, H2O fails because a 2 follows it, and O2 fails because a 2 precedes it. Nothing is wrongly rewritten.
  • Fallback: when the literal check fails, normalized = verifiable. If that equals the original quote, the normalized != supporting_text guard skips Strategy 1, so no stray action is added. test_fallback_that_still_fails_does_not_repair covers this.
  • Literal mode: normalize_whitespace lowercases and collapses whitespace, which matches "ignoring only case and whitespace" in the docs and the comment.
  • Cache: _mappings_pattern is keyed on the tuple of mapping keys, and the replacements are looked up per call through mappings[match.group(0)]. That stays correct when only a replacement value changes.

Nits (optional)

  1. Validator placement: in models.py:338, _no_empty_mapping_keys sits between the character_mappings and skip_references field definitions. Pydantic handles that fine, but it splits up the field list. Moving it below the last field would read better.
  2. Small repeated work: apply_character_mappings runs normalize_text on every key and value on every call when skip_unverifiable=True. With 7 default mappings this costs almost nothing. If you want, you could cache the set of unverifiable keys per mapping dict, as _mappings_pattern already does for the regex.
  3. Case-sensitive keys: keys match case-sensitively (co2 is not mapped), but the literal check ignores case. That is reasonable. A short note in the docs could help users who write lowercase custom keys.

Test coverage

Good. The new tests cover:

I see no remaining gaps worth blocking on.

@caufieldjh
caufieldjh merged commit e17ddf9 into main Oct 27, 2026
7 checks passed
@caufieldjh
caufieldjh deleted the fix-char-normalization-128-129 branch October 27, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Character-normalization repair rewrites 'Ca2+-' to 'Ca2±' and 'CDKN2A' to 'CDKN₂A', and marks it safe to auto-fix

2 participants