-
Notifications
You must be signed in to change notification settings - Fork 63
feat(extract): ingest selection knob + keep dotted numbers intact #541
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: test
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,8 +28,11 @@ | |
|
|
||
| # Split on newlines and sentence-ending punctuation. Each match is kept as an | ||
| # exact substring of the source so its receipt verifies; only surrounding | ||
| # whitespace is stripped (the inner run stays contiguous in the source). | ||
| _SEGMENT_RE = re.compile(r"[^\n.!?]+[.!?]?") | ||
| # whitespace is stripped (the inner run stays contiguous in the source). A `.` | ||
| # flanked by digits is a decimal/version dot ("6.8.3", "3.14"), never a | ||
| # sentence boundary — keep it inside the span so the number-valued fact isn't | ||
| # fractured out of every claim. | ||
| _SEGMENT_RE = re.compile(r"(?:[^\n.!?]|(?<=\d)\.(?=\d))+[.!?]?") | ||
|
|
||
| DEFAULT_MIN_CHARS = 16 | ||
| DEFAULT_MAX_CHARS = 320 | ||
|
|
@@ -44,6 +47,79 @@ def _is_noise(segment: str) -> bool: | |
| return letters < len(segment) * _MIN_LETTER_RATIO | ||
|
|
||
|
|
||
| # Words that carry no fact: a span made mostly of them is filler, not | ||
| # knowledge. Kept local (not imported from synthesize) so the ingest hot path | ||
| # stays clear of the synthesis/LLM import chain. | ||
| _STOPWORDS = frozenset( | ||
| { | ||
| "a", "an", "and", "are", "as", "at", "be", "by", "do", "does", "for", | ||
| "from", "how", "in", "into", "is", "it", "its", "of", "on", "or", | ||
| "that", "the", "their", "them", "then", "there", "these", "this", "to", | ||
| "was", "were", "what", "when", "where", "which", "who", "why", "will", | ||
| "with", "you", "your", | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def _content_words(span: str) -> list[str]: | ||
| """Lowercased alphanumeric tokens of ``span`` minus short words/stopwords.""" | ||
| words: list[str] = [] | ||
| for raw in span.split(): | ||
| token = "".join(ch for ch in raw.lower() if ch.isalnum()) | ||
| if len(token) < 3 or token in _STOPWORDS: | ||
| continue | ||
| words.append(token) | ||
| return words | ||
|
|
||
|
|
||
| def _span_score(span: str, doc_freq: dict[str, int]) -> float: | ||
| """Information density of ``span``: sum over its distinct content words of | ||
| ``1 / document-frequency``. A word repeated across many spans is less | ||
| discriminating, so it counts for less; a rare, specific term counts for | ||
| more. Stopword-heavy filler scores near zero. | ||
| """ | ||
| return sum(1.0 / doc_freq.get(word, 1) for word in set(_content_words(span))) | ||
|
|
||
|
|
||
| def select_spans( | ||
| segments: list[str], | ||
| *, | ||
| max_claims: int | None = None, | ||
| budget_chars: int | None = None, | ||
| ) -> list[str]: | ||
| """Keep the most information-dense spans under a budget, in source order. | ||
|
|
||
| Ranking is deterministic and llm-free (see ``_span_score``): fact-dense | ||
| sentences outrank stopword-heavy filler. With no budget the input is | ||
| returned unchanged — the unbudgeted baseline that captures every span. | ||
| Selection only ever returns a *subset* of ``segments``, never a rewrite, so | ||
| every kept span is still a verbatim substring of the source and its receipt | ||
| still verifies by construction. | ||
| """ | ||
| if max_claims is None and budget_chars is None: | ||
| return segments | ||
| doc_freq: dict[str, int] = {} | ||
| for seg in segments: | ||
| for word in set(_content_words(seg)): | ||
| doc_freq[word] = doc_freq.get(word, 0) + 1 | ||
| # Rank by score (desc), ties broken by original position for determinism. | ||
| ranked = sorted( | ||
| range(len(segments)), | ||
| key=lambda i: (-_span_score(segments[i], doc_freq), i), | ||
| ) | ||
| kept: list[int] = [] | ||
| used = 0 | ||
| for i in ranked: | ||
| if max_claims is not None and len(kept) >= max_claims: | ||
| break | ||
| length = len(segments[i]) | ||
| if budget_chars is not None and used + length > budget_chars: | ||
| continue | ||
| kept.append(i) | ||
| used += length | ||
| return [segments[i] for i in sorted(kept)] | ||
|
Comment on lines
+99
to
+120
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win 🧩 Analysis chain🌐 Web query:
💡 Result: Yes, the Click library supports Citations:
🏁 Script executed: #!/bin/bash
set -euo pipefail
printf '--- src/vouch/extract.py (relevant section) ---\n'
sed -n '1,220p' src/vouch/extract.py
printf '\n--- src/vouch/cli.py (relevant option section) ---\n'
sed -n '1720,1785p' src/vouch/cli.py
printf '\n--- tests/test_extract.py (relevant tests) ---\n'
sed -n '1,260p' tests/test_extract.py
printf '\n--- search for select_spans usages ---\n'
rg -n "select_spans\(" -S src testsRepository: vouchdev/vouch Length of output: 243 🏁 Script executed: #!/bin/bash
set -euo pipefail
python3 - <<'PY'
from pathlib import Path
p = Path('src/vouch/extract.py')
print('extract.py lines', sum(1 for _ in p.open()))
p = Path('src/vouch/cli.py')
print('cli.py lines', sum(1 for _ in p.open()))
p = Path('tests/test_extract.py')
print('test_extract.py lines', sum(1 for _ in p.open()))
PYRepository: vouchdev/vouch Length of output: 217 🏁 Script executed: #!/bin/bash
set -euo pipefail
# Probe runtime semantics only if click is importable in the sandbox.
python3 - <<'PY'
try:
import click
except Exception as e:
print(f'click import failed: {e}')
raise SystemExit(0)
opt = click.Option(['--n'], type=click.IntRange(min=0), default=None)
ctx = click.Context(click.Command('cmd', params=[opt]))
def parse(args):
try:
return opt.consume_value(ctx, opt.process_value(ctx, args))
except Exception as e:
return type(e).__name__, str(e)
print('click', click.__version__)
print('type', type(opt.type).__name__)
for value in [None, 0, 3, -1]:
try:
rv = opt.type.convert(value, opt, ctx) if value is not None else None
print(value, '=>', rv)
except Exception as e:
print(value, '=>', type(e).__name__, e)
PYRepository: vouchdev/vouch Length of output: 433 🏁 Script executed: #!/bin/bash
set -euo pipefail
echo '--- src/vouch/extract.py (relevant section) ---'
sed -n '70,140p' src/vouch/extract.py
echo
echo '--- src/vouch/cli.py (relevant option section) ---'
sed -n '1748,1778p' src/vouch/cli.py
echo
echo '--- tests/test_extract.py (relevant tests) ---'
sed -n '96,190p' tests/test_extract.py
echo
echo '--- direct usage search ---'
rg -n "select_spans\(" src tests -SRepository: vouchdev/vouch Length of output: 8672 reject negative selection budgets.
📍 Affects 3 files
🤖 Prompt for AI Agents |
||
|
|
||
|
|
||
| def segment_source( | ||
| text: str, | ||
| *, | ||
|
|
@@ -75,17 +151,28 @@ def extract_receipt_claims( | |
| *, | ||
| proposed_by: str, | ||
| limit: int | None = None, | ||
| max_claims: int | None = None, | ||
| budget_chars: int | None = None, | ||
| ) -> list[ProposeClaimResult]: | ||
| """File a receipt-backed claim for each quotable span in ``source_id``. | ||
|
|
||
| Each segment becomes a claim that quotes itself verbatim, so its receipt | ||
| verifies by construction. A segment that (defensively) fails the verbatim | ||
| check — e.g. non-UTF-8 bytes mangled on decode — is dropped by | ||
| ``propose_quoted_claim``. Returns the proposals actually filed. | ||
|
|
||
| ``max_claims``/``budget_chars`` turn on density selection (``select_spans``): | ||
| only the most informative spans are filed, so ingest keeps the facts worth a | ||
| claim and drops filler instead of restating the whole document. ``limit`` is | ||
| the older positional cap (first-N in document order, used by session-answer | ||
| capture) and still applies after selection. | ||
| """ | ||
| text = store.read_source_content(source_id).decode("utf-8", errors="replace") | ||
| spans = segment_source(text) | ||
| if max_claims is not None or budget_chars is not None: | ||
| spans = select_spans(spans, max_claims=max_claims, budget_chars=budget_chars) | ||
| filed: list[ProposeClaimResult] = [] | ||
| for segment in segment_source(text): | ||
| for segment in spans: | ||
| if limit is not None and len(filed) >= limit: | ||
| break | ||
| result = propose_quoted_claim( | ||
|
|
@@ -104,6 +191,8 @@ def ingest_source( | |
| proposed_by: str, | ||
| title: str | None = None, | ||
| auto_approve: bool = True, | ||
| max_claims: int | None = None, | ||
| budget_chars: int | None = None, | ||
| ) -> tuple[Source, list[Claim]]: | ||
| """Run the whole capture loop on a document, no human in the loop. | ||
|
|
||
|
|
@@ -112,8 +201,14 @@ def ingest_source( | |
| approve every one whose receipt verifies. Returns the source and the claims | ||
| that became durable. With the gate off the claims are filed but left pending | ||
| for a human — the review gate is never silently bypassed. | ||
|
|
||
| ``max_claims``/``budget_chars`` bound the capture to the most informative | ||
| spans (see ``extract_receipt_claims``); unset, every quotable span is kept. | ||
| """ | ||
| source = store.put_source(content, title=title, scope=default_scope(store)) | ||
| extract_receipt_claims(store, source.id, proposed_by=proposed_by) | ||
| extract_receipt_claims( | ||
| store, source.id, proposed_by=proposed_by, | ||
| max_claims=max_claims, budget_chars=budget_chars, | ||
| ) | ||
| approved = auto_approve_receipts(store) if auto_approve else [] | ||
| return source, approved | ||
Uh oh!
There was an error while loading. Please reload this page.