citebound 0.2.0__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.
- citebound/__init__.py +51 -0
- citebound/citations.py +67 -0
- citebound/cli.py +109 -0
- citebound/grounding.py +545 -0
- citebound/passages.py +148 -0
- citebound/polarity.py +146 -0
- citebound/provenance.py +32 -0
- citebound/py.typed +0 -0
- citebound/refusal.py +58 -0
- citebound/units.py +155 -0
- citebound-0.2.0.dist-info/METADATA +360 -0
- citebound-0.2.0.dist-info/RECORD +16 -0
- citebound-0.2.0.dist-info/WHEEL +5 -0
- citebound-0.2.0.dist-info/entry_points.txt +2 -0
- citebound-0.2.0.dist-info/licenses/LICENSE +202 -0
- citebound-0.2.0.dist-info/top_level.txt +1 -0
citebound/polarity.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Conservative English operator checks, not a semantic entailment model.
|
|
2
|
+
|
|
3
|
+
Compare operators only in sentences with identical normalized content anchors.
|
|
4
|
+
An unrelated prohibition elsewhere in a chunk must not invalidate a faithful
|
|
5
|
+
claim. Missing modal or ordering words can be a harmless summary; explicit
|
|
6
|
+
opposing operators cannot.
|
|
7
|
+
Quantifier weakening is deliberately allowed: completeness is a separate task.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
|
|
15
|
+
from .passages import Passage
|
|
16
|
+
|
|
17
|
+
_SENTENCES = re.compile(r"(?<=[.!?])\s+|[\n;]+")
|
|
18
|
+
_WORDS = re.compile(r"[a-z]{2,}|\d[\d,]*(?:\.\d+)?")
|
|
19
|
+
_FILLER = frozenset(
|
|
20
|
+
[
|
|
21
|
+
"the",
|
|
22
|
+
"an",
|
|
23
|
+
"and",
|
|
24
|
+
"are",
|
|
25
|
+
"is",
|
|
26
|
+
"was",
|
|
27
|
+
"were",
|
|
28
|
+
"be",
|
|
29
|
+
"been",
|
|
30
|
+
"being",
|
|
31
|
+
"do",
|
|
32
|
+
"does",
|
|
33
|
+
"did",
|
|
34
|
+
"has",
|
|
35
|
+
"have",
|
|
36
|
+
"had",
|
|
37
|
+
"to",
|
|
38
|
+
"of",
|
|
39
|
+
"for",
|
|
40
|
+
"in",
|
|
41
|
+
"on",
|
|
42
|
+
"at",
|
|
43
|
+
"by",
|
|
44
|
+
"with",
|
|
45
|
+
"it",
|
|
46
|
+
"its",
|
|
47
|
+
"that",
|
|
48
|
+
"this",
|
|
49
|
+
"they",
|
|
50
|
+
"their",
|
|
51
|
+
"can",
|
|
52
|
+
]
|
|
53
|
+
)
|
|
54
|
+
# Long phrases first so 'no more than' is a ceiling, not a negation.
|
|
55
|
+
_OPERATORS = (
|
|
56
|
+
("comparison", "upper", r"no more than|at most|less than|below|lower than"),
|
|
57
|
+
("comparison", "lower", r"no fewer than|at least|more than|above|higher than"),
|
|
58
|
+
("negation", "negative", r"not|never|no|neither|nor"),
|
|
59
|
+
("modality", "required", r"must|shall|required to|requires?|mandatory"),
|
|
60
|
+
("modality", "optional", r"may|can|optional"),
|
|
61
|
+
("modality", "recommended", r"should|recommended"),
|
|
62
|
+
("quantifier", "universal", r"all|every|each|always"),
|
|
63
|
+
("quantifier", "partial", r"some|sometimes"),
|
|
64
|
+
("time", "before", r"prior to|before"),
|
|
65
|
+
("time", "after", r"following|after"),
|
|
66
|
+
)
|
|
67
|
+
_PATTERNS = tuple(
|
|
68
|
+
(kind, value, re.compile(rf"\b(?:{pattern})\b")) for kind, value, pattern in _OPERATORS
|
|
69
|
+
)
|
|
70
|
+
_CONTRACTIONS = re.compile(r"\b(?:cannot|can't|won't|shan't)\b|\b(\w+)n't\b")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class Statement:
|
|
75
|
+
anchors: frozenset[str]
|
|
76
|
+
operators: dict[str, frozenset[str]]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def statement(text: str) -> Statement:
|
|
80
|
+
text = text.lower().replace("\u2019", "'")
|
|
81
|
+
text = _CONTRACTIONS.sub("not", text)
|
|
82
|
+
# Discourse 'No.' and additive 'not only' do not negate the proposition.
|
|
83
|
+
text = re.sub(r"^\s*no[.,!]\s*|\bnot only\b", "", text)
|
|
84
|
+
operators: dict[str, set[str]] = {}
|
|
85
|
+
for kind, value, pattern in _PATTERNS:
|
|
86
|
+
if pattern.search(text):
|
|
87
|
+
operators.setdefault(kind, set()).add(value)
|
|
88
|
+
text = pattern.sub(" ", text)
|
|
89
|
+
# Only the common plural/third-person suffix is folded. This is an
|
|
90
|
+
# alignment aid, not stemming or a claim of language understanding.
|
|
91
|
+
anchors = frozenset(
|
|
92
|
+
w[:-1] if w.endswith("s") and len(w) > 3 else w.replace(",", "")
|
|
93
|
+
for w in _WORDS.findall(text)
|
|
94
|
+
if w not in _FILLER
|
|
95
|
+
)
|
|
96
|
+
return Statement(anchors, {k: frozenset(v) for k, v in operators.items()})
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _opposes(claim: Statement, evidence: Statement) -> bool:
|
|
100
|
+
c, e = claim.operators, evidence.operators
|
|
101
|
+
if c.get("negation") != e.get("negation"):
|
|
102
|
+
return True
|
|
103
|
+
for kind in ("modality", "comparison", "time"):
|
|
104
|
+
left, right = c.get(kind, frozenset()), e.get(kind, frozenset())
|
|
105
|
+
# Multiple operators need clause scope, which this guard cannot infer.
|
|
106
|
+
if len(left) == len(right) == 1 and left != right:
|
|
107
|
+
return True
|
|
108
|
+
return c.get("quantifier") == frozenset({"universal"}) and e.get("quantifier") == frozenset(
|
|
109
|
+
{"partial"}
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def conflicts(claim: Statement, evidence: tuple[Statement, ...]) -> bool:
|
|
114
|
+
"""Whether matching evidence sentences all oppose the claim.
|
|
115
|
+
|
|
116
|
+
Ties with both polarities are left to a future source-conflict policy.
|
|
117
|
+
Equality after operator removal bounds the rule to explicit mutations;
|
|
118
|
+
weaker lexical matches are not sufficient to infer contradiction. Numbers
|
|
119
|
+
remain anchors so another threshold/year cannot supply the polarity.
|
|
120
|
+
"""
|
|
121
|
+
if not claim.anchors:
|
|
122
|
+
return False
|
|
123
|
+
opposing = False
|
|
124
|
+
for candidate in evidence:
|
|
125
|
+
if candidate.anchors != claim.anchors:
|
|
126
|
+
continue
|
|
127
|
+
if not _opposes(claim, candidate):
|
|
128
|
+
return False
|
|
129
|
+
opposing = True
|
|
130
|
+
return opposing
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class PolarityGuard:
|
|
134
|
+
"""Request-local evidence parsing; no retained document data across calls."""
|
|
135
|
+
|
|
136
|
+
def __init__(self) -> None:
|
|
137
|
+
self._evidence: dict[str, tuple[Statement, ...]] = {}
|
|
138
|
+
|
|
139
|
+
def allows(self, claim: Statement, passage: Passage) -> bool:
|
|
140
|
+
if passage.id not in self._evidence:
|
|
141
|
+
# Headings still supply lexical/numeric evidence in the grounding
|
|
142
|
+
# gate, but must not supply a body's sentence polarity here.
|
|
143
|
+
self._evidence[passage.id] = tuple(
|
|
144
|
+
statement(text) for text in _SENTENCES.split(passage.text) if text.strip()
|
|
145
|
+
)
|
|
146
|
+
return not conflicts(claim, self._evidence[passage.id])
|
citebound/provenance.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""A citation hash anyone can recompute.
|
|
2
|
+
|
|
3
|
+
"This quote is characters 120 to 410 of the file whose SHA-256 is X" is a
|
|
4
|
+
claim. The hash makes it checkable without trusting the server that made it:
|
|
5
|
+
``sha256(document_sha256 | char_start | char_end | text)``. A client holding
|
|
6
|
+
those four things, in any language, can prove the quote is that exact span of
|
|
7
|
+
that exact file. The recipe is deliberately trivial so that stays true.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
|
|
14
|
+
HASH_RECIPE = "sha256(document_sha256 + '|' + char_start + '|' + char_end + '|' + text)"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def provenance_hash(document_sha256: str, char_start: int, char_end: int, text: str) -> str:
|
|
18
|
+
payload = f"{document_sha256}|{char_start}|{char_end}|{text}".encode()
|
|
19
|
+
return hashlib.sha256(payload).hexdigest()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def document_sha256(data: bytes) -> str:
|
|
23
|
+
"""The checksum of a source file, as the recipe expects it."""
|
|
24
|
+
return hashlib.sha256(data).hexdigest()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_provenance(
|
|
28
|
+
*, document_sha256: str, char_start: int, char_end: int, text: str, expected: str
|
|
29
|
+
) -> bool:
|
|
30
|
+
"""Does this passage's hash match the span it claims? Constant-time compare."""
|
|
31
|
+
actual = provenance_hash(document_sha256, char_start, char_end, text)
|
|
32
|
+
return hashlib.sha256(actual.encode()).digest() == hashlib.sha256(expected.encode()).digest()
|
citebound/py.typed
ADDED
|
File without changes
|
citebound/refusal.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Refusing is an outcome, with a code, never a guess.
|
|
2
|
+
|
|
3
|
+
Two ideas from running this in production:
|
|
4
|
+
|
|
5
|
+
* The model is told to emit one exact token, ``INSUFFICIENT_CONTEXT``, when
|
|
6
|
+
the evidence does not answer the question. :func:`is_refusal` recognises it
|
|
7
|
+
however the model decorates it (quotes, a period, a stray citation tag,
|
|
8
|
+
wrong case), as long as it is the WHOLE answer.
|
|
9
|
+
* The text shown for a refusal is generated from the reason code, never taken
|
|
10
|
+
from the model. A refusal must not carry the draft it rejected: that draft
|
|
11
|
+
is the one text the system just decided it could not stand behind.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from enum import Enum
|
|
18
|
+
|
|
19
|
+
REFUSAL_SENTINEL = "INSUFFICIENT_CONTEXT"
|
|
20
|
+
|
|
21
|
+
_TAG_RE = re.compile(r"\[(?:chunk:)?[\w-]+\]")
|
|
22
|
+
_SENTINEL_RE = re.compile(rf"^[\s\W]*{REFUSAL_SENTINEL}[\s\W]*$", re.IGNORECASE)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def is_refusal(answer: str) -> bool:
|
|
26
|
+
"""Is this answer the refusal sentinel rather than a real answer?"""
|
|
27
|
+
return bool(_SENTINEL_RE.match(_TAG_RE.sub("", answer)))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class RefusalReason(str, Enum):
|
|
31
|
+
"""Why no answer was delivered, as something a UI or a log can act on."""
|
|
32
|
+
|
|
33
|
+
INSUFFICIENT_EVIDENCE = "INSUFFICIENT_EVIDENCE" # the passages do not answer it
|
|
34
|
+
UNVERIFIABLE_ANSWER = "UNVERIFIABLE_ANSWER" # drafted, but the evidence does not support it
|
|
35
|
+
BUDGET_EXHAUSTED = "BUDGET_EXHAUSTED" # a time, token or attempt cap fired first
|
|
36
|
+
|
|
37
|
+
def __str__(self) -> str:
|
|
38
|
+
return self.value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_TEXT: dict[RefusalReason, str] = {
|
|
42
|
+
RefusalReason.INSUFFICIENT_EVIDENCE: (
|
|
43
|
+
"I couldn't find anything in the provided documents that answers this question."
|
|
44
|
+
),
|
|
45
|
+
RefusalReason.UNVERIFIABLE_ANSWER: (
|
|
46
|
+
"I found related material, but couldn't confirm an answer was fully "
|
|
47
|
+
"supported by it, so I'm not going to guess."
|
|
48
|
+
),
|
|
49
|
+
RefusalReason.BUDGET_EXHAUSTED: (
|
|
50
|
+
"This question hit the processing limit before a verified answer was "
|
|
51
|
+
"ready. Please try again."
|
|
52
|
+
),
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def refusal_text(reason: RefusalReason) -> str:
|
|
57
|
+
"""Prose that is safe to show for a reason code. No model output reaches it."""
|
|
58
|
+
return _TEXT[reason]
|
citebound/units.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Bind a figure to the unit it is quoted with.
|
|
2
|
+
|
|
3
|
+
A set of numbers cannot tell "3 days" from "3 months": both contribute the
|
|
4
|
+
token ``3``, so the numeric check accepts either against the other. This module
|
|
5
|
+
records which units a passage quotes each figure with, so a claim that keeps
|
|
6
|
+
the figure and swaps the unit stops being supported by that passage.
|
|
7
|
+
|
|
8
|
+
Conservative in the same way as the polarity guard. A passage is rejected only
|
|
9
|
+
when it quotes the claim's figure with a *different* unit and never with the
|
|
10
|
+
claim's own. A figure the passage does not quantify at all is left to the
|
|
11
|
+
numeric check, so a range ("3 to 5 days", where 3 carries no unit of its own),
|
|
12
|
+
a spelled-out figure and any unit outside the closed vocabulary below can never
|
|
13
|
+
cause a refusal here.
|
|
14
|
+
|
|
15
|
+
The vocabulary is deliberately small and closed. Counting nouns are left out:
|
|
16
|
+
"100 seats" against "100 licences" is a question about the subject of the
|
|
17
|
+
sentence, not about units, and belongs to a check that can read subjects.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import re
|
|
23
|
+
from collections.abc import Mapping
|
|
24
|
+
|
|
25
|
+
from .passages import Passage
|
|
26
|
+
|
|
27
|
+
# canonical -> the spellings that mean it. Single letters that collide with
|
|
28
|
+
# other conventions (m for million or metre, g for gram) are left out.
|
|
29
|
+
_UNIT_GROUPS: dict[str, tuple[str, ...]] = {
|
|
30
|
+
"second": ("second", "seconds", "sec", "secs"),
|
|
31
|
+
"minute": ("minute", "minutes", "min", "mins"),
|
|
32
|
+
"hour": ("hour", "hours", "hr", "hrs"),
|
|
33
|
+
"day": ("day", "days"),
|
|
34
|
+
"week": ("week", "weeks"),
|
|
35
|
+
"month": ("month", "months"),
|
|
36
|
+
"quarter": ("quarter", "quarters"),
|
|
37
|
+
"year": ("year", "years"),
|
|
38
|
+
"usd": ("usd", "dollar", "dollars", "$"),
|
|
39
|
+
"eur": ("eur", "euro", "euros", "€"),
|
|
40
|
+
# "pound" alone is left out on purpose: it is a currency in "40 pounds
|
|
41
|
+
# sterling" and a mass in "40 pounds of flour", and binding it either way
|
|
42
|
+
# makes an honest sentence collide with its own evidence.
|
|
43
|
+
"gbp": ("gbp", "£"),
|
|
44
|
+
"inr": ("inr", "rupee", "rupees", "₹"),
|
|
45
|
+
"jpy": ("jpy", "yen"),
|
|
46
|
+
"percent": ("percent", "percentage", "pct", "%"),
|
|
47
|
+
"byte": ("byte", "bytes"),
|
|
48
|
+
"kb": ("kb", "kilobyte", "kilobytes"),
|
|
49
|
+
"mb": ("mb", "megabyte", "megabytes"),
|
|
50
|
+
"gb": ("gb", "gigabyte", "gigabytes"),
|
|
51
|
+
"tb": ("tb", "terabyte", "terabytes"),
|
|
52
|
+
"kilogram": ("kg", "kilogram", "kilograms"),
|
|
53
|
+
"pound_mass": ("lb", "lbs"),
|
|
54
|
+
"kilometre": ("km", "kilometre", "kilometres", "kilometer", "kilometers"),
|
|
55
|
+
"mile": ("mile", "miles"),
|
|
56
|
+
}
|
|
57
|
+
_ALIASES: dict[str, str] = {
|
|
58
|
+
spelling: canonical for canonical, group in _UNIT_GROUPS.items() for spelling in group
|
|
59
|
+
}
|
|
60
|
+
_CURRENCIES = frozenset({"usd", "eur", "gbp", "inr", "jpy"})
|
|
61
|
+
_CURRENCY_SYMBOLS = frozenset("$€£₹")
|
|
62
|
+
|
|
63
|
+
_SYMBOLS = "%$€£₹"
|
|
64
|
+
_NUMBER = re.compile(r"\d[\d,]*(?:\.\d+)?")
|
|
65
|
+
# Only spaces and tabs are skipped, so a unit never binds across a line break,
|
|
66
|
+
# and anything that is not a word or a unit symbol ends the search.
|
|
67
|
+
_NEXT = re.compile(rf"[ \t]*([A-Za-z]+|[{_SYMBOLS}])")
|
|
68
|
+
_PREVIOUS = re.compile(rf"([A-Za-z]+|[{_SYMBOLS}])[ \t]*$")
|
|
69
|
+
# "3 business days" and "30 calendar days" must still bind; two words is enough
|
|
70
|
+
# for the qualifiers that occur in practice, and short enough that the next
|
|
71
|
+
# figure's unit cannot be captured by the figure before it.
|
|
72
|
+
_LOOKAHEAD = 2
|
|
73
|
+
_BEHIND = 16
|
|
74
|
+
|
|
75
|
+
Bindings = Mapping[str, frozenset[str]]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _normalise(number: str) -> str:
|
|
79
|
+
"""Match the numeric check: separators dropped, a trailing point ignored."""
|
|
80
|
+
return number.replace(",", "").rstrip(".")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def figures(text: str) -> dict[str, frozenset[str]]:
|
|
84
|
+
"""Every figure in ``text``, mapped to the units it is quoted with.
|
|
85
|
+
|
|
86
|
+
Only the few characters around each figure are examined, so the cost
|
|
87
|
+
follows the number of figures rather than the length of the passage.
|
|
88
|
+
"""
|
|
89
|
+
bound: dict[str, set[str]] = {}
|
|
90
|
+
for match in _NUMBER.finditer(text):
|
|
91
|
+
# Both ends, not the first that matches: "$1,720 per year" is a sum of
|
|
92
|
+
# money AND a rate per year. Recording only one of them makes the same
|
|
93
|
+
# quantity disagree with itself when the evidence words it differently.
|
|
94
|
+
units = {
|
|
95
|
+
unit
|
|
96
|
+
for unit in (
|
|
97
|
+
_unit_after(text, match.end()),
|
|
98
|
+
_currency_before(text, match.start()),
|
|
99
|
+
)
|
|
100
|
+
if unit is not None
|
|
101
|
+
}
|
|
102
|
+
if units:
|
|
103
|
+
bound.setdefault(_normalise(match.group()), set()).update(units)
|
|
104
|
+
return {number: frozenset(units) for number, units in bound.items()}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _unit_after(text: str, position: int) -> str | None:
|
|
108
|
+
"""The first unit within the lookahead, not crossing into another quantity."""
|
|
109
|
+
for _ in range(_LOOKAHEAD):
|
|
110
|
+
word = _NEXT.match(text, position)
|
|
111
|
+
if word is None:
|
|
112
|
+
return None
|
|
113
|
+
token = word.group(1)
|
|
114
|
+
# A currency symbol opens the next amount, as in "aged 55 is $1,720".
|
|
115
|
+
if token in _CURRENCY_SYMBOLS:
|
|
116
|
+
return None
|
|
117
|
+
unit = _ALIASES.get(token.lower())
|
|
118
|
+
if unit is not None:
|
|
119
|
+
return unit
|
|
120
|
+
position = word.end()
|
|
121
|
+
return None
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _currency_before(text: str, position: int) -> str | None:
|
|
125
|
+
"""A currency written in front of its amount, as in "$500" or "USD 500"."""
|
|
126
|
+
word = _PREVIOUS.search(text, max(0, position - _BEHIND), position)
|
|
127
|
+
if word is None:
|
|
128
|
+
return None
|
|
129
|
+
unit = _ALIASES.get(word.group(1).lower())
|
|
130
|
+
return unit if unit in _CURRENCIES else None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def conflicts(claim: Bindings, evidence: Bindings) -> bool:
|
|
134
|
+
"""Whether the evidence quotes one of the claim's figures with another unit."""
|
|
135
|
+
for number, units in claim.items():
|
|
136
|
+
quoted = evidence.get(number)
|
|
137
|
+
if not units or not quoted:
|
|
138
|
+
continue # the passage does not quantify this figure: not our call
|
|
139
|
+
if not units & quoted:
|
|
140
|
+
return True
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class UnitGuard:
|
|
145
|
+
"""Request-local evidence parsing; no retained document data across calls."""
|
|
146
|
+
|
|
147
|
+
def __init__(self) -> None:
|
|
148
|
+
self._evidence: dict[str, dict[str, frozenset[str]]] = {}
|
|
149
|
+
|
|
150
|
+
def allows(self, claim: Bindings, passage: Passage) -> bool:
|
|
151
|
+
if not claim: # nothing quantified: never parse the passage for nothing
|
|
152
|
+
return True
|
|
153
|
+
if passage.id not in self._evidence:
|
|
154
|
+
self._evidence[passage.id] = figures(passage.evidence)
|
|
155
|
+
return not conflicts(claim, self._evidence[passage.id])
|