brainlint 0.1.0b1__py3-none-any.whl

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.
brainlint/__init__.py ADDED
@@ -0,0 +1,64 @@
1
+ """brainlint: a prose linter for explanatory texts that simulates readers.
2
+
3
+ Public API (D8, mirrors Airlint)::
4
+
5
+ import brainlint
6
+ config = brainlint.load_config("brainlint.yaml")
7
+ diags = brainlint.check_text("Text.", lang="en", config=config) # -> list[Diagnostic]
8
+ trace = brainlint.analyze_text("Text.", config=config) # per sentence, per persona
9
+
10
+ from brainlint.rules import REGISTRY
11
+ REGISTRY["LOD001"].implemented # False while the rule is reserved
12
+ """
13
+
14
+ from importlib.metadata import version
15
+
16
+ __version__ = version("brainlint")
17
+
18
+ from brainlint.backends import BackendError
19
+ from brainlint.config import Config, ConfigError, load_config
20
+ from brainlint.diagnostics import Diagnostic, Severity
21
+ from brainlint.linter import Analysis, analyze, lint
22
+ from brainlint.rules import REGISTRY
23
+ from brainlint.sources import make_source
24
+
25
+
26
+ def _config(lang: str | None, config: Config | None) -> Config:
27
+ overrides = {"lang": lang} if lang is not None else {}
28
+ if config is None:
29
+ return load_config(known_rules=set(REGISTRY), overrides=overrides)
30
+ return config.with_overrides(overrides, known_rules=set(REGISTRY))
31
+
32
+
33
+ def check_text(
34
+ text: str, lang: str | None = None, config: Config | None = None, kind: str = "text"
35
+ ) -> list[Diagnostic]:
36
+ """Lint a string and return its diagnostics, sorted by offset.
37
+
38
+ ``lang`` is applied over ``config`` (the packaged defaults when it is None). ``kind`` is
39
+ ``"text"`` or ``"markdown"``. Raises :class:`ConfigError` without personas and
40
+ :class:`BackendError` when the configured backend cannot run.
41
+ """
42
+ return lint(make_source("<text>", text, kind), _config(lang, config)).diagnostics
43
+
44
+
45
+ def analyze_text(
46
+ text: str, lang: str | None = None, config: Config | None = None, kind: str = "text"
47
+ ) -> Analysis:
48
+ """The per-sentence, per-persona trace: ``.steps`` with each persona's load and signals."""
49
+ return analyze(make_source("<text>", text, kind), _config(lang, config))
50
+
51
+
52
+ __all__ = [
53
+ "REGISTRY",
54
+ "Analysis",
55
+ "BackendError",
56
+ "Config",
57
+ "ConfigError",
58
+ "Diagnostic",
59
+ "Severity",
60
+ "__version__",
61
+ "analyze_text",
62
+ "check_text",
63
+ "load_config",
64
+ ]
brainlint/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from brainlint.cli import main
2
+
3
+ raise SystemExit(main())
brainlint/backends.py ADDED
@@ -0,0 +1,298 @@
1
+ """Interfaces of the two pipeline layers and their backends.
2
+
3
+ Layer 1 (:class:`Extractor`) turns a sentence into an :class:`~brainlint.models.Extraction`,
4
+ once per sentence, shared by all personas (D2). Layer 2 (:class:`Decider`) projects that
5
+ extraction onto one persona's state and returns rule signals.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections import defaultdict
12
+ from dataclasses import dataclass, replace
13
+ from datetime import date
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Protocol
16
+
17
+ from pydantic import BaseModel, ConfigDict, Field, ValidationError
18
+
19
+ from brainlint.models import (
20
+ Concept,
21
+ Decision,
22
+ Extraction,
23
+ Misconception,
24
+ OpenQuestion,
25
+ Persona,
26
+ ReaderState,
27
+ RuleId,
28
+ Sentence,
29
+ Signal,
30
+ )
31
+ from brainlint.rules.decider import RuleDecider
32
+ from brainlint.sources import STDIN_NAME
33
+
34
+ if TYPE_CHECKING:
35
+ from brainlint.config import Config
36
+
37
+
38
+ class BackendError(Exception):
39
+ """A backend cannot run: not configured, not implemented, or missing a recording."""
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class EarlierPremise:
44
+ sentence: Sentence
45
+ proposition: str
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class ExtractionContext:
50
+ """What layer 1 may see: the text read so far as canonical state, never later text."""
51
+
52
+ language: str
53
+ read_so_far: tuple[Sentence, ...]
54
+ known_concepts: tuple[str, ...]
55
+ """Concept ids the text has introduced or used so far."""
56
+ open_questions: tuple[OpenQuestion, ...]
57
+ vocabulary: tuple[Concept, ...] = ()
58
+ """The union of the personas' concepts: ids, labels and aliases (D11)."""
59
+ new_concepts: tuple[Concept, ...] = ()
60
+ """Concepts outside the vocabulary that the text has brought in so far (``new:<id>``)."""
61
+ misconceptions: tuple[Misconception, ...] = ()
62
+ """The persona-independent misconception watch list (D11)."""
63
+ heading: str | None = None
64
+ section_start: bool = False
65
+ """The sentence is the first one after ``heading``."""
66
+ code: tuple[str, ...] = ()
67
+ """Code blocks shown between the previous sentence and this one (D18)."""
68
+ claims: tuple[str, ...] = ()
69
+ """Atomic claims of the sentences read so far (D20), to judge ``stated_in_text``."""
70
+
71
+ prior_premises: tuple[EarlierPremise, ...] = ()
72
+ legacy_questions: tuple[OpenQuestion, ...] | None = None
73
+ """Pre-equivalence open IDs for exact lookup of historical offline recordings."""
74
+
75
+ def with_new_concepts(self, concepts: tuple[Concept, ...]) -> ExtractionContext:
76
+ return replace(self, new_concepts=concepts)
77
+
78
+
79
+ class Extractor(Protocol):
80
+ def extract(self, sentence: Sentence, context: ExtractionContext) -> Extraction: ...
81
+
82
+
83
+ class Decider(Protocol):
84
+ def decide(
85
+ self, sentence: Sentence, extraction: Extraction, persona: Persona, state: ReaderState
86
+ ) -> Decision: ...
87
+
88
+
89
+ class OkDecider:
90
+ """Raises nothing. The decision layer and the rule checks come in the rule issues."""
91
+
92
+ def decide(
93
+ self, sentence: Sentence, extraction: Extraction, persona: Persona, state: ReaderState
94
+ ) -> Decision:
95
+ return Decision()
96
+
97
+
98
+ # --- Replay fixtures -------------------------------------------------------------------------
99
+
100
+ REPLAY_FORMAT = "brainlint-replay/2"
101
+
102
+
103
+ class ReplayMiss(BackendError):
104
+ """No recorded response for a sentence. Replay never falls back to a model."""
105
+
106
+
107
+ class RecordedExtraction(BaseModel):
108
+ model_config = ConfigDict(extra="forbid")
109
+ text: str
110
+ source: str | None = None
111
+ extraction: Extraction
112
+ prompt_version: str | None = None
113
+ raw: dict | None = None
114
+ """The model's output before canonicalisation, when recorded from a live backend."""
115
+
116
+
117
+ class RecordedSignal(BaseModel):
118
+ model_config = ConfigDict(extra="forbid")
119
+ text: str
120
+ persona_id: str
121
+ rule_id: RuleId
122
+ note: str = ""
123
+
124
+
125
+ class ReplayFixture(BaseModel):
126
+ """Recorded layer responses for one text, matched by sentence text."""
127
+
128
+ model_config = ConfigDict(extra="forbid")
129
+ format: str = Field(REPLAY_FORMAT, pattern=f"^{REPLAY_FORMAT}$")
130
+ source: str = ""
131
+ recorded_with: dict[str, str] = Field(default_factory=dict)
132
+ """Provenance, e.g. ``{"model": "...", "date": "..."}`` or ``{"model": "hand-written"}``."""
133
+ extractions: list[RecordedExtraction] = Field(default_factory=list)
134
+ goal_responses: dict[str, dict] = Field(default_factory=dict)
135
+ signals: list[RecordedSignal] = Field(default_factory=list)
136
+
137
+ @classmethod
138
+ def load(cls, path: str | Path) -> ReplayFixture:
139
+ try:
140
+ return cls.model_validate(json.loads(Path(path).read_text(encoding="utf-8")))
141
+ except OSError as exc:
142
+ raise BackendError(f"{path}: {exc.strerror}") from None
143
+ except (ValueError, ValidationError) as exc:
144
+ raise BackendError(f"{path}: invalid replay fixture: {exc}") from None
145
+
146
+ @classmethod
147
+ def load_all(cls, path: str | Path) -> ReplayFixture:
148
+ """One fixture file, or every ``*.json`` under a directory merged into one."""
149
+ path = Path(path)
150
+ if not path.is_dir():
151
+ return cls.load(path)
152
+ merged = cls(source=str(path))
153
+ for file in sorted(path.rglob("*.json")):
154
+ fixture = cls.load(file)
155
+ merged.extractions.extend(fixture.extractions)
156
+ merged.goal_responses.update(fixture.goal_responses)
157
+ merged.signals.extend(fixture.signals)
158
+ return merged
159
+
160
+
161
+ def recording_source(path: str) -> str:
162
+ """A batch input's identity, independent of the replay working directory."""
163
+ return path if path == STDIN_NAME else str(Path(path).resolve())
164
+
165
+
166
+ def _key(text: str) -> str:
167
+ return " ".join(text.split())
168
+
169
+
170
+ class ReplayExtractor:
171
+ """Repeated identical sentences take the recorded responses in order; the last repeats."""
172
+
173
+ def __init__(self, fixture: ReplayFixture, source: str | None = None) -> None:
174
+ self._items: dict[str, list[Extraction]] = defaultdict(list)
175
+ self._used: dict[str, int] = defaultdict(int)
176
+ accepted = {None, source}
177
+ if source is not None:
178
+ accepted.add(recording_source(source))
179
+ for item in fixture.extractions:
180
+ if source is not None and item.source not in accepted:
181
+ continue
182
+ self._items[_key(item.text)].append(item.extraction)
183
+
184
+ def extract(self, sentence: Sentence, context: ExtractionContext) -> Extraction:
185
+ key = _key(sentence.text)
186
+ found = self._items.get(key)
187
+ if not found:
188
+ raise ReplayMiss(f"no recorded extraction for {sentence.id}: {sentence.text!r}")
189
+ index = min(self._used[key], len(found) - 1)
190
+ self._used[key] += 1
191
+ return found[index]
192
+
193
+
194
+ class ReplayDecider:
195
+ """Replays recorded signals. A sentence with none for a persona is ok for that persona."""
196
+
197
+ def __init__(self, fixture: ReplayFixture) -> None:
198
+ self._signals: dict[tuple[str, str], list[Signal]] = defaultdict(list)
199
+ for item in fixture.signals:
200
+ signal = Signal(rule_id=item.rule_id, note=item.note)
201
+ self._signals[(_key(item.text), item.persona_id)].append(signal)
202
+
203
+ def decide(
204
+ self, sentence: Sentence, extraction: Extraction, persona: Persona, state: ReaderState
205
+ ) -> Decision:
206
+ return Decision(signals=list(self._signals.get((_key(sentence.text), persona.id), [])))
207
+
208
+
209
+ class Recorder:
210
+ """Wraps an extractor and keeps what it returned, to save as a replay fixture."""
211
+
212
+ def __init__(self, inner: Extractor, records: list[RecordedExtraction]) -> None:
213
+ self.inner = inner
214
+ self.records = records
215
+
216
+ @property
217
+ def usage(self): # forwarded so the summary still reports calls and cost
218
+ return getattr(self.inner, "usage", None)
219
+
220
+ def extract(self, sentence: Sentence, context: ExtractionContext) -> Extraction:
221
+ extraction = self.inner.extract(sentence, context)
222
+ self.records.append(
223
+ RecordedExtraction(
224
+ text=sentence.text,
225
+ extraction=extraction,
226
+ raw=getattr(self.inner, "last_raw", None),
227
+ prompt_version=getattr(self.inner, "last_prompt_version", None),
228
+ )
229
+ )
230
+ return extraction
231
+
232
+
233
+ def save_recording(
234
+ path: str | Path,
235
+ records: list[RecordedExtraction],
236
+ *,
237
+ source: str,
238
+ config: Config,
239
+ goal_responses: dict | None = None,
240
+ ) -> None:
241
+ provenance = {"backend": config.backend, "lang": config.lang, "date": date.today().isoformat()}
242
+ if config.backend == "openai":
243
+ from brainlint.llm import offline_version, version_label
244
+ from brainlint.prompts import PROMPT_VERSION
245
+
246
+ versions = sorted({r.prompt_version for r in records if r.prompt_version})
247
+ provenance |= {
248
+ "model": str(config.llm["model"]),
249
+ "prompt_version": version_label(versions, offline_version() or PROMPT_VERSION),
250
+ "reasoning_effort": str(config.llm.get("reasoning_effort")),
251
+ }
252
+ fixture = ReplayFixture(
253
+ source=source,
254
+ recorded_with=provenance,
255
+ extractions=records,
256
+ goal_responses=goal_responses or {},
257
+ )
258
+ Path(path).write_text(
259
+ fixture.model_dump_json(indent=2, exclude_none=True) + "\n", encoding="utf-8"
260
+ )
261
+
262
+
263
+ def build_decider(config: Config) -> Decider:
264
+ """Use recorded decisions when present, otherwise compute them from the extraction."""
265
+ if config.backend == "replay":
266
+ return build_backends(config)[1]
267
+ if config.uses_decisions:
268
+ return build_backends(config)[1]
269
+ return RuleDecider(config)
270
+
271
+
272
+ def build_backends(config: Config, *, source: str | None = None) -> tuple[Extractor, Decider]:
273
+ """The extractor and decider selected by ``llm.backend``."""
274
+ from brainlint.goals import DecisionsBackend
275
+
276
+ enabled = config.uses_decisions
277
+ pricing = config.llm["pricing"]
278
+ if config.backend == "openai":
279
+ from brainlint.llm import make_openai_extractor
280
+
281
+ extractor = make_openai_extractor(config.llm)
282
+ goal = DecisionsBackend(pricing, client=extractor.client) if enabled else None
283
+ return extractor, RuleDecider(config, goal)
284
+ if config.backend == "replay":
285
+ fixtures = config.llm.get("fixtures")
286
+ if not fixtures:
287
+ raise BackendError(
288
+ "the replay backend needs recorded responses: set llm.fixtures in the config "
289
+ "or pass --fixtures DIR"
290
+ )
291
+ fixture = ReplayFixture.load_all(fixtures)
292
+ if enabled:
293
+ goal = DecisionsBackend(pricing, recordings=fixture.goal_responses)
294
+ return ReplayExtractor(fixture, source), RuleDecider(config, goal)
295
+ return ReplayExtractor(fixture, source), (
296
+ ReplayDecider(fixture) if fixture.signals else RuleDecider(config)
297
+ )
298
+ raise BackendError(f"unknown backend {config.backend!r}")
brainlint/canonical.py ADDED
@@ -0,0 +1,203 @@
1
+ """Concept canonicalisation: map the model's raw references to stable concept ids (D11).
2
+
3
+ The model is asked to use vocabulary ids, but code does not trust it: every reference is resolved
4
+ again here, in this order:
5
+
6
+ 1. the id is a vocabulary id (after normalising case and separators);
7
+ 2. a named surface ("the loop", "хеш-функцию") matches a vocabulary label or alias;
8
+ 3. the id spelled as words matches a vocabulary label or alias ("new:hash_function" when the
9
+ vocabulary calls it ``hashing`` with label "hash function");
10
+ 4. the id or a named surface matches a concept introduced earlier in the same text;
11
+ 5. otherwise it is a new concept, ``new:<id>``, registered so later mentions keep the id.
12
+
13
+ Matching is case-insensitive, ignores punctuation, quotes and leading articles, and compares
14
+ word stems, so Russian case forms match ("корзина", "корзину", "корзины").
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Any
21
+
22
+ from brainlint.models import (
23
+ NEW_PREFIX,
24
+ Concept,
25
+ Extraction,
26
+ MisconceptionHit,
27
+ Prerequisite,
28
+ Question,
29
+ Reference,
30
+ Role,
31
+ )
32
+
33
+ _TRANSLIT = dict(
34
+ zip(
35
+ "абвгдеёжзийклмнопрстуфхцчшщъыьэюя",
36
+ "a b v g d e e zh z i y k l m n o p r s t u f kh ts ch sh shch _ y _ e yu ya".split(),
37
+ strict=True,
38
+ )
39
+ )
40
+ _ARTICLES = {"the", "a", "an", "this", "that", "these", "those"}
41
+ _RU_ENDINGS = sorted(
42
+ "ами ями ого его ому ему ыми ими ой ей ом ем ам ям ах ях ую юю ая яя ое ее ые ие ов ев "
43
+ "а я о е у ю ы и ь й".split(),
44
+ key=len,
45
+ reverse=True,
46
+ )
47
+ _EN_ENDINGS = ("es", "s")
48
+
49
+
50
+ def snake_id(text: str) -> str:
51
+ """An ASCII snake_case id: ``"Hash Function"`` -> ``hash_function``."""
52
+ text = "".join(_TRANSLIT.get(ch, ch) for ch in text.lower())
53
+ text = re.sub(r"[^a-z0-9]+", "_", text).strip("_")
54
+ if not text:
55
+ return "concept"
56
+ if text[0].isdigit():
57
+ text = "c_" + text
58
+ return re.sub(r"_+", "_", text)
59
+
60
+
61
+ def _stem(word: str) -> str:
62
+ if len(word) <= 3:
63
+ return word
64
+ endings = _RU_ENDINGS if re.search("[а-яё]", word) else _EN_ENDINGS
65
+ for ending in endings:
66
+ if word.endswith(ending) and len(word) - len(ending) >= 3:
67
+ return word[: -len(ending)]
68
+ return word
69
+
70
+
71
+ def match_key(text: str) -> str:
72
+ """A key that ignores case, punctuation, articles and word endings."""
73
+ words = re.findall(r"[\wё]+", text.lower().replace("_", " "))
74
+ words = [w for w in words if w not in _ARTICLES]
75
+ return " ".join(_stem(w) for w in words)
76
+
77
+
78
+ class Canonicalizer:
79
+ """Resolves references for one text; remembers the new concepts it has seen."""
80
+
81
+ def __init__(self, vocabulary: list[Concept] | tuple[Concept, ...] = ()) -> None:
82
+ self.vocabulary = {c.id: c for c in vocabulary}
83
+ self._vocab_keys: dict[str, str] = {}
84
+ for concept in vocabulary:
85
+ for name in (concept.id, concept.label, *concept.aliases):
86
+ if name:
87
+ self._vocab_keys.setdefault(match_key(name), concept.id)
88
+ self.new: dict[str, Concept] = {}
89
+ self._new_keys: dict[str, str] = {}
90
+
91
+ def new_concepts(self) -> tuple[Concept, ...]:
92
+ return tuple(self.new.values())
93
+
94
+ def names(self, concept: str, surface: str) -> bool | None:
95
+ """Whether ``surface`` contains the concept's id words, label or an alias; ``None`` when
96
+ the concept has no known names."""
97
+ entry = self.vocabulary.get(concept) or self.new.get(concept.removeprefix(NEW_PREFIX))
98
+ if entry is None or not surface:
99
+ return None
100
+ names = [match_key(n) for n in (entry.id, entry.label, *entry.aliases) if n]
101
+ haystack = f" {match_key(surface)} "
102
+ return any(name and f" {name} " in haystack for name in names)
103
+
104
+ def resolve(self, concept: str, surface: str = "", named: bool = True) -> str:
105
+ raw = concept.strip()
106
+ raw = raw.removeprefix(NEW_PREFIX).removeprefix("new_")
107
+ cid = snake_id(raw)
108
+ if cid in self.vocabulary:
109
+ return cid
110
+ surface_key = match_key(surface) if surface else ""
111
+ if surface_key and surface_key in self._vocab_keys:
112
+ return self._vocab_keys[surface_key]
113
+ id_key = match_key(cid)
114
+ if id_key in self._vocab_keys:
115
+ return self._vocab_keys[id_key]
116
+ if cid in self.new:
117
+ known = cid
118
+ elif surface_key and surface_key in self._new_keys:
119
+ known = self._new_keys[surface_key]
120
+ elif id_key in self._new_keys:
121
+ known = self._new_keys[id_key]
122
+ else:
123
+ known = cid
124
+ self.new[cid] = Concept(id=cid, label=surface if named else "")
125
+ self._new_keys[id_key] = cid
126
+ if surface_key and named: # never learn "it" or "this mechanism" as a name
127
+ self._new_keys.setdefault(surface_key, known)
128
+ entry = self.new[known]
129
+ if not entry.label:
130
+ self.new[known] = entry.model_copy(update={"label": surface})
131
+ elif surface not in (entry.label, *entry.aliases) and match_key(
132
+ entry.label
133
+ ) != match_key(surface):
134
+ self.new[known] = entry.model_copy(update={"aliases": [*entry.aliases, surface]})
135
+ return NEW_PREFIX + known
136
+
137
+ def extraction(
138
+ self,
139
+ raw: dict[str, Any],
140
+ *,
141
+ sentence_id: str,
142
+ open_questions: set[str],
143
+ watch_list: set[str],
144
+ ) -> Extraction:
145
+ """Turn the model's raw JSON into a canonical :class:`Extraction`."""
146
+ seen: set[str] = set()
147
+
148
+ def refs(items: list[dict[str, Any]]) -> list[Reference]:
149
+ out = []
150
+ for item in items:
151
+ surface = str(item.get("surface", "")).strip()
152
+ claimed = bool(item.get("named", True))
153
+ cid = self.resolve(str(item.get("concept", "")), surface, claimed)
154
+ # D11: "named" means the name or an alias appears; code checks it when it can.
155
+ named = self.names(cid, surface)
156
+ named = claimed if named is None else named
157
+ if cid in seen:
158
+ continue
159
+ seen.add(cid)
160
+ out.append(Reference(concept=cid, surface=surface, named=named))
161
+ return out
162
+
163
+ introduced = refs(raw.get("introduced", []))
164
+ used = refs(raw.get("used", []))
165
+ prerequisites = []
166
+ for item in raw.get("prerequisites", []):
167
+ prerequisites.append(
168
+ Prerequisite(
169
+ concept=self.resolve(str(item.get("concept", ""))),
170
+ target=item.get("target"),
171
+ given=item.get("given"),
172
+ proposition=str(item.get("proposition", "")).strip(),
173
+ stated_in_text=bool(item.get("stated_in_text")),
174
+ )
175
+ )
176
+ opened = [
177
+ Question(id=f"{sentence_id}.q{n}", text=str(q.get("text", "")).strip())
178
+ for n, q in enumerate(raw.get("questions_opened", []), start=1)
179
+ if str(q.get("text", "")).strip()
180
+ ]
181
+ closed = list(
182
+ dict.fromkeys(q for q in raw.get("questions_closed", []) if q in open_questions)
183
+ )
184
+ hits = {}
185
+ for item in raw.get("misconceptions", []):
186
+ # "addresses" wins when the model reports both for one item.
187
+ if (
188
+ item.get("id") in watch_list
189
+ and item.get("relation") in ("contradicts", "addresses")
190
+ and hits.get(item["id"]) != "addresses"
191
+ ):
192
+ hits[item["id"]] = item["relation"]
193
+ role = raw.get("role")
194
+ return Extraction(
195
+ role=Role(role) if role in Role._value2member_map_ else None,
196
+ introduced=introduced,
197
+ used=used,
198
+ prerequisites=prerequisites,
199
+ questions_opened=opened,
200
+ questions_closed=closed,
201
+ misconceptions=[MisconceptionHit(id=k, relation=v) for k, v in hits.items()],
202
+ claims=[str(c).strip() for c in raw.get("claims", []) if str(c).strip()],
203
+ )