proofix 0.7.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.
- {proofix-0.7.0 → proofix-0.8.2}/PKG-INFO +2 -2
- {proofix-0.7.0 → proofix-0.8.2}/man/proofix.1 +1 -1
- {proofix-0.7.0 → proofix-0.8.2}/proofix/__init__.py +1 -1
- {proofix-0.7.0 → proofix-0.8.2}/proofix/api.py +63 -25
- {proofix-0.7.0 → proofix-0.8.2}/proofix/basics.py +3 -3
- {proofix-0.7.0 → proofix-0.8.2}/proofix/commas.py +4 -14
- {proofix-0.7.0 → proofix-0.8.2}/proofix/consistency.py +40 -10
- {proofix-0.7.0 → proofix-0.8.2}/proofix/tiers.py +40 -8
- {proofix-0.7.0 → proofix-0.8.2}/pyproject.toml +2 -2
- proofix-0.8.2/tests/test_api.py +215 -0
- proofix-0.8.2/tests/test_comma_cache_merge.py +26 -0
- proofix-0.8.2/tests/test_explain.py +122 -0
- proofix-0.7.0/tests/test_api.py +0 -77
- {proofix-0.7.0 → proofix-0.8.2}/.gitignore +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/LICENSE +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/README.md +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/examples/typos.md +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/proofix/cli.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/proofix/hygiene.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/proofix/lt.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/proofix/report.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/conftest.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/fixtures/audit.lt.json +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/fixtures/typos.lt.json +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_audit.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_basics.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_docs.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_e2e.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_endpoint_cli.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_lt_server.py +0 -0
- {proofix-0.7.0 → proofix-0.8.2}/tests/test_units.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: proofix
|
|
3
|
-
Version: 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.
|
|
17
|
+
Requires-Dist: adjudicate<0.4,>=0.3.5
|
|
18
18
|
Description-Content-Type: text/markdown
|
|
19
19
|
|
|
20
20
|
# proofix
|
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import difflib
|
|
5
6
|
import re
|
|
6
7
|
import shutil
|
|
7
8
|
import subprocess
|
|
8
9
|
from dataclasses import dataclass, replace
|
|
9
10
|
|
|
10
11
|
from adjudicate import Annotation, Change, ReviewItem, Skipped, compose, derive_changes
|
|
11
|
-
from adjudicate import Cache, Edit, adjudicate, apply_edits, protected_spans, system_prompt
|
|
12
|
+
from adjudicate import Cache, Edit, adjudicate, apply_edits, protected_spans, question, system_prompt
|
|
12
13
|
from adjudicate.apply import to_offsets
|
|
13
14
|
from adjudicate.core import Decision
|
|
14
15
|
from adjudicate.llm import Endpoint
|
|
@@ -38,7 +39,8 @@ class Options:
|
|
|
38
39
|
parallel: int = 4
|
|
39
40
|
verbose: bool = False
|
|
40
41
|
skip: frozenset[str] = frozenset()
|
|
41
|
-
replay_cache: bool = False
|
|
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
|
|
42
44
|
oxford_ize: bool = False # the style guide uses -ize: LanguageTool's Oxford rules stay on
|
|
43
45
|
|
|
44
46
|
|
|
@@ -107,25 +109,51 @@ def _overlap_reviews(before: str, applied: list[Edit], rejected: list[Edit], aft
|
|
|
107
109
|
return out
|
|
108
110
|
|
|
109
111
|
|
|
110
|
-
def
|
|
111
|
-
"""Where offset `pos` of
|
|
112
|
-
|
|
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."""
|
|
113
118
|
delta = 0
|
|
114
|
-
for s, t, n in
|
|
115
|
-
if pos < s + delta:
|
|
119
|
+
for s, t, n in spans:
|
|
120
|
+
if pos < s + delta or (end and pos == s + delta):
|
|
116
121
|
break
|
|
117
122
|
if pos < s + delta + n:
|
|
118
|
-
return s
|
|
123
|
+
return t if end else s
|
|
119
124
|
delta += n - (t - s)
|
|
120
125
|
return pos - delta
|
|
121
126
|
|
|
122
127
|
|
|
123
|
-
def
|
|
124
|
-
"""The
|
|
125
|
-
|
|
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`."""
|
|
126
148
|
for before, applied in reversed(stages):
|
|
127
|
-
pos =
|
|
128
|
-
return
|
|
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))
|
|
129
157
|
|
|
130
158
|
|
|
131
159
|
def _line_start(text: str, line: int) -> int:
|
|
@@ -368,8 +396,7 @@ def fix(text: str, options: Options, endpoint: Endpoint | None, cache: Cache,
|
|
|
368
396
|
parallel=o.parallel, verbose=o.verbose, system=system,
|
|
369
397
|
log_name="proofix")
|
|
370
398
|
for d in decisions:
|
|
371
|
-
|
|
372
|
-
d.reason, d.choice = f"low confidence ({d.confidence:.2f}): {d.reason}", None
|
|
399
|
+
d.withhold(o.min_confidence)
|
|
373
400
|
if d.replacement is not None:
|
|
374
401
|
e = Edit(d.item.line, d.item.start, d.item.end, d.item.word, d.replacement, "adjudicated")
|
|
375
402
|
edits.append(e)
|
|
@@ -394,8 +421,7 @@ def fix(text: str, options: Options, endpoint: Endpoint | None, cache: Cache,
|
|
|
394
421
|
log_name="proofix")
|
|
395
422
|
c_edits = []
|
|
396
423
|
for d in c_decisions:
|
|
397
|
-
|
|
398
|
-
d.reason, d.choice = f"low confidence ({d.confidence:.2f}): {d.reason}", None
|
|
424
|
+
d.withhold(o.min_confidence)
|
|
399
425
|
if not d.replacement:
|
|
400
426
|
continue
|
|
401
427
|
for g in groups[d.item.id]:
|
|
@@ -456,15 +482,27 @@ def fix(text: str, options: Options, endpoint: Endpoint | None, cache: Cache,
|
|
|
456
482
|
review_items += [ReviewItem(_input_line(stages[:1], m.start), "alert", m.message, m.rule, "proofix")
|
|
457
483
|
for m in review]
|
|
458
484
|
|
|
459
|
-
def
|
|
460
|
-
if id(item) in p2_items:
|
|
461
|
-
|
|
462
|
-
|
|
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)
|
|
463
499
|
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
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"))
|
|
468
506
|
for r in comma_results:
|
|
469
507
|
if r.status in ("rejected", "note"):
|
|
470
508
|
review_items.append(ReviewItem(_input_line(stages, r.sentence.start),
|
|
@@ -20,9 +20,9 @@ _WORD = r"[^\W\d_]+(?:['\u2019][^\W\d_]+)*"
|
|
|
20
20
|
_DOUBLE = re.compile(rf"(?<![\w'\u2019-])({_WORD})([ \t]+|\n(?![ \t]*(?:[-*+>#|]|\d+[.)])))(\1)(?![\w'\u2019-])",
|
|
21
21
|
re.I)
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
DOUBLE_EXPLAIN = ("A word appears twice in a row. That is usually a typo ('the the'), but some "
|
|
24
|
+
"repeats are correct English: 'that that', 'had had', or an emphatic 'very very'.")
|
|
25
|
+
DOUBLE_RULE = "Choose the single word if the repeat is a typo. KEEP if it is grammatical or deliberate."
|
|
26
26
|
|
|
27
27
|
|
|
28
28
|
@dataclass(frozen=True)
|
|
@@ -13,7 +13,7 @@ from concurrent.futures import ThreadPoolExecutor
|
|
|
13
13
|
from dataclasses import dataclass, field
|
|
14
14
|
from pathlib import Path
|
|
15
15
|
|
|
16
|
-
from adjudicate import FENCE, FRONT_MATTER, Edit, Endpoint, LLMError, protected_spans, strip_thinking
|
|
16
|
+
from adjudicate import FENCE, FRONT_MATTER, Cache, Edit, Endpoint, LLMError, protected_spans, strip_thinking
|
|
17
17
|
|
|
18
18
|
VARIETY = {"us": "American English", "uk": "British English"}
|
|
19
19
|
|
|
@@ -201,24 +201,14 @@ def comma_edits(text: str, s: Sentence, new: str) -> list[Edit]:
|
|
|
201
201
|
return edits
|
|
202
202
|
|
|
203
203
|
|
|
204
|
-
class CommaCache:
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if path and path.exists():
|
|
208
|
-
try:
|
|
209
|
-
self.data = json.loads(path.read_text())
|
|
210
|
-
except json.JSONDecodeError:
|
|
211
|
-
self.data = {}
|
|
204
|
+
class CommaCache(Cache):
|
|
205
|
+
"""Corrected sentences, keyed by sentence. Loading and the merging,
|
|
206
|
+
locked save come from adjudicate's Cache."""
|
|
212
207
|
|
|
213
208
|
@staticmethod
|
|
214
209
|
def key(scope: str, sentence: str) -> str:
|
|
215
210
|
return hashlib.sha256(f"commas|{scope}|{sentence.strip()}".encode()).hexdigest()[:24]
|
|
216
211
|
|
|
217
|
-
def save(self):
|
|
218
|
-
if self.path:
|
|
219
|
-
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
220
|
-
self.path.write_text(json.dumps(self.data, indent=1, ensure_ascii=False))
|
|
221
|
-
|
|
222
212
|
|
|
223
213
|
def _ask(ep: Endpoint, system: str, batch: list[Sentence]) -> dict[int, dict] | None:
|
|
224
214
|
"""{id: {"text", "confidence", "reason"} or {"note": reason}}; None on a bad reply."""
|
|
@@ -24,6 +24,8 @@ from dataclasses import dataclass
|
|
|
24
24
|
|
|
25
25
|
from adjudicate import Item, at_sentence_start, known, known_anywhere, protected_spans, sentence_context
|
|
26
26
|
|
|
27
|
+
from .commas import VARIETY
|
|
28
|
+
|
|
27
29
|
_WORD = r"[A-Za-z][A-Za-z']*"
|
|
28
30
|
_PAIR = re.compile(rf"(?<!['’\w])(?=({_WORD})([- ])({_WORD})\b)") # lookahead: overlapping pairs
|
|
29
31
|
_TERM2 = re.compile(rf"(?<!['’\w])(?=({_WORD} {_WORD})\b)")
|
|
@@ -61,9 +63,26 @@ CLOSING = {"us": "American usage closes established compounds: cyberattack, cybe
|
|
|
61
63
|
STYLE_NOTE = {"ap": "AP style hyphenates less than Chicago: omit the hyphen in a compound modifier "
|
|
62
64
|
"when the meaning is clear without it ('first quarter earnings'). ",
|
|
63
65
|
"chicago": "", "gpo": "", "apa": "", "oxford": "", "guardian": "", "none": ""}
|
|
64
|
-
CASE_RULE = ("
|
|
65
|
-
"
|
|
66
|
-
|
|
66
|
+
CASE_RULE = ("Choose the document's dominant form unless this occurrence is a heading, a sentence "
|
|
67
|
+
"start, or a different sense (a proper name versus a common noun).")
|
|
68
|
+
|
|
69
|
+
# The person answering reads explain; the model reads it before the rule.
|
|
70
|
+
# NAME: the dictionary as explain names it.
|
|
71
|
+
NAME = {"us": "Merriam-Webster", "uk": "Oxford"}
|
|
72
|
+
USAGE = {"us": "American usage closes most established compounds.",
|
|
73
|
+
"uk": "British usage hyphenates more compounds than American."}
|
|
74
|
+
CLOSED_EXPLAIN = "In {variety}, {name} spells this '{closed}', {how}."
|
|
75
|
+
MAYBE_CLOSED_EXPLAIN = "In {variety}, this may be one word: '{closed}'. {usage}"
|
|
76
|
+
SPLIT_EXPLAIN = ("In {variety}, '{word}' is not one word: write '{hyph}' before a noun it describes, "
|
|
77
|
+
"and '{open}' elsewhere.{style}")
|
|
78
|
+
SHAPE_EXPLAIN = "In {variety}, write '{hyph}' before a noun it describes, and '{open}' elsewhere.{style}"
|
|
79
|
+
STYLE_EXPLAIN = {"ap": " AP style leaves that hyphen out when the meaning is clear without it."}
|
|
80
|
+
CASE_EXPLAIN = ("This document writes {counts}. A term keeps one capitalisation throughout, unless "
|
|
81
|
+
"one use is a heading or a proper name.")
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _times(n: int) -> str:
|
|
85
|
+
return {1: "once", 2: "twice"}.get(n, f"{n} times")
|
|
67
86
|
|
|
68
87
|
|
|
69
88
|
@dataclass
|
|
@@ -181,12 +200,13 @@ def items(text: str, variety: str = "us", style: str = "none", next_id: int = 1
|
|
|
181
200
|
out: list[Item] = []
|
|
182
201
|
groups: dict[int, list[Occurrence]] = {}
|
|
183
202
|
|
|
184
|
-
def add(o: Occurrence, options: tuple[str, ...], rule: str, source: str, group: list[Occurrence]
|
|
203
|
+
def add(o: Occurrence, options: tuple[str, ...], rule: str, source: str, group: list[Occurrence],
|
|
204
|
+
explain: str):
|
|
185
205
|
nonlocal next_id
|
|
186
206
|
line, col = _line_col(text, o.start)
|
|
187
207
|
out.append(Item(next_id, o.form, options + ("KEEP",), rule,
|
|
188
208
|
sentence_context(text, o.start, o.end), line, col,
|
|
189
|
-
col + (o.end - o.start) - 1, source=source))
|
|
209
|
+
col + (o.end - o.start) - 1, source=source, explain=explain))
|
|
190
210
|
groups[next_id] = group
|
|
191
211
|
next_id += 1
|
|
192
212
|
|
|
@@ -199,6 +219,7 @@ def items(text: str, variety: str = "us", style: str = "none", next_id: int = 1
|
|
|
199
219
|
desc = "This document writes it " + ", ".join(f"'{f}' {n}×" for f, n in counts.most_common()) + ". "
|
|
200
220
|
rule = RULE.format(dictionary=DICTIONARY[variety], closing=CLOSING[variety],
|
|
201
221
|
style=STYLE_NOTE.get(style, ""), counts=desc)
|
|
222
|
+
names = {"variety": VARIETY[variety], "name": NAME[variety], "style": STYLE_EXPLAIN.get(style, "")}
|
|
202
223
|
if _closed_is_word(closed, parts):
|
|
203
224
|
# One decision per non-closed surface form, applied to all of them.
|
|
204
225
|
by_form: dict[str, list[Occurrence]] = defaultdict(list)
|
|
@@ -206,7 +227,12 @@ def items(text: str, variety: str = "us", style: str = "none", next_id: int = 1
|
|
|
206
227
|
if "-" in o.form or " " in o.form:
|
|
207
228
|
by_form[o.form].append(o)
|
|
208
229
|
for form, group in by_form.items():
|
|
209
|
-
|
|
230
|
+
# Said outright only when the variety's own dictionary has the closed form.
|
|
231
|
+
explain = (CLOSED_EXPLAIN.format(**names, closed=closed,
|
|
232
|
+
how="without a hyphen" if "-" in form else "as one word")
|
|
233
|
+
if known(closed, variety) else
|
|
234
|
+
MAYBE_CLOSED_EXPLAIN.format(**names, closed=closed, usage=USAGE[variety]))
|
|
235
|
+
add(group[0], (_recase(form, closed),), rule, "compound", group, explain)
|
|
210
236
|
continue
|
|
211
237
|
if not parts:
|
|
212
238
|
continue
|
|
@@ -216,19 +242,23 @@ def items(text: str, variety: str = "us", style: str = "none", next_id: int = 1
|
|
|
216
242
|
for o in occ:
|
|
217
243
|
sh = "-" if "-" in o.form else " " if " " in o.form else "closed"
|
|
218
244
|
if sh == "closed": # a non-word like "longterm"
|
|
219
|
-
add(o, (_recase(o.form, hyph), _recase(o.form, open_)), rule, "compound", [o]
|
|
245
|
+
add(o, (_recase(o.form, hyph), _recase(o.form, open_)), rule, "compound", [o],
|
|
246
|
+
SPLIT_EXPLAIN.format(**names, word=o.form, hyph=hyph, open=open_))
|
|
220
247
|
continue
|
|
221
248
|
if shape[sh] * 2 > majority and len(shape) > 1:
|
|
222
249
|
continue # the majority shape is not questioned
|
|
223
250
|
other = open_ if sh == "-" else hyph
|
|
224
|
-
add(o, (_recase(o.form, other),), rule, "compound", [o]
|
|
251
|
+
add(o, (_recase(o.form, other),), rule, "compound", [o],
|
|
252
|
+
SHAPE_EXPLAIN.format(**names, hyph=hyph, open=open_))
|
|
225
253
|
for key, occ in case_families(text, spans).items():
|
|
226
254
|
counts = Counter(o.form for o in occ)
|
|
227
255
|
ranked = [f for f, _ in counts.most_common()]
|
|
228
256
|
majority = counts[ranked[0]]
|
|
229
|
-
|
|
257
|
+
forms = [f"'{f}' {_times(n)}" for f, n in counts.most_common()]
|
|
258
|
+
desc = ", ".join(forms[:-1]) + " and " + forms[-1]
|
|
259
|
+
explain = CASE_EXPLAIN.format(counts=desc)
|
|
230
260
|
for o in occ:
|
|
231
261
|
if counts[o.form] * 2 > majority:
|
|
232
262
|
continue
|
|
233
|
-
add(o, tuple(f for f in ranked if f != o.form), CASE_RULE
|
|
263
|
+
add(o, tuple(f for f in ranked if f != o.form), CASE_RULE, "consistency", [o], explain)
|
|
234
264
|
return out, groups
|
|
@@ -11,7 +11,7 @@ from adjudicate.apply import to_offsets
|
|
|
11
11
|
|
|
12
12
|
from . import basics
|
|
13
13
|
|
|
14
|
-
from .basics import CLOSED_DOUBLES, DOUBLE_RULE, Double, double_edit, doubled_words
|
|
14
|
+
from .basics import CLOSED_DOUBLES, DOUBLE_EXPLAIN, DOUBLE_RULE, Double, double_edit, doubled_words
|
|
15
15
|
from .lt import Match
|
|
16
16
|
|
|
17
17
|
# LanguageTool rules whose replacement may be applied outright, each only where the
|
|
@@ -63,6 +63,36 @@ VARIETY_DISABLED: dict[str, frozenset[str]] = {
|
|
|
63
63
|
SPELLING_RULE = ("Choose the correctly spelled word only if the marked text is an ordinary word "
|
|
64
64
|
"misspelled. KEEP if it is a name, an acronym, a product, jargon, a code "
|
|
65
65
|
"identifier, a foreign word, or a deliberate spelling.")
|
|
66
|
+
GRAMMAR_RULE = ("LanguageTool rule {rule}. Choose the option that makes the sentence correct; KEEP if "
|
|
67
|
+
"the original is acceptable or the suggestion changes the meaning.")
|
|
68
|
+
# The variety each spelling rule checks, named by the suffix of its id.
|
|
69
|
+
SPELLING_VARIETY = {"US": "American English", "GB": "British English", "AU": "Australian English",
|
|
70
|
+
"CA": "Canadian English", "NZ": "New Zealand English", "ZA": "South African English"}
|
|
71
|
+
|
|
72
|
+
_DID_YOU_MEAN = re.compile(r"Did you mean\b(.*?)\?\s*")
|
|
73
|
+
_SENTENCE_END = re.compile(r"(?<=[.?!])\s+(?=[A-Z'(])")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def spelling_explain(word: str, rule: str) -> str:
|
|
77
|
+
"""LanguageTool's spelling message ("Possible spelling mistake found.") says nothing
|
|
78
|
+
the person answering can use. This names the dictionary's variety instead."""
|
|
79
|
+
variety = SPELLING_VARIETY[rule.rsplit("_", 1)[-1]]
|
|
80
|
+
return f"'{word}' isn't in the {variety} dictionary. LanguageTool suggests the spellings shown."
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def lt_explain(message: str) -> str:
|
|
84
|
+
"""LanguageTool's message, cleaned for the person answering. "Did you mean X?" goes,
|
|
85
|
+
since the options show X; a message that is only that question becomes "LanguageTool
|
|
86
|
+
suggests X." Quotes become single quotes. At most two sentences are kept."""
|
|
87
|
+
msg = re.sub(r'["\u201c\u201d]', "'", " ".join(message.split()))
|
|
88
|
+
rest = _DID_YOU_MEAN.sub("", msg).strip()
|
|
89
|
+
if not rest:
|
|
90
|
+
m = _DID_YOU_MEAN.search(msg)
|
|
91
|
+
rest = f"LanguageTool suggests{m.group(1)}." if m else msg or "LanguageTool flags this wording."
|
|
92
|
+
if rest.startswith("(") and rest.endswith(")"):
|
|
93
|
+
rest = rest[1:-1]
|
|
94
|
+
rest = " ".join(_SENTENCE_END.split(rest)[:2])
|
|
95
|
+
return rest if rest[-1:] in ".?!" else rest + "."
|
|
66
96
|
|
|
67
97
|
|
|
68
98
|
@dataclass
|
|
@@ -170,7 +200,8 @@ def double_item(text: str, d: Double, item_id: int) -> Item:
|
|
|
170
200
|
word = text[s:d.end]
|
|
171
201
|
line, col = _line_col(text, s)
|
|
172
202
|
return Item(item_id, word, (text[s:d.start], "KEEP"), DOUBLE_RULE,
|
|
173
|
-
sentence_context(text, s, d.end), line, col, col + len(word) - 1, source="repeat"
|
|
203
|
+
sentence_context(text, s, d.end), line, col, col + len(word) - 1, source="repeat",
|
|
204
|
+
explain=DOUBLE_EXPLAIN)
|
|
174
205
|
|
|
175
206
|
|
|
176
207
|
def double_message(text: str, d: Double) -> str:
|
|
@@ -259,13 +290,13 @@ def partition(text: str, matches: list[Match], accept: set[str] | None = None,
|
|
|
259
290
|
start, end, reps = _readable(text, start, end, reps)
|
|
260
291
|
word = text[start:end]
|
|
261
292
|
options = tuple(dict.fromkeys(r for r in reps if r != word)) + ("KEEP",)
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
293
|
+
if m.rule in SPELLING:
|
|
294
|
+
rule, explain, source = SPELLING_RULE, spelling_explain(original, m.rule), "spelling"
|
|
295
|
+
else:
|
|
296
|
+
rule, explain, source = GRAMMAR_RULE.format(rule=m.rule), lt_explain(m.message), "grammar"
|
|
265
297
|
line, col = _line_col(text, start)
|
|
266
298
|
items.append(Item(next_id, word, options, rule, sentence_context(text, start, end),
|
|
267
|
-
line, col, col + (end - start) - 1,
|
|
268
|
-
source="spelling" if m.rule in SPELLING else "grammar"))
|
|
299
|
+
line, col, col + (end - start) - 1, source=source, explain=explain))
|
|
269
300
|
rules[next_id] = m.rule
|
|
270
301
|
next_id += 1
|
|
271
302
|
continue
|
|
@@ -374,5 +405,6 @@ def typos_item(text: str, m: Match, item_id: int) -> Item:
|
|
|
374
405
|
line, col = _line_col(text, m.start)
|
|
375
406
|
word = text[m.start:m.end]
|
|
376
407
|
options = tuple(dict.fromkeys(c for c in m.replacements[:4] if c != word)) + ("KEEP",)
|
|
408
|
+
explain = f"'{word}' is a common misspelling of " + " or ".join(f"'{o}'" for o in options[:-1]) + "."
|
|
377
409
|
return Item(item_id, word, options, SPELLING_RULE, sentence_context(text, m.start, m.end),
|
|
378
|
-
line, col, col + len(word) - 1, source="spelling")
|
|
410
|
+
line, col, col + len(word) - 1, source="spelling", explain=explain)
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "proofix"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.8.2"
|
|
4
4
|
description = "Fix typos and punctuation in Markdown: LanguageTool detects, a language model adjudicates, comma placement is corrected under a diff guard."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
requires-python = ">=3.11"
|
|
7
7
|
license = "MIT"
|
|
8
8
|
license-files = ["LICENSE"]
|
|
9
9
|
authors = [{ name = "Andrew Brož" }]
|
|
10
|
-
dependencies = ["adjudicate>=0.3.
|
|
10
|
+
dependencies = ["adjudicate>=0.3.5,<0.4"]
|
|
11
11
|
classifiers = [
|
|
12
12
|
"Development Status :: 3 - Alpha",
|
|
13
13
|
"Environment :: Console",
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from adjudicate import Cache, apply_changes
|
|
7
|
+
from adjudicate.llm import Endpoint
|
|
8
|
+
from proofix import api
|
|
9
|
+
from proofix.commas import CommaCache
|
|
10
|
+
from proofix.lt import parse_matches
|
|
11
|
+
|
|
12
|
+
TYPOS = (Path(__file__).parent.parent / "examples" / "typos.md").read_text()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(text, **kw):
|
|
16
|
+
return api.fix(text, api.Options(**kw), None, Cache(None), CommaCache(None))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def test_changes_reproduce_the_output(monkeypatch):
|
|
20
|
+
monkeypatch.setenv("PATH", "/nonexistent") # no LanguageTool, no typos
|
|
21
|
+
r = run("Badspace and entity.\r\n")
|
|
22
|
+
assert apply_changes("Badspace and entity.\r\n", r.changes) == r.text
|
|
23
|
+
assert r.lt_missing
|
|
24
|
+
assert {s.why for s in r.skipped} >= {"LanguageTool not found"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def test_skip_hygiene():
|
|
28
|
+
text = "Badspace.\n"
|
|
29
|
+
assert run(text, skip=frozenset({"hygiene", "mechanical", "adjudicated", "typos"})).text == text
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_no_file_io(tmp_path, monkeypatch):
|
|
33
|
+
monkeypatch.chdir(tmp_path)
|
|
34
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
35
|
+
run(TYPOS)
|
|
36
|
+
assert list(tmp_path.iterdir()) == []
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_cached_comma_decision_is_labelled_cache(monkeypatch):
|
|
40
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
41
|
+
text = "The committee, decided to postpone the vote.\n"
|
|
42
|
+
cc = CommaCache(None)
|
|
43
|
+
cc.data[CommaCache.key("us|leave", "The committee, decided to postpone the vote.")] = {
|
|
44
|
+
"text": "The committee decided to postpone the vote.", "confidence": 0.95, "reason": "stub"}
|
|
45
|
+
r = api.fix(text, api.Options(skip=frozenset({"typos"})), None, Cache(None), cc)
|
|
46
|
+
assert r.text == "The committee decided to postpone the vote.\n"
|
|
47
|
+
commas = [c for c in r.changes if c.check == "commas"]
|
|
48
|
+
assert len(commas) == 1 and commas[0].decided_by == "cache"
|
|
49
|
+
assert apply_changes(text, r.changes) == r.text
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class Fake(Endpoint):
|
|
53
|
+
def chat(self, system, user, timeout=None, json_mode=True):
|
|
54
|
+
if "comma placement" in system:
|
|
55
|
+
return json.dumps({"changed": [], "notes": []})
|
|
56
|
+
ds = []
|
|
57
|
+
for line in user.splitlines():
|
|
58
|
+
if line.startswith("Item "):
|
|
59
|
+
options = [o.split("] ", 1)[-1] for o in line.split("options: ")[1].split(" | ")]
|
|
60
|
+
ds.append({"id": int(line.split()[1]), "choice": options[0],
|
|
61
|
+
"confidence": 0.9, "reason": "model says so"})
|
|
62
|
+
return json.dumps({"decisions": ds})
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_model_decided_compound_is_labelled_model(monkeypatch):
|
|
66
|
+
fixture = (Path(__file__).parent / "fixtures" / "typos.lt.json").read_text()
|
|
67
|
+
monkeypatch.setattr(api, "find_languagetool", lambda: "/replay/languagetool")
|
|
68
|
+
monkeypatch.setattr(api, "run_languagetool", lambda t, target, level="default", **kw: parse_matches(fixture, t))
|
|
69
|
+
r = api.fix(TYPOS, api.Options(skip=frozenset({"typos", "commas"})),
|
|
70
|
+
Fake(url="http://x/v1", model="m"), Cache(None), CommaCache(None))
|
|
71
|
+
assert apply_changes(TYPOS, r.changes) == r.text
|
|
72
|
+
third = [c for c in r.changes if c.after == "-" and c.decided_by == "model"]
|
|
73
|
+
assert third and third[0].check == "adjudicated" and third[0].reason == "model says so"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_no_endpoint_is_not_a_review_item_per_sentence(monkeypatch):
|
|
77
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
78
|
+
r = run(TYPOS)
|
|
79
|
+
assert not [i for i in r.review if "no model configured" in i.message]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
# Undecided decisions are review items a reader can answer: offsets into fix()'s input,
|
|
83
|
+
# the options, the model's pick and the cache key.
|
|
84
|
+
|
|
85
|
+
class Picks(Endpoint):
|
|
86
|
+
"""Picks each item's first option with a set confidence."""
|
|
87
|
+
def __init__(self, confidence):
|
|
88
|
+
super().__init__(url="http://x/v1", model="m")
|
|
89
|
+
self.confidence = confidence
|
|
90
|
+
|
|
91
|
+
def chat(self, system, user, timeout=None, json_mode=True):
|
|
92
|
+
ds = []
|
|
93
|
+
for line in user.splitlines():
|
|
94
|
+
if line.startswith("Item "):
|
|
95
|
+
options = [o.split("] ", 1)[-1] for o in line.split("options: ")[1].split(" | ")]
|
|
96
|
+
ds.append({"id": int(line.split()[1]), "choice": options[0],
|
|
97
|
+
"confidence": self.confidence, "reason": "model says so"})
|
|
98
|
+
return json.dumps({"decisions": ds})
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def ask(text, ep=None, cache=None, **kw):
|
|
102
|
+
kw.setdefault("skip", frozenset({"typos", "commas"}))
|
|
103
|
+
return api.fix(text, api.Options(replay_cache=True, **kw), ep, cache or Cache(None),
|
|
104
|
+
CommaCache(None))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def undecided(r):
|
|
108
|
+
return [i for i in r.review if i.kind == "undecided"]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_undecided_double_is_question(monkeypatch):
|
|
112
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
113
|
+
text = "I saw saw it.\n"
|
|
114
|
+
r = ask(text)
|
|
115
|
+
[i] = undecided(r)
|
|
116
|
+
[d] = r.decisions
|
|
117
|
+
assert text[i.start:i.end] == "saw saw"
|
|
118
|
+
assert i.options == ("saw",)
|
|
119
|
+
assert i.key == Cache.key("proofix|us", d.item)
|
|
120
|
+
assert i.suggestion is None and i.confidence is None
|
|
121
|
+
assert i.check == "repeat" and i.pass_ == "proofix"
|
|
122
|
+
assert i.explain == d.item.explain and i.explain.startswith("A word appears twice")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_low_confidence_pick_is_suggestion(monkeypatch):
|
|
126
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
127
|
+
text = "I saw saw it.\n"
|
|
128
|
+
r = ask(text, ep=Picks(0.3))
|
|
129
|
+
assert r.text == text
|
|
130
|
+
[i] = undecided(r)
|
|
131
|
+
assert i.suggestion == "saw" and i.confidence == 0.3
|
|
132
|
+
assert i.reason == "model says so"
|
|
133
|
+
assert "low confidence" in i.message
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def test_offsets_map_through_pass_one(monkeypatch):
|
|
137
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
138
|
+
text = "Hello , I saw saw it.\n"
|
|
139
|
+
r = ask(text)
|
|
140
|
+
assert r.applied # pass 1 removed a space before the double
|
|
141
|
+
[i] = undecided(r)
|
|
142
|
+
assert text[i.start:i.end] == "saw saw"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def test_offsets_crlf_input(monkeypatch):
|
|
146
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
147
|
+
text = "First line.\r\nHello , I saw saw it.\r\n"
|
|
148
|
+
r = ask(text)
|
|
149
|
+
[i] = undecided(r)
|
|
150
|
+
assert text[i.start:i.end] == "saw saw"
|
|
151
|
+
assert i.line == 2
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def test_offsets_after_pass_two(monkeypatch):
|
|
155
|
+
# a consistency item sits on the text after pass 2: a pass-2 edit before it moves it
|
|
156
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
157
|
+
text = "I saw saw the e-mail and the email.\n"
|
|
158
|
+
cache = Cache(None)
|
|
159
|
+
first = ask(text, cache=cache)
|
|
160
|
+
double = next(d for d in first.decisions if d.item.source == "repeat")
|
|
161
|
+
cache.put_user(Cache.key("proofix|us", double.item), "saw")
|
|
162
|
+
r = ask(text, cache=cache)
|
|
163
|
+
assert r.text.startswith("I saw the")
|
|
164
|
+
[i] = undecided(r)
|
|
165
|
+
assert i.check == "compound"
|
|
166
|
+
assert text[i.start:i.end] == "e-mail"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def test_user_answer_applied_on_replay(monkeypatch):
|
|
170
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
171
|
+
text = "I saw saw it.\n"
|
|
172
|
+
[d] = ask(text).decisions
|
|
173
|
+
key = Cache.key("proofix|us", d.item)
|
|
174
|
+
cache = Cache(None)
|
|
175
|
+
cache.put_user(key, "have seen")
|
|
176
|
+
r = ask(text, cache=cache)
|
|
177
|
+
assert r.text == "I have seen it.\n"
|
|
178
|
+
assert undecided(r) == []
|
|
179
|
+
cache.put_user(key, "KEEP")
|
|
180
|
+
r = ask(text, cache=cache)
|
|
181
|
+
assert r.text == text
|
|
182
|
+
assert undecided(r) == []
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
needs_lt = pytest.mark.skipif(api.find_languagetool() is None, reason="languagetool not installed")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
@needs_lt
|
|
189
|
+
def test_replay_cache_asks_about_lt_matches_without_endpoint():
|
|
190
|
+
text = "The lettr arrived yesterday.\n"
|
|
191
|
+
r = ask(text)
|
|
192
|
+
assert r.text == text
|
|
193
|
+
spelling = [i for i in undecided(r) if i.check == "spelling"]
|
|
194
|
+
assert spelling
|
|
195
|
+
i = spelling[0]
|
|
196
|
+
assert text[i.start:i.end] == "lettr"
|
|
197
|
+
assert len(i.options) >= 2 and "KEEP" not in i.options
|
|
198
|
+
assert i.key
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def test_offsets_end_before_removed_text(monkeypatch):
|
|
202
|
+
# pass 1 or hygiene removes text right after the item: the end stays at the item's end
|
|
203
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
204
|
+
for text in ("I saw saw\u200b next.\n", "I saw saw .\n", "I saw saw\r\nnext.\r\n"):
|
|
205
|
+
r = ask(text)
|
|
206
|
+
[i] = undecided(r)
|
|
207
|
+
assert text[i.start:i.end] == "saw saw", text
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_offsets_crlf_one_word_line(monkeypatch):
|
|
211
|
+
# each line ending is mapped on its own, not as one change spanning the line
|
|
212
|
+
monkeypatch.setenv("PATH", "/nonexistent")
|
|
213
|
+
text = "First.\r\ne-mail\r\nand the email.\r\n"
|
|
214
|
+
[i] = undecided(ask(text))
|
|
215
|
+
assert text[i.start:i.end] == "e-mail"
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import multiprocessing
|
|
3
|
+
|
|
4
|
+
from proofix.commas import CommaCache
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _add_and_save(path, key, barrier):
|
|
8
|
+
cache = CommaCache(path)
|
|
9
|
+
cache.data[key] = {"text": "x", "confidence": 1.0, "reason": ""}
|
|
10
|
+
barrier.wait()
|
|
11
|
+
cache.save()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_concurrent_saves_keep_both_entries(tmp_path):
|
|
15
|
+
ctx = multiprocessing.get_context("spawn")
|
|
16
|
+
path = tmp_path / "commas.json"
|
|
17
|
+
for n in range(20):
|
|
18
|
+
barrier = ctx.Barrier(2)
|
|
19
|
+
procs = [ctx.Process(target=_add_and_save, args=(path, f"{n}-{who}", barrier))
|
|
20
|
+
for who in "ab"]
|
|
21
|
+
for p in procs:
|
|
22
|
+
p.start()
|
|
23
|
+
for p in procs:
|
|
24
|
+
p.join()
|
|
25
|
+
assert p.exitcode == 0
|
|
26
|
+
assert {f"{n}-a", f"{n}-b"} <= set(json.loads(path.read_text()))
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Every question kind carries explain: plain prose for the person answering."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
|
|
7
|
+
from proofix import consistency, tiers
|
|
8
|
+
from proofix.basics import doubled_words
|
|
9
|
+
from proofix.lt import Match
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _match(text, word, rule, message, replacements):
|
|
13
|
+
s = text.index(word)
|
|
14
|
+
return Match(s, s + len(word), rule, "", message, "", replacements)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _item(text, m):
|
|
18
|
+
part = tiers.partition(text, [m], adjudicate_available=True)
|
|
19
|
+
assert len(part.items) == 1
|
|
20
|
+
return part.items[0]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_spelling_names_the_variety():
|
|
24
|
+
text = "I recieve mail.\n"
|
|
25
|
+
item = _item(text, _match(text, "recieve", "MORFOLOGIK_RULE_EN_GB", "Possible spelling mistake found.",
|
|
26
|
+
["receive", "relieve"]))
|
|
27
|
+
assert item.explain == ("'recieve' isn't in the British English dictionary. "
|
|
28
|
+
"LanguageTool suggests the spellings shown.")
|
|
29
|
+
assert item.rule == tiers.SPELLING_RULE
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.mark.parametrize("message, explain", [
|
|
33
|
+
# "Did you mean …?" goes when more remains; the options already show the word
|
|
34
|
+
('Did you mean "fewer"? The noun "people" is countable.', "The noun 'people' is countable."),
|
|
35
|
+
("Did you mean simply \"discussed the\"? You do not need the word \"about\" here.",
|
|
36
|
+
"You do not need the word 'about' here."),
|
|
37
|
+
# a message that is only the question becomes a statement
|
|
38
|
+
("Did you mean \"it's\" (short for 'it is') instead of 'its' (possessive pronoun)?",
|
|
39
|
+
"LanguageTool suggests 'it's' (short for 'it is') instead of 'its' (possessive pronoun)."),
|
|
40
|
+
# a parenthesised remark left on its own is unwrapped
|
|
41
|
+
("Did you mean \"have\"? ('could of' is probably an incorrect use of the verb phrase 'could have')",
|
|
42
|
+
"'could of' is probably an incorrect use of the verb phrase 'could have'."),
|
|
43
|
+
# quotes made single; a full stop added
|
|
44
|
+
("Two consecutive dots", "Two consecutive dots."),
|
|
45
|
+
('Use "an" instead of \'a\' if the following word starts with a vowel sound, e.g. \'an article\'.',
|
|
46
|
+
"Use 'an' instead of 'a' if the following word starts with a vowel sound, e.g. 'an article'."),
|
|
47
|
+
# at most two sentences
|
|
48
|
+
("One. Two. Three.", "One. Two."),
|
|
49
|
+
("", "LanguageTool flags this wording."),
|
|
50
|
+
])
|
|
51
|
+
def test_languagetool_message_cleaned(message, explain):
|
|
52
|
+
assert tiers.lt_explain(message) == explain
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_grammar_item_uses_the_message_and_keeps_the_rule_id_out():
|
|
56
|
+
text = "Less people came.\n"
|
|
57
|
+
item = _item(text, _match(text, "Less", "FEWER_LESS", 'Did you mean "fewer"? The noun "people" is countable.',
|
|
58
|
+
["Fewer"]))
|
|
59
|
+
assert item.explain == "The noun 'people' is countable."
|
|
60
|
+
assert "FEWER_LESS" in item.rule and "FEWER_LESS" not in item.explain
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def test_typos_item_names_the_correction():
|
|
64
|
+
text = "Teh plan.\n"
|
|
65
|
+
m = Match(0, 3, "typos", "TYPOS", "", "", ["The"])
|
|
66
|
+
assert tiers.typos_item(text, m, 1).explain == "'Teh' is a common misspelling of 'The'."
|
|
67
|
+
m = Match(0, 3, "typos", "TYPOS", "", "", ["The", "Ten"])
|
|
68
|
+
assert tiers.typos_item(text, m, 1).explain == "'Teh' is a common misspelling of 'The' or 'Ten'."
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_compound_explains_by_case():
|
|
72
|
+
text = "Send an e-mail. The longterm plan is a long-term plan, a long-term goal and a long term view.\n"
|
|
73
|
+
its, _ = consistency.items(text, "uk")
|
|
74
|
+
by_word = {i.word: i.explain for i in its}
|
|
75
|
+
assert by_word["e-mail"] == "In British English, Oxford spells this 'email', without a hyphen."
|
|
76
|
+
assert by_word["longterm"] == ("In British English, 'longterm' is not one word: write 'long-term' "
|
|
77
|
+
"before a noun it describes, and 'long term' elsewhere.")
|
|
78
|
+
assert by_word["long term"] == ("In British English, write 'long-term' before a noun it describes, "
|
|
79
|
+
"and 'long term' elsewhere.")
|
|
80
|
+
its, _ = consistency.items(text, "us", "ap")
|
|
81
|
+
assert {i.word: i.explain for i in its}["long term"] == (
|
|
82
|
+
"In American English, write 'long-term' before a noun it describes, and 'long term' elsewhere. "
|
|
83
|
+
"AP style leaves that hyphen out when the meaning is clear without it.")
|
|
84
|
+
its, _ = consistency.items("A cyber attack.\n", "us")
|
|
85
|
+
assert its[0].explain == ("In American English, this may be one word: 'cyberattack'. American usage "
|
|
86
|
+
"closes most established compounds.")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_case_explain_counts_the_forms():
|
|
90
|
+
text = "Some Frontier AI labs, frontier AI labs, frontier AI labs and frontier AI labs.\n"
|
|
91
|
+
its, _ = consistency.items(text, "us")
|
|
92
|
+
assert [i.explain for i in its] == [
|
|
93
|
+
"This document writes 'frontier AI' 3 times and 'Frontier AI' once. A term keeps one "
|
|
94
|
+
"capitalisation throughout, unless one use is a heading or a proper name."]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _all_kinds():
|
|
98
|
+
"""One item of every question kind."""
|
|
99
|
+
out = []
|
|
100
|
+
t = "I recieve mail. Less people came.\n"
|
|
101
|
+
part = tiers.partition(t, [
|
|
102
|
+
_match(t, "recieve", "MORFOLOGIK_RULE_EN_US", "Possible spelling mistake found.", ["receive"]),
|
|
103
|
+
_match(t, "Less", "FEWER_LESS", 'Did you mean "fewer"?', ["Fewer"])], adjudicate_available=True)
|
|
104
|
+
out += part.items
|
|
105
|
+
t = "We saw the the cat.\n"
|
|
106
|
+
out.append(tiers.double_item(t, doubled_words(t, [])[0], 1))
|
|
107
|
+
out.append(tiers.typos_item("Teh plan.\n", Match(0, 3, "typos", "TYPOS", "", "", ["The"]), 1))
|
|
108
|
+
for variety in ("us", "uk"):
|
|
109
|
+
its, _ = consistency.items("Send an e-mail. The longterm plan, a long-term plan and a long term "
|
|
110
|
+
"plan. Some Frontier AI labs, frontier AI labs, frontier AI labs.\n", variety)
|
|
111
|
+
out += its
|
|
112
|
+
assert {i.source for i in out} == {"spelling", "grammar", "repeat", "compound", "consistency"}
|
|
113
|
+
return out
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.mark.parametrize("item", _all_kinds(), ids=lambda i: f"{i.source}:{i.word}")
|
|
117
|
+
def test_every_kind_has_a_plain_explain(item):
|
|
118
|
+
assert item.explain
|
|
119
|
+
assert "KEEP" not in item.explain and "[[" not in item.explain
|
|
120
|
+
assert not re.search(r"\b(choose|option)", item.explain, re.I)
|
|
121
|
+
assert not re.search(r"[A-Z]+_[A-Z_]+", item.explain) # no rule ids
|
|
122
|
+
assert item.explain not in item.rule # written once
|
proofix-0.7.0/tests/test_api.py
DELETED
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
from pathlib import Path
|
|
3
|
-
|
|
4
|
-
from adjudicate import Cache, apply_changes
|
|
5
|
-
from adjudicate.llm import Endpoint
|
|
6
|
-
from proofix import api
|
|
7
|
-
from proofix.commas import CommaCache
|
|
8
|
-
from proofix.lt import parse_matches
|
|
9
|
-
|
|
10
|
-
TYPOS = (Path(__file__).parent.parent / "examples" / "typos.md").read_text()
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
def run(text, **kw):
|
|
14
|
-
return api.fix(text, api.Options(**kw), None, Cache(None), CommaCache(None))
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def test_changes_reproduce_the_output(monkeypatch):
|
|
18
|
-
monkeypatch.setenv("PATH", "/nonexistent") # no LanguageTool, no typos
|
|
19
|
-
r = run("Badspace and entity.\r\n")
|
|
20
|
-
assert apply_changes("Badspace and entity.\r\n", r.changes) == r.text
|
|
21
|
-
assert r.lt_missing
|
|
22
|
-
assert {s.why for s in r.skipped} >= {"LanguageTool not found"}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
def test_skip_hygiene():
|
|
26
|
-
text = "Badspace.\n"
|
|
27
|
-
assert run(text, skip=frozenset({"hygiene", "mechanical", "adjudicated", "typos"})).text == text
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
def test_no_file_io(tmp_path, monkeypatch):
|
|
31
|
-
monkeypatch.chdir(tmp_path)
|
|
32
|
-
monkeypatch.setenv("PATH", "/nonexistent")
|
|
33
|
-
run(TYPOS)
|
|
34
|
-
assert list(tmp_path.iterdir()) == []
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
def test_cached_comma_decision_is_labelled_cache(monkeypatch):
|
|
38
|
-
monkeypatch.setenv("PATH", "/nonexistent")
|
|
39
|
-
text = "The committee, decided to postpone the vote.\n"
|
|
40
|
-
cc = CommaCache(None)
|
|
41
|
-
cc.data[CommaCache.key("us|leave", "The committee, decided to postpone the vote.")] = {
|
|
42
|
-
"text": "The committee decided to postpone the vote.", "confidence": 0.95, "reason": "stub"}
|
|
43
|
-
r = api.fix(text, api.Options(skip=frozenset({"typos"})), None, Cache(None), cc)
|
|
44
|
-
assert r.text == "The committee decided to postpone the vote.\n"
|
|
45
|
-
commas = [c for c in r.changes if c.check == "commas"]
|
|
46
|
-
assert len(commas) == 1 and commas[0].decided_by == "cache"
|
|
47
|
-
assert apply_changes(text, r.changes) == r.text
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
class Fake(Endpoint):
|
|
51
|
-
def chat(self, system, user, timeout=None, json_mode=True):
|
|
52
|
-
if "comma placement" in system:
|
|
53
|
-
return json.dumps({"changed": [], "notes": []})
|
|
54
|
-
ds = []
|
|
55
|
-
for line in user.splitlines():
|
|
56
|
-
if line.startswith("Item "):
|
|
57
|
-
options = [o.split("] ", 1)[-1] for o in line.split("options: ")[1].split(" | ")]
|
|
58
|
-
ds.append({"id": int(line.split()[1]), "choice": options[0],
|
|
59
|
-
"confidence": 0.9, "reason": "model says so"})
|
|
60
|
-
return json.dumps({"decisions": ds})
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
def test_model_decided_compound_is_labelled_model(monkeypatch):
|
|
64
|
-
fixture = (Path(__file__).parent / "fixtures" / "typos.lt.json").read_text()
|
|
65
|
-
monkeypatch.setattr(api, "find_languagetool", lambda: "/replay/languagetool")
|
|
66
|
-
monkeypatch.setattr(api, "run_languagetool", lambda t, target, level="default", **kw: parse_matches(fixture, t))
|
|
67
|
-
r = api.fix(TYPOS, api.Options(skip=frozenset({"typos", "commas"})),
|
|
68
|
-
Fake(url="http://x/v1", model="m"), Cache(None), CommaCache(None))
|
|
69
|
-
assert apply_changes(TYPOS, r.changes) == r.text
|
|
70
|
-
third = [c for c in r.changes if c.after == "-" and c.decided_by == "model"]
|
|
71
|
-
assert third and third[0].check == "adjudicated" and third[0].reason == "model says so"
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
def test_no_endpoint_is_not_a_review_item_per_sentence(monkeypatch):
|
|
75
|
-
monkeypatch.setenv("PATH", "/nonexistent")
|
|
76
|
-
r = run(TYPOS)
|
|
77
|
-
assert not [i for i in r.review if "no model configured" in i.message]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|