proofix 0.6.0__tar.gz → 0.8.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. {proofix-0.6.0 → proofix-0.8.2}/PKG-INFO +3 -3
  2. {proofix-0.6.0 → proofix-0.8.2}/README.md +1 -1
  3. {proofix-0.6.0 → proofix-0.8.2}/man/proofix.1 +47 -3
  4. {proofix-0.6.0 → proofix-0.8.2}/proofix/__init__.py +1 -1
  5. proofix-0.8.2/proofix/api.py +514 -0
  6. proofix-0.8.2/proofix/basics.py +146 -0
  7. {proofix-0.6.0 → proofix-0.8.2}/proofix/cli.py +8 -3
  8. {proofix-0.6.0 → proofix-0.8.2}/proofix/commas.py +4 -14
  9. {proofix-0.6.0 → proofix-0.8.2}/proofix/consistency.py +40 -10
  10. {proofix-0.6.0 → proofix-0.8.2}/proofix/hygiene.py +57 -0
  11. proofix-0.8.2/proofix/lt.py +197 -0
  12. proofix-0.8.2/proofix/tiers.py +410 -0
  13. {proofix-0.6.0 → proofix-0.8.2}/pyproject.toml +2 -2
  14. proofix-0.8.2/tests/fixtures/audit.lt.json +34 -0
  15. proofix-0.8.2/tests/test_api.py +215 -0
  16. proofix-0.8.2/tests/test_audit.py +507 -0
  17. proofix-0.8.2/tests/test_basics.py +454 -0
  18. proofix-0.8.2/tests/test_comma_cache_merge.py +26 -0
  19. {proofix-0.6.0 → proofix-0.8.2}/tests/test_docs.py +11 -0
  20. {proofix-0.6.0 → proofix-0.8.2}/tests/test_e2e.py +6 -2
  21. proofix-0.8.2/tests/test_explain.py +122 -0
  22. proofix-0.8.2/tests/test_lt_server.py +174 -0
  23. {proofix-0.6.0 → proofix-0.8.2}/tests/test_units.py +8 -5
  24. proofix-0.6.0/proofix/api.py +0 -198
  25. proofix-0.6.0/proofix/lt.py +0 -97
  26. proofix-0.6.0/proofix/tiers.py +0 -133
  27. proofix-0.6.0/tests/test_api.py +0 -77
  28. {proofix-0.6.0 → proofix-0.8.2}/.gitignore +0 -0
  29. {proofix-0.6.0 → proofix-0.8.2}/LICENSE +0 -0
  30. {proofix-0.6.0 → proofix-0.8.2}/examples/typos.md +0 -0
  31. {proofix-0.6.0 → proofix-0.8.2}/proofix/report.py +0 -0
  32. {proofix-0.6.0 → proofix-0.8.2}/tests/conftest.py +0 -0
  33. {proofix-0.6.0 → proofix-0.8.2}/tests/fixtures/typos.lt.json +0 -0
  34. {proofix-0.6.0 → proofix-0.8.2}/tests/test_endpoint_cli.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: proofix
3
- Version: 0.6.0
3
+ Version: 0.8.2
4
4
  Summary: Fix typos and punctuation in Markdown: LanguageTool detects, a language model adjudicates, comma placement is corrected under a diff guard.
5
5
  Project-URL: Homepage, https://github.com/AndrewBroz/proofix
6
6
  Project-URL: Issues, https://github.com/AndrewBroz/proofix/issues
@@ -14,7 +14,7 @@ Classifier: Programming Language :: Python :: 3
14
14
  Classifier: Programming Language :: Python :: 3.11
15
15
  Classifier: Topic :: Text Processing :: Markup :: Markdown
16
16
  Requires-Python: >=3.11
17
- Requires-Dist: adjudicate<0.4,>=0.3.1
17
+ Requires-Dist: adjudicate<0.4,>=0.3.5
18
18
  Description-Content-Type: text/markdown
19
19
 
20
20
  # proofix
@@ -34,7 +34,7 @@ Run it after [stylefix](https://github.com/AndrewBroz/stylefix), so the grammar
34
34
  | tier | what | how | who decides |
35
35
  |---|---|---|---|
36
36
  | 0 hygiene | text that renders fine but is not what it looks like: HTML entities Markdown can carry plainly (`&#32;`, `&quot;`, `&mdash;`), zero-width spaces, byte-order marks, soft hyphens, control characters, Windows line endings, decomposed accents | fixed deterministically and logged; entities that would change Markdown's parsing (`&lt;`, `&gt;`, `&amp;`) or carry meaning (`&nbsp;`) are left alone and reported | applied outright, or noted |
37
- | 1 mechanical | space before a comma or period, missing space after one, doubled punctuation, doubled words, known misspellings | LanguageTool's single-answer rules, the `typos` tool, a small missing-space rule | applied outright |
37
+ | 1 mechanical | space before a comma or period, missing space after one, doubled punctuation, doubled words whose repeat is never grammatical (`the the`, `of of`), known misspellings | LanguageTool's single-answer rules, the `typos` tool, a small missing-space rule; the built-in `basics` check (doubled words always; spacing without LanguageTool) | applied outright only where right in every context (audited rule by rule): a typos fix only when the word is all lower case, has one correction, is not part of a word with a digit or underscore, and is a known short typo (`teh`) or four letters or more and not a contraction missing its apostrophe (`youre`); `..` (`.` or `…`, or `cd ..`), `Node.Js`, `.bashrc`, a paragraph opening `, and` go to the model with KEEP, or are listed for review without one; indentation, table alignment and Markdown hard line breaks are left alone. The closed list is `a an the of to at for with from into onto and or but nor it we they my your our their`; a double from it that LanguageTool's pass ran over without flagging, and every other double (`that that`, `had had`, `log in in`, `on on Monday`), goes to the model with KEEP, or is listed for review. A hyphen touching either copy (`to to-do`) is no double |
38
38
  | 2 adjudicated | unknown words with candidate spellings, grammar rules with candidate fixes ("a comma may be missing after However") | LanguageTool proposes, a language model picks one or KEEP from the sentence and the rule's message | model |
39
39
  | 3 compounds and consistency | how a compound is written: "cyber attack" or "cyberattack", "non-profit" or "nonprofit", "long term" or "long-term"; and terms the document capitalises two ways | candidates found from the dictionaries (an open or hyphenated pair whose closed form is a word; a non-word that splits into two words; anything the document itself writes two ways). The model chooses closed, hyphenated, open or KEEP, told which dictionary rules (Merriam-Webster for US, Oxford for UK) and the rule that a compound modifier before a noun is hyphenated while a noun phrase is open | model |
40
40
  | 4 commas | a comma between subject and verb, a missing comma after an introductory phrase or around a non-restrictive clause, a stray comma before "and" joining objects: nothing a rule engine detects | the model returns the sentence with commas corrected; a diff guard admits only insertions and deletions of commas, rejects anything else, and reports it | model, under the guard |
@@ -15,7 +15,7 @@ Run it after [stylefix](https://github.com/AndrewBroz/stylefix), so the grammar
15
15
  | tier | what | how | who decides |
16
16
  |---|---|---|---|
17
17
  | 0 hygiene | text that renders fine but is not what it looks like: HTML entities Markdown can carry plainly (`&#32;`, `&quot;`, `&mdash;`), zero-width spaces, byte-order marks, soft hyphens, control characters, Windows line endings, decomposed accents | fixed deterministically and logged; entities that would change Markdown's parsing (`&lt;`, `&gt;`, `&amp;`) or carry meaning (`&nbsp;`) are left alone and reported | applied outright, or noted |
18
- | 1 mechanical | space before a comma or period, missing space after one, doubled punctuation, doubled words, known misspellings | LanguageTool's single-answer rules, the `typos` tool, a small missing-space rule | applied outright |
18
+ | 1 mechanical | space before a comma or period, missing space after one, doubled punctuation, doubled words whose repeat is never grammatical (`the the`, `of of`), known misspellings | LanguageTool's single-answer rules, the `typos` tool, a small missing-space rule; the built-in `basics` check (doubled words always; spacing without LanguageTool) | applied outright only where right in every context (audited rule by rule): a typos fix only when the word is all lower case, has one correction, is not part of a word with a digit or underscore, and is a known short typo (`teh`) or four letters or more and not a contraction missing its apostrophe (`youre`); `..` (`.` or `…`, or `cd ..`), `Node.Js`, `.bashrc`, a paragraph opening `, and` go to the model with KEEP, or are listed for review without one; indentation, table alignment and Markdown hard line breaks are left alone. The closed list is `a an the of to at for with from into onto and or but nor it we they my your our their`; a double from it that LanguageTool's pass ran over without flagging, and every other double (`that that`, `had had`, `log in in`, `on on Monday`), goes to the model with KEEP, or is listed for review. A hyphen touching either copy (`to to-do`) is no double |
19
19
  | 2 adjudicated | unknown words with candidate spellings, grammar rules with candidate fixes ("a comma may be missing after However") | LanguageTool proposes, a language model picks one or KEEP from the sentence and the rule's message | model |
20
20
  | 3 compounds and consistency | how a compound is written: "cyber attack" or "cyberattack", "non-profit" or "nonprofit", "long term" or "long-term"; and terms the document capitalises two ways | candidates found from the dictionaries (an open or hyphenated pair whose closed form is a word; a non-word that splits into two words; anything the document itself writes two ways). The model chooses closed, hyphenated, open or KEEP, told which dictionary rules (Merriam-Webster for US, Oxford for UK) and the rule that a compound modifier before a noun is hyphenated while a noun phrase is open | model |
21
21
  | 4 commas | a comma between subject and verb, a missing comma after an introductory phrase or around a non-restrictive clause, a stray comma before "and" joining objects: nothing a rule engine detects | the model returns the sentence with commas corrected; a diff guard admits only insertions and deletions of commas, rejects anything else, and reports it | model, under the guard |
@@ -1,4 +1,4 @@
1
- .TH PROOFIX 1 "October 2026" "proofix 0.6.0" "User Commands"
1
+ .TH PROOFIX 1 "November 2026" "proofix 0.8.2" "User Commands"
2
2
  .SH NAME
3
3
  proofix \- fix typos and punctuation in Markdown, under audit
4
4
  .SH SYNOPSIS
@@ -28,8 +28,52 @@ first. Every change is logged.
28
28
  .TP
29
29
  .B 1 mechanical
30
30
  A space before a comma or period, a missing space after one, doubled
31
- punctuation, doubled words, known misspellings. Found by LanguageTool's
32
- single-answer rules and the typos tool; applied outright.
31
+ punctuation, doubled words whose repeat is never grammatical ("the the",
32
+ "of of"), known misspellings. Found by LanguageTool and the typos tool.
33
+ An edit is applied outright only where it is right in every context;
34
+ the audit of these rules found:
35
+ .RS
36
+ .IP \(bu 2
37
+ A space before a comma or period is removed where the basics check below
38
+ agrees, and a space just inside a bracket beside a letter or digit;
39
+ ".bashrc", ". . ." and "1 ,000" go to the model.
40
+ .IP \(bu 2
41
+ Doubled punctuation with one answer (",,") is fixed; ".." ("." or "\[u2026]",
42
+ or a path, as in "cd ..") goes to the model.
43
+ .IP \(bu 2
44
+ A run of spaces mid-line is collapsed; indentation, a table row, an
45
+ indented code line and trailing spaces (a Markdown hard line break) are left
46
+ alone.
47
+ .IP \(bu 2
48
+ A missing space between sentences ("Node.Js" is a name) and punctuation
49
+ opening a paragraph go to the model.
50
+ .IP \(bu 2
51
+ A typos correction is applied only when the word is all lower case, has
52
+ one correction, is not part of a word with a digit or underscore, and is
53
+ either a known short typo ("teh", "adn") or four letters or more and not a
54
+ contraction missing its apostrophe ("youre", "whos"); "Teh", "TEH",
55
+ "foo_bar_teh", "teh2", "alle" (all? alley?), "ein", "hed" and "youre" go to
56
+ the model.
57
+ .RE
58
+ .IP
59
+ "Go to the model" means an item with KEEP among its choices; without a
60
+ model, it is listed for review with LanguageTool's or typos' reason. An
61
+ edit that overlaps another edit and so cannot be applied is listed for
62
+ review too ("not applied: it overlaps another edit").
63
+ .TP
64
+ .B basics
65
+ The built-in checks of tier 1, which need no tools. Doubled words always
66
+ run: a repeat on the closed list (a, an, the, of, to, at, for, with, from,
67
+ into, onto, and, or, but, nor, it, we, they, my, your, our, their) is
68
+ fixed, unless LanguageTool's mechanical pass ran and did not flag it, when it
69
+ goes to the model with KEEP, or is listed for review without one. A
70
+ capitalised one ("The The") is listed for review, and any other ("that
71
+ that", "had had", "log in in", "turn it on on Monday") goes to the model
72
+ with KEEP, or is listed for review without one. A hyphen touching either
73
+ copy ("to to-do", "for for-profit") makes it no double. Without LanguageTool's mechanical pass, basics also fixes the spacing
74
+ around commas, periods, semicolons and colons where that is provably right
75
+ (never next to a digit, in an emoticon or :shortcode:, or before ".bashrc"),
76
+ and lists "Press : to enter" and the like for review.
33
77
  .TP
34
78
  .B 2 adjudicated
35
79
  Unknown words and grammar rules with candidate fixes. LanguageTool
@@ -1,3 +1,3 @@
1
1
  """proofix: typos and punctuation, fixed under audit."""
2
2
 
3
- __version__ = "0.6.0"
3
+ __version__ = "0.8.2"
@@ -0,0 +1,514 @@
1
+ """Library API: proofread a Markdown string; the CLI is a wrapper around fix()."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from dataclasses import dataclass, replace
10
+
11
+ from adjudicate import Annotation, Change, ReviewItem, Skipped, compose, derive_changes
12
+ from adjudicate import Cache, Edit, adjudicate, apply_edits, protected_spans, question, system_prompt
13
+ from adjudicate.apply import to_offsets
14
+ from adjudicate.core import Decision
15
+ from adjudicate.llm import Endpoint
16
+
17
+ from . import basics, consistency, hygiene
18
+ from .commas import CommaCache, CommaResult, comma_edits, correct_commas
19
+ from .lt import LanguageToolServer, Match, find_languagetool, run_languagetool
20
+ from .tiers import (IGNORED, MECHANICAL, REPEAT, VARIETY_DISABLED, Partition, _line_col,
21
+ accepted_double, double_item, double_message, double_route, partition,
22
+ typos_edits, typos_item, typos_matches)
23
+
24
+ TASK = "You are a meticulous copy editor fixing typos and punctuation in a document written in {variety}."
25
+ VARIETY = {"us": "American English", "uk": "British English"}
26
+ TIERS = ("hygiene", "mechanical", "basics", "typos", "adjudicated", "compounds", "commas")
27
+
28
+
29
+ @dataclass
30
+ class Options:
31
+ target: str = "us"
32
+ accept: frozenset[str] = frozenset()
33
+ lt_level: str = "default"
34
+ style: str = "none"
35
+ commas: str = "gated"
36
+ optional_commas: str = "leave"
37
+ max_sentences: int | None = None
38
+ min_confidence: float = 0.8
39
+ parallel: int = 4
40
+ verbose: bool = False
41
+ skip: frozenset[str] = frozenset()
42
+ replay_cache: bool = False # ask with no endpoint: matches, doubles, held typos and compounds
43
+ # go through adjudicate(), answered from the cache or left undecided
44
+ oxford_ize: bool = False # the style guide uses -ize: LanguageTool's Oxford rules stay on
45
+
46
+
47
+ @dataclass
48
+ class Result:
49
+ text: str
50
+ changes: list[Change]
51
+ review: list[ReviewItem]
52
+ skipped: list[Skipped]
53
+ applied: list[Edit]
54
+ decisions: list[Decision]
55
+ comma_results: list[CommaResult]
56
+ lt_review: list[Match]
57
+ typos_fixed: int
58
+ hygiene_notes: list[str]
59
+ lt_missing: bool
60
+
61
+
62
+ def run_typos(text: str, accept: set[str] | frozenset[str] = frozenset()) -> tuple[list[Edit], list[Match]]:
63
+ """Known misspellings from the `typos` tool, if installed: (edits applied outright,
64
+ matches a model or a person decides). See tiers.typos_edits."""
65
+ exe = shutil.which("typos")
66
+ if not exe:
67
+ return [], []
68
+ proc = subprocess.run([exe, "--format", "json", "-"], input=text, capture_output=True, text=True)
69
+ return typos_edits(text, proc.stdout, accept=accept), typos_matches(text, proc.stdout, accept=accept)
70
+
71
+
72
+ # Rules partition() ignores, and CONSECUTIVE_SPACES (WHITESPACE_RULE's duplicate), are
73
+ # disabled in LanguageTool itself: a server drops overlapping matches, so a rule that is
74
+ # ignored anyway must not knock out one that is not.
75
+ LT_DISABLED = IGNORED | {"CONSECUTIVE_SPACES"}
76
+
77
+
78
+ def lt_disabled(o: Options) -> list[str]:
79
+ """The rules LanguageTool runs without: LT_DISABLED, and those that contradict the variety."""
80
+ key = "us" if o.target == "us" else ("uk_ise" if not o.oxford_ize else None)
81
+ return sorted(LT_DISABLED | (VARIETY_DISABLED[key] if key else frozenset()))
82
+
83
+
84
+ def _overlap_reviews(before: str, applied: list[Edit], rejected: list[Edit], after: str,
85
+ routed: set[tuple[int, int]], at_before: bool = False,
86
+ rules: dict | None = None) -> list[Match]:
87
+ """Review matches for edits apply_edits rejected because another edit overlapped them,
88
+ where the original is still in the text: nothing is dropped silently. Positions are in
89
+ `after`, or in `before` with at_before (when the review list is read against it).
90
+ `rules` names the LanguageTool rule behind a model's edit (its source is "adjudicated")."""
91
+ out = []
92
+ for e in rejected:
93
+ s, _ = to_offsets(before, e)
94
+ if before[s:s + len(e.original)] != e.original:
95
+ continue # stale: the text no longer matches the edit
96
+ pos = _shifted(before, applied, s)
97
+ found = after.find(e.original, max(0, pos - len(e.original)), pos + 2 * len(e.original))
98
+ if found < 0:
99
+ continue # the overlapping edit changed this text too
100
+ where = s if at_before else found
101
+ key = _line_col(before if at_before else after, where)
102
+ if key in routed:
103
+ continue
104
+ routed.add(key)
105
+ rule = (rules or {}).get((e.line, e.start, e.original, e.replacement))
106
+ out.append(Match(where, where + len(e.original), e.source, "",
107
+ f"'{e.original}' -> '{e.replacement}' not applied: it overlaps another edit"
108
+ + (f" ({rule})" if rule else ""), ""))
109
+ return out
110
+
111
+
112
+ def _unshift(spans: list[tuple[int, int, int]], pos: int, end: bool = False) -> int:
113
+ """Where offset `pos` of an edited text was before the edits. Each span is an edit's
114
+ (start, end, replacement length), in the earlier text, in order. A start offset inside
115
+ a replacement maps to the start of the text it replaced. An exclusive end offset maps
116
+ to the end of that text, and one at an edit's start stays before the edit: it does not
117
+ take in text the edit removed."""
118
+ delta = 0
119
+ for s, t, n in spans:
120
+ if pos < s + delta or (end and pos == s + delta):
121
+ break
122
+ if pos < s + delta + n:
123
+ return t if end else s
124
+ delta += n - (t - s)
125
+ return pos - delta
126
+
127
+
128
+ def _line_spans(before: str, after: str) -> list[tuple[int, int, int]]:
129
+ """The (start, end, replacement length) spans that turn `before` into `after`, two
130
+ texts with the same lines: hygiene's normalisation (CRLF and lone CR to LF, NFC).
131
+ Line by line, with each line ending apart from the line's text, so a change to one
132
+ never takes in the other."""
133
+ spans, pos = [], 0
134
+ for line_a, line_b in zip(before.splitlines(keepends=True), after.splitlines(keepends=True)):
135
+ body_a, body_b = line_a.splitlines()[0], line_b.splitlines()[0]
136
+ parts = ((body_a, body_b, pos), (line_a[len(body_a):], line_b[len(body_b):], pos + len(body_a)))
137
+ for a, b, at in parts:
138
+ if a != b:
139
+ ops = difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes()
140
+ spans += [(at + i, at + j, n - m) for tag, i, j, m, n in ops if tag != "equal"]
141
+ pos += len(line_a)
142
+ return spans
143
+
144
+
145
+ def _unstaged(stages: list[tuple[str, list[Edit]]], pos: int, end: bool = False) -> int:
146
+ """Where offset `pos` of the text after `stages` (each a text and the edits applied
147
+ to it) was in the first stage's text. See _unshift for `end`."""
148
+ for before, applied in reversed(stages):
149
+ pos = _unshift(sorted((*to_offsets(before, e), len(e.replacement)) for e in applied), pos, end)
150
+ return pos
151
+
152
+
153
+ def _input_line(stages: list[tuple[str, list[Edit]]], pos: int) -> int:
154
+ """The line of fix()'s input that offset `pos` of the text after `stages` came from:
155
+ review lines are the reader's lines."""
156
+ return _line_of(stages[0][0], _unstaged(stages, pos))
157
+
158
+
159
+ def _line_start(text: str, line: int) -> int:
160
+ pos = 0
161
+ for _ in range(line - 1):
162
+ nxt = text.find("\n", pos)
163
+ if nxt < 0:
164
+ break
165
+ pos = nxt + 1
166
+ return pos
167
+
168
+
169
+ def _quoted(message: str, word: str) -> bool:
170
+ return any(f"{a}{word}{b}" in message for a, b in (("'", "'"), ("\u2018", "\u2019"), ('"', '"'),
171
+ ("\u201c", "\u201d")))
172
+
173
+
174
+ def _named(text: str, m: Match) -> Match:
175
+ """A review match whose message names the text it flags ("'colur': Possible spelling
176
+ mistake found."), unless the message already quotes it."""
177
+ word = " ".join(text[m.start:m.end].split())
178
+ if not word or _quoted(m.message, word):
179
+ return m
180
+ return replace(m, message=f"'{word}': {m.message}")
181
+
182
+
183
+ def _staged_changes(original: str, middle: str, final: str, first_ann: list[Annotation],
184
+ rest_ann: list[Annotation]) -> list[Change]:
185
+ """Changes original -> final, labelled stage by stage: pass 1's on original -> middle,
186
+ the rest on middle -> final, composed onto the original. A later change that overlaps
187
+ a pass-1 change replaces it (one change, labelled by the later edit)."""
188
+ first = derive_changes(original, middle, first_ann, "proofix")
189
+ second = derive_changes(middle, final, rest_ann, "proofix")
190
+ for n, c in enumerate(first, 1):
191
+ c.id = f"a{n}"
192
+ for n, c in enumerate(second, 1):
193
+ c.id = f"b{n}"
194
+ composed = compose(original, middle, first, second)
195
+ superseded = {d for c in composed for d in c.depends_on}
196
+ out = [c for c in composed if c.id not in superseded]
197
+ for c in out:
198
+ c.id, c.depends_on = "", ()
199
+ return sorted(out, key=lambda c: (c.start, c.end))
200
+
201
+
202
+ def _decided_by(d: Decision, model_used: bool) -> str:
203
+ return "cache" if d.cached else ("model" if model_used else "rule")
204
+
205
+
206
+ def _line_of(text: str, pos: int) -> int:
207
+ return text.count("\n", 0, pos) + 1
208
+
209
+
210
+ def _shifted(text: str, applied: list[Edit], pos: int) -> int:
211
+ """Where offset `pos` of `text` lands once `applied` (edits on `text`) are made."""
212
+ delta = 0
213
+ for e in applied:
214
+ s, t = to_offsets(text, e)
215
+ if t <= pos:
216
+ delta += len(e.replacement) - (t - s)
217
+ return pos + delta
218
+
219
+
220
+ def fix(text: str, options: Options, endpoint: Endpoint | None, cache: Cache,
221
+ comma_cache: CommaCache, lt_server: LanguageToolServer | None = None) -> Result:
222
+ """Proofread text; no I/O on the caller's files. Raises LTError if LanguageTool fails.
223
+ With `lt_server` (a running LanguageToolServer), LanguageTool is asked through it."""
224
+ o, ep = options, endpoint
225
+ skip = o.skip
226
+ asking = ep is not None or o.replay_cache
227
+ accept = {w.lower() for w in o.accept}
228
+ original = text
229
+ skipped: list[Skipped] = []
230
+ hygiene_notes: list[str] = []
231
+ edits: list[Edit] = []
232
+ typos_held: list[Match] = []
233
+ if "hygiene" not in skip:
234
+ text, hygiene_notes = hygiene.normalize_text(text)
235
+ h_edits, h_notes = hygiene.plan(text)
236
+ edits += h_edits
237
+ hygiene_notes += [f"L{n.line} {n.message}" for n in h_notes]
238
+ if "typos" not in skip:
239
+ if shutil.which("typos") is None:
240
+ skipped.append(Skipped("known-misspelling fixes", "typos not found", "brew install typos-cli"))
241
+ else:
242
+ t_edits, typos_held = run_typos(text, accept)
243
+ edits += t_edits
244
+ typos_fixed = sum(1 for e in edits if e.source == "typos")
245
+ decisions: list[Decision] = []
246
+ review: list[Match] = []
247
+ review_items: list[ReviewItem] = []
248
+ lt_wanted = not {"mechanical", "adjudicated"} <= skip
249
+ disabled = lt_disabled(o)
250
+ # what the server's overlap filtering must not hide: every rule tier 1 applies or routes
251
+ ensure = sorted(MECHANICAL) if lt_server is not None else None
252
+ lt = find_languagetool() if lt_wanted else None
253
+ lt_missing = lt_wanted and not lt
254
+ if lt_missing:
255
+ skipped.append(Skipped("grammar and spelling fixes (tiers 1 and 2)", "LanguageTool not found",
256
+ "brew install languagetool"))
257
+ # basics' doubled words always run (LanguageTool misses "that that"), deduplicated
258
+ # against its repeat rule; basics' spacing stands in for LanguageTool's mechanical
259
+ # pass only when that pass will not run.
260
+ use_doubles = "basics" not in skip
261
+ use_spacing = use_doubles and not (lt and "mechanical" not in skip)
262
+ # Pass 1: mechanical faults (typos, whitespace, doubled punctuation), applied.
263
+ pass1_review: list[Match] = []
264
+ lt_repeats: set[tuple[int, int]] = set()
265
+ lt_p1 = bool(lt) and "mechanical" not in skip
266
+ lt_flagged: set[int] = set() # where pass 1's LanguageTool saw a repeated word
267
+ unflagged: list[int] = [] # closed-list doubles it did not see: routed, not applied
268
+ if lt_p1:
269
+ matches = run_languagetool(text, o.target, o.lt_level, disabled=disabled, server=lt_server,
270
+ ensure=ensure)
271
+ lt_flagged = {m.start for m in matches if m.rule == REPEAT}
272
+ p1 = partition(text, matches, accept, adjudicate_available=False)
273
+ edits += p1.edits
274
+ lt_repeats = {(e.line, e.start) for e in p1.edits if e.source == REPEAT}
275
+ if "adjudicated" in skip: # no pass 2 to route them: keep pass 1's mechanical reviews
276
+ pass1_review = [m for m in p1.review if m.rule in MECHANICAL]
277
+ if use_doubles:
278
+ spans = protected_spans(text)
279
+ if use_spacing:
280
+ edits += basics.spacing_edits(text, spans)
281
+ for d in basics.doubled_words(text, spans):
282
+ if double_route(d, asking) != "edit" or accepted_double(text, d, accept):
283
+ continue
284
+ if lt_p1 and d.first_start not in lt_flagged:
285
+ # LanguageTool knows exceptions the closed list does not: its silence means
286
+ # a model or a person decides (below, on the cleaned text).
287
+ unflagged.append(d.first_start)
288
+ continue
289
+ e = basics.double_edit(text, d)
290
+ if (e.line, e.start) not in lt_repeats: # LanguageTool's edit is the one kept
291
+ edits.append(e)
292
+ pre_text = text
293
+ text, rejected_p1 = apply_edits(text, edits)
294
+ applied = [e for e in edits if e not in rejected_p1]
295
+ stages: list[tuple[str, list[Edit]]] = [(pre_text, list(applied))]
296
+ unflagged_at = {_line_col(text, _shifted(pre_text, applied, p)) for p in unflagged}
297
+ p1_rejected_repeats = [e for e in rejected_p1 if e.source == REPEAT]
298
+ lt_pass2 = bool(lt) and "adjudicated" not in skip
299
+ item_rules: dict[int, str] = {} # item id -> the rule that raised it
300
+ # Pass 2: judgement calls on the cleaned text, so spans no longer collide.
301
+ review_text = text
302
+ if lt_pass2:
303
+ matches = run_languagetool(text, o.target, o.lt_level, disabled=disabled, server=lt_server,
304
+ ensure=ensure)
305
+ part = partition(text, matches, accept, adjudicate_available=asking)
306
+ item_rules.update(part.rules)
307
+ # Pass 2's outright edits are audited like pass 1's: anything pass 1 exposed, a repeat
308
+ # pass 1 did not catch ("the the"), or an edit that lost to an overlapping one there.
309
+ edits = list(part.edits)
310
+ review = part.review
311
+ else:
312
+ part = Partition([], [], [])
313
+ edits = []
314
+ review = [replace(m, start=_shifted(pre_text, applied, m.start),
315
+ end=_shifted(pre_text, applied, m.end)) for m in pass1_review]
316
+ if use_doubles:
317
+ # Doubles outside the closed list: adjudicated with a model, else reviewed.
318
+ # One LanguageTool's repeat rule already routed is not raised twice.
319
+ seen = ({(i.line, i.start) for i in part.items if i.source == "repeat"}
320
+ | {_line_col(text, m.start) for m in review if m.rule in (REPEAT, "basics")})
321
+ next_id = max((i.id for i in part.items), default=0) + 1
322
+ spans = protected_spans(text)
323
+ seen |= {(e.line, e.start) for e in edits if e.source == REPEAT}
324
+ for d in basics.doubled_words(text, spans):
325
+ route = double_route(d, asking)
326
+ if accepted_double(text, d, accept) or _line_col(text, d.first_start) in seen:
327
+ continue
328
+ # A closed-list double LanguageTool ran over and did not flag (pass 2 did not, or
329
+ # pass 1 did not and there is no pass 2): a model or a person decides.
330
+ if route == "edit" and (lt_pass2 or _line_col(text, d.first_start) in unflagged_at):
331
+ route = "item" if asking else "review"
332
+ if route == "edit": # one pass 1 could not apply ("the the" beside a whitespace fix)
333
+ edits.append(basics.double_edit(text, d))
334
+ seen.add(_line_col(text, d.first_start))
335
+ elif route == "item":
336
+ part.items.append(double_item(text, d, next_id))
337
+ next_id += 1
338
+ else: # listed with LanguageTool's review matches, so the CLI shows it too
339
+ review.append(Match(d.first_start, d.end, "basics", "", double_message(text, d), ""))
340
+ # A space before : ; ! ? with more text after it may be a key ("Press : to"): a person decides.
341
+ if use_spacing:
342
+ review += [Match(p, p + 1, "basics", "", f"space before '{mark}'", "")
343
+ for p, mark in basics.spacing_notes(text, spans)]
344
+ if not lt_pass2 and p1_rejected_repeats:
345
+ # A pass-1 repeat edit that lost to an overlapping edit, with no pass 2 to catch it
346
+ # and basics not routing it either: a person decides, nothing is dropped silently.
347
+ routed = ({(e.line, e.start) for e in edits} | {(i.line, i.start) for i in part.items}
348
+ | {_line_col(text, m.start) for m in review})
349
+ for e in p1_rejected_repeats:
350
+ pos = _shifted(pre_text, applied, to_offsets(pre_text, e)[0])
351
+ m = re.match(r"([^\W\d_]\S*)[ \t]+(\S+)", text[pos:])
352
+ if not m or m.group(1).lower() != m.group(2).lower() or _line_col(text, pos) in routed:
353
+ continue
354
+ review.append(Match(pos, m.end() + pos, REPEAT, "",
355
+ f"repeated word '{m.group(1)} {m.group(2)}'", ""))
356
+ routed = ({(e.line, e.start) for e in edits} | {(i.line, i.start) for i in part.items}
357
+ | {_line_col(text, m.start) for m in review})
358
+ if typos_held:
359
+ # typos' findings that are not provably right: a model decides (KEEP offered), else
360
+ # a person. One LanguageTool already routed at the same place is not raised twice.
361
+ next_id = max((i.id for i in part.items), default=0) + 1
362
+ for m in typos_held:
363
+ s = _shifted(pre_text, applied, m.start)
364
+ word = pre_text[m.start:m.end]
365
+ if text[s:s + len(word)] != word:
366
+ found = text.find(word, max(0, s - len(word)), s + 2 * len(word))
367
+ if found < 0:
368
+ continue # an overlapping fix changed the word
369
+ s = found
370
+ key = _line_col(text, s)
371
+ held = replace(m, start=s, end=s + len(word))
372
+ if key in routed:
373
+ # typos' reason names the word and its correction: it replaces a
374
+ # LanguageTool review of the same word ("Possible spelling mistake found.")
375
+ same = [k for k, r in enumerate(review) if r.start == s and r.end == s + len(word)]
376
+ if same and not asking:
377
+ review[same[0]] = held
378
+ continue
379
+ routed.add(key)
380
+ if asking:
381
+ part.items.append(typos_item(text, held, next_id))
382
+ item_rules[next_id] = "TYPOS"
383
+ next_id += 1
384
+ else:
385
+ review.append(held)
386
+ # A pass-1 edit that lost to an overlapping one (other than the repeats above).
387
+ # One a pass-2 edit covers is resolved by it: not listed.
388
+ covered = [to_offsets(text, e) for e in edits]
389
+ review += [m for m in _overlap_reviews(pre_text, applied,
390
+ [e for e in rejected_p1 if e.source != REPEAT], text, routed)
391
+ if not any(s < m.end and m.start < t for s, t in covered)]
392
+ system = system_prompt(TASK.format(variety=VARIETY[o.target]))
393
+ adj_rules: dict[tuple, str] = {}
394
+ if part.items:
395
+ decisions = adjudicate(ep, f"proofix|{o.target}", part.items, cache,
396
+ parallel=o.parallel, verbose=o.verbose, system=system,
397
+ log_name="proofix")
398
+ for d in decisions:
399
+ d.withhold(o.min_confidence)
400
+ if d.replacement is not None:
401
+ e = Edit(d.item.line, d.item.start, d.item.end, d.item.word, d.replacement, "adjudicated")
402
+ edits.append(e)
403
+ if d.item.id in item_rules:
404
+ adj_rules[(e.line, e.start, e.original, e.replacement)] = item_rules[d.item.id]
405
+ new_text, rejected = apply_edits(text, edits)
406
+ pass2_applied = [e for e in edits if e not in rejected]
407
+ # an edit (a decision, too) that lost to an overlapping one: listed unless already listed
408
+ review += _overlap_reviews(text, pass2_applied, rejected, new_text,
409
+ {_line_col(text, m.start) for m in review}, at_before=True,
410
+ rules=adj_rules)
411
+ applied += pass2_applied
412
+ stages.append((text, pass2_applied))
413
+ p2_items = {id(d.item) for d in decisions}
414
+ text = after_p2 = new_text
415
+ # Pass 3: compounds and consistency, on the text as it now stands.
416
+ if "compounds" not in skip and asking:
417
+ c_items, groups = consistency.items(text, o.target, o.style)
418
+ if c_items:
419
+ c_decisions = adjudicate(ep, f"proofix|{o.target}", c_items, cache,
420
+ parallel=o.parallel, verbose=o.verbose, system=system,
421
+ log_name="proofix")
422
+ c_edits = []
423
+ for d in c_decisions:
424
+ d.withhold(o.min_confidence)
425
+ if not d.replacement:
426
+ continue
427
+ for g in groups[d.item.id]:
428
+ line = text.count("\n", 0, g.start) + 1
429
+ col = g.start - (text.rfind("\n", 0, g.start) + 1) + 1
430
+ rep = consistency._recase(g.form, d.replacement.lower())
431
+ c_edits.append(Edit(line, col, col + (g.end - g.start) - 1, g.form, rep,
432
+ "adjudicated"))
433
+ decisions += c_decisions
434
+ new_text, rejected = apply_edits(text, c_edits)
435
+ applied += [e for e in c_edits if e not in rejected]
436
+ stages.append((text, [e for e in c_edits if e not in rejected]))
437
+ text = new_text
438
+ new_text = text
439
+
440
+ before_commas = new_text
441
+ comma_results: list[CommaResult] = []
442
+ if "commas" not in skip and o.commas != "none":
443
+ cedits, comma_results = correct_commas(new_text, o.target, ep, comma_cache,
444
+ o.optional_commas, o.min_confidence,
445
+ parallel=o.parallel, verbose=o.verbose,
446
+ gate=o.commas == "gated",
447
+ max_sentences=o.max_sentences)
448
+ final, cskipped = apply_edits(new_text, cedits)
449
+ applied += [e for e in cedits if e not in cskipped]
450
+ new_text = final
451
+
452
+ # Most specific label last-wins-first: commas, then adjudicated, then plain edits.
453
+ ann: list[Annotation] = []
454
+ for r in comma_results:
455
+ if r.status == "edit" and r.new_text:
456
+ by = "cache" if r.reason.endswith("(cached)") else ("model" if ep is not None else "rule")
457
+ for e in comma_edits(before_commas, r.sentence, r.new_text):
458
+ ann.append(Annotation(e.original, e.replacement, "commas", r.reason, by, r.confidence))
459
+ for d in decisions:
460
+ if d.replacement is not None:
461
+ ann.append(Annotation(d.item.word, d.replacement, "adjudicated", d.reason,
462
+ _decided_by(d, ep is not None), d.confidence))
463
+ ann += [Annotation(e.original, e.replacement, e.source) for e in applied]
464
+ changes = derive_changes(original, new_text, ann, "proofix")
465
+ if any(c.check == "proofix" for c in changes):
466
+ # A pass-1 edit can make the text a later edit applies to ("teh the" -> "the the"
467
+ # -> "the"), which no annotation reproduces on the original: label each stage on
468
+ # its own text and compose them, when that leaves fewer changes unlabelled.
469
+ p1 = len(stages[0][1]) # applied[:p1] are pass 1's edits
470
+ n_plain = len(applied)
471
+ first_ann = ann[len(ann) - n_plain:len(ann) - n_plain + p1]
472
+ rest_ann = ann[:len(ann) - n_plain] + ann[len(ann) - n_plain + p1:]
473
+ staged = _staged_changes(original, review_text, new_text, first_ann, rest_ann)
474
+ if sum(c.check == "proofix" for c in staged) < sum(c.check == "proofix" for c in changes):
475
+ changes = staged
476
+ for c in changes:
477
+ c.pass_ = "proofix"
478
+
479
+ # Review lines are fix()'s input lines: each position is mapped back through the
480
+ # edits applied after the text it was found in (pass 1 can remove a line break).
481
+ review = [_named(review_text, m) for m in review]
482
+ review_items += [ReviewItem(_input_line(stages[:1], m.start), "alert", m.message, m.rule, "proofix")
483
+ for m in review]
484
+
485
+ def item_stage(item) -> tuple[list, str]: # pass 2's items are on review_text, pass 3's on after_p2
486
+ return (stages[:1], review_text) if id(item) in p2_items else (stages[:2], after_p2)
487
+
488
+ def item_line(item) -> int:
489
+ before, at = item_stage(item)
490
+ return _input_line(before, _line_start(at, item.line))
491
+
492
+ # Offsets into fix()'s input: back through the stages, then through hygiene's
493
+ # normalisation (CRLF and lone CR to LF, NFC), which no stage records.
494
+ undecided = [d for d in decisions if d.choice is None]
495
+ normalised = _line_spans(original, stages[0][0]) if undecided and original != stages[0][0] else []
496
+
497
+ def input_offset(item, pos: int, end: bool = False) -> int:
498
+ return _unshift(normalised, _unstaged(item_stage(item)[0], pos, end), end)
499
+
500
+ for d in undecided:
501
+ s, e = to_offsets(item_stage(d.item)[1], Edit(d.item.line, d.item.start, d.item.end, "", "", ""))
502
+ message = (f"repeated word '{' '.join(d.item.word.split())}': {d.reason}"
503
+ if d.item.source == "repeat" else f"'{d.item.word}': {d.reason}")
504
+ review_items.append(question(d, f"proofix|{o.target}", item_line(d.item), input_offset(d.item, s),
505
+ input_offset(d.item, e, end=True), message, "proofix"))
506
+ for r in comma_results:
507
+ if r.status in ("rejected", "note"):
508
+ review_items.append(ReviewItem(_input_line(stages, r.sentence.start),
509
+ r.status, r.reason, "commas", "proofix"))
510
+ elif r.status == "error" and r.reason != "no model configured": # reported once, as a skipped capability
511
+ review_items.append(ReviewItem(_input_line(stages, r.sentence.start),
512
+ "note", r.reason, "commas", "proofix"))
513
+ return Result(new_text, changes, review_items, skipped, applied, decisions, comma_results,
514
+ review, typos_fixed, hygiene_notes, lt_missing)