probative 0.1.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.
- probative/__init__.py +14 -0
- probative/agents/__init__.py +1 -0
- probative/cli.py +167 -0
- probative/config.py +76 -0
- probative/core/__init__.py +1 -0
- probative/core/candidates.py +165 -0
- probative/core/critic.py +113 -0
- probative/core/evidence.py +158 -0
- probative/critics/__init__.py +26 -0
- probative/critics/base.py +66 -0
- probative/critics/constraint_critic.py +434 -0
- probative/critics/dependency_critic.py +132 -0
- probative/critics/evidence_auditor.py +127 -0
- probative/critics/invest.py +62 -0
- probative/critics/llm_judge.py +530 -0
- probative/critics/red_team.py +127 -0
- probative/critics/rubric.py +46 -0
- probative/critics/rubrics/constraint_critic/rubric.yaml +42 -0
- probative/critics/rubrics/dependency_critic/rubric.yaml +31 -0
- probative/critics/rubrics/evidence_auditor/rubric.yaml +74 -0
- probative/critics/rubrics/invest/rubric.yaml +67 -0
- probative/critics/rubrics/red_team/rubric.yaml +119 -0
- probative/critics/rubrics/segment_skeptic/rubric.yaml +47 -0
- probative/critics/rubrics/space_warden/rubric.yaml +24 -0
- probative/critics/runner.py +34 -0
- probative/critics/scoring.py +50 -0
- probative/critics/segment_skeptic.py +125 -0
- probative/critics/space_warden.py +57 -0
- probative/critics/testing.py +46 -0
- probative/critique/__init__.py +65 -0
- probative/critique/pipeline.py +374 -0
- probative/critique/report.py +230 -0
- probative/critique/roster.py +103 -0
- probative/critique/scoring.py +94 -0
- probative/critique/sources.py +198 -0
- probative/critique/verify.py +141 -0
- probative/exporters/__init__.py +1 -0
- probative/extract/__init__.py +33 -0
- probative/extract/chunking.py +47 -0
- probative/extract/pipeline.py +182 -0
- probative/extract/prompts.py +183 -0
- probative/extract/resolve.py +85 -0
- probative/extract/scoring.py +156 -0
- probative/formulas/__init__.py +1 -0
- probative/graph_runtime/__init__.py +1 -0
- probative/ingest/__init__.py +144 -0
- probative/ingest/_extracted.py +18 -0
- probative/ingest/_html.py +27 -0
- probative/ingest/_lines.py +41 -0
- probative/ingest/_tracker_text.py +71 -0
- probative/ingest/_wiki.py +30 -0
- probative/ingest/ado_csv.py +74 -0
- probative/ingest/confluence.py +91 -0
- probative/ingest/confluence_word.py +128 -0
- probative/ingest/csv_.py +50 -0
- probative/ingest/docx_.py +66 -0
- probative/ingest/jira_csv.py +76 -0
- probative/ingest/jira_html.py +116 -0
- probative/ingest/jira_xml.py +94 -0
- probative/ingest/markdown.py +70 -0
- probative/ingest/pdf.py +76 -0
- probative/ingest/text.py +20 -0
- probative/ingest/tracker.py +158 -0
- probative/ingest/xlsx.py +61 -0
- probative/interfaces/__init__.py +1 -0
- probative/interfaces/doctor.py +189 -0
- probative/interfaces/mcp_server.py +487 -0
- probative/llm/__init__.py +21 -0
- probative/llm/factory.py +85 -0
- probative/llm/fake.py +47 -0
- probative/llm/litellm_provider.py +86 -0
- probative/llm/provider.py +34 -0
- probative/llm/structured.py +38 -0
- probative/llm/types.py +51 -0
- probative/render/__init__.py +1 -0
- probative/render/_view.py +125 -0
- probative/render/design.py +63 -0
- probative/render/html.py +256 -0
- probative/render/markdown.py +122 -0
- probative-0.1.0.dist-info/METADATA +143 -0
- probative-0.1.0.dist-info/RECORD +84 -0
- probative-0.1.0.dist-info/WHEEL +4 -0
- probative-0.1.0.dist-info/entry_points.txt +2 -0
- probative-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Precision and recall of an extraction against hand-labelled gold.
|
|
2
|
+
|
|
3
|
+
Pure functions. These are eval metrics, not node fields, so they sit outside
|
|
4
|
+
the I4 formula registry (PB11); PB32's eval harness may absorb them.
|
|
5
|
+
|
|
6
|
+
A predicted span matches a gold span of the same kind when their character
|
|
7
|
+
IoU is at least 0.5, one-to-one, greedily by highest IoU. Precision is `None`
|
|
8
|
+
when nothing was predicted and recall `None` when nothing was labelled — an
|
|
9
|
+
undefined ratio is reported as undefined, not as a flattering 1.0.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
from collections.abc import Sequence
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from pydantic import BaseModel
|
|
19
|
+
|
|
20
|
+
from probative.core.candidates import (
|
|
21
|
+
Candidate,
|
|
22
|
+
CandidateKind,
|
|
23
|
+
ClaimCandidate,
|
|
24
|
+
ConstraintCandidate,
|
|
25
|
+
DependencyCandidate,
|
|
26
|
+
ForecastCandidate,
|
|
27
|
+
NeedCandidate,
|
|
28
|
+
RejectReason,
|
|
29
|
+
SegmentCandidate,
|
|
30
|
+
StoryCandidate,
|
|
31
|
+
candidate_id,
|
|
32
|
+
)
|
|
33
|
+
from probative.core.evidence import EvidenceSpan, Source
|
|
34
|
+
from probative.extract.resolve import occurrences, resolve_quote
|
|
35
|
+
|
|
36
|
+
IOU_THRESHOLD = 0.5
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class KindScore(BaseModel):
|
|
40
|
+
tp: int
|
|
41
|
+
fp: int
|
|
42
|
+
fn: int
|
|
43
|
+
precision: float | None
|
|
44
|
+
recall: float | None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ExtractionScore(BaseModel):
|
|
48
|
+
per_kind: dict[CandidateKind, KindScore]
|
|
49
|
+
overall: KindScore
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class GoldLabel(BaseModel):
|
|
53
|
+
kind: CandidateKind
|
|
54
|
+
quote: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class GoldLabelError(Exception):
|
|
58
|
+
"""A hand label does not resolve to exactly one place in its document."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _iou(a: Candidate, b: Candidate) -> float:
|
|
62
|
+
if a.evidence.source_id != b.evidence.source_id:
|
|
63
|
+
return 0.0
|
|
64
|
+
overlap = min(a.evidence.end, b.evidence.end) - max(a.evidence.start, b.evidence.start)
|
|
65
|
+
if overlap <= 0:
|
|
66
|
+
return 0.0
|
|
67
|
+
union = (a.evidence.end - a.evidence.start) + (b.evidence.end - b.evidence.start) - overlap
|
|
68
|
+
return overlap / union
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _kind_score(tp: int, fp: int, fn: int) -> KindScore:
|
|
72
|
+
return KindScore(
|
|
73
|
+
tp=tp,
|
|
74
|
+
fp=fp,
|
|
75
|
+
fn=fn,
|
|
76
|
+
precision=tp / (tp + fp) if tp + fp else None,
|
|
77
|
+
recall=tp / (tp + fn) if tp + fn else None,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _match_count(predicted: list[Candidate], gold: list[Candidate]) -> int:
|
|
82
|
+
pairs = sorted(
|
|
83
|
+
(
|
|
84
|
+
(-iou, p, g)
|
|
85
|
+
for p, pred in enumerate(predicted)
|
|
86
|
+
for g, gold_item in enumerate(gold)
|
|
87
|
+
if (iou := _iou(pred, gold_item)) >= IOU_THRESHOLD
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
used_pred: set[int] = set()
|
|
91
|
+
used_gold: set[int] = set()
|
|
92
|
+
for _, p, g in pairs:
|
|
93
|
+
if p not in used_pred and g not in used_gold:
|
|
94
|
+
used_pred.add(p)
|
|
95
|
+
used_gold.add(g)
|
|
96
|
+
return len(used_pred)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def score_extraction(predicted: Sequence[Candidate], gold: Sequence[Candidate]) -> ExtractionScore:
|
|
100
|
+
per_kind: dict[CandidateKind, KindScore] = {}
|
|
101
|
+
total_tp = total_fp = total_fn = 0
|
|
102
|
+
for kind in CandidateKind:
|
|
103
|
+
pred_k = [c for c in predicted if c.kind is kind]
|
|
104
|
+
gold_k = [c for c in gold if c.kind is kind]
|
|
105
|
+
tp = _match_count(pred_k, gold_k)
|
|
106
|
+
fp, fn = len(pred_k) - tp, len(gold_k) - tp
|
|
107
|
+
per_kind[kind] = _kind_score(tp, fp, fn)
|
|
108
|
+
total_tp, total_fp, total_fn = total_tp + tp, total_fp + fp, total_fn + fn
|
|
109
|
+
return ExtractionScore(per_kind=per_kind, overall=_kind_score(total_tp, total_fp, total_fn))
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def gold_candidates(source: Source, labels: Sequence[GoldLabel]) -> list[Candidate]:
|
|
113
|
+
"""Resolve hand labels (quotes) to candidates through the same resolver
|
|
114
|
+
the pipeline uses. A label must resolve to exactly one place — judged
|
|
115
|
+
loosely (whitespace-tolerant), so a near-duplicate elsewhere counts — and
|
|
116
|
+
no two labels of a kind may resolve to the same span."""
|
|
117
|
+
out: list[Candidate] = []
|
|
118
|
+
seen: set[tuple[CandidateKind, int, int]] = set()
|
|
119
|
+
window = (0, len(source.text))
|
|
120
|
+
for label in labels:
|
|
121
|
+
resolved = resolve_quote(
|
|
122
|
+
source, label.quote, window=window, claimed=set(), max_quote_chars=10_000
|
|
123
|
+
)
|
|
124
|
+
if isinstance(resolved, RejectReason):
|
|
125
|
+
raise GoldLabelError(f"gold quote not resolvable ({resolved.value}): {label.quote!r}")
|
|
126
|
+
if len(occurrences(source.text, label.quote.strip(), window, loose_only=True)) != 1:
|
|
127
|
+
raise GoldLabelError(f"gold quote is not unique in its document: {label.quote!r}")
|
|
128
|
+
key = (label.kind, resolved.start, resolved.end)
|
|
129
|
+
if key in seen:
|
|
130
|
+
raise GoldLabelError(f"duplicate gold label: {label.quote!r}")
|
|
131
|
+
seen.add(key)
|
|
132
|
+
out.append(_make(label.kind, resolved))
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _make(kind: CandidateKind, span: EvidenceSpan) -> Candidate:
|
|
137
|
+
cid = candidate_id(kind, span)
|
|
138
|
+
match kind:
|
|
139
|
+
case CandidateKind.CLAIM:
|
|
140
|
+
return ClaimCandidate(id=cid, evidence=span)
|
|
141
|
+
case CandidateKind.NEED:
|
|
142
|
+
return NeedCandidate(id=cid, evidence=span)
|
|
143
|
+
case CandidateKind.STORY:
|
|
144
|
+
return StoryCandidate(id=cid, evidence=span)
|
|
145
|
+
case CandidateKind.CONSTRAINT:
|
|
146
|
+
return ConstraintCandidate(id=cid, evidence=span)
|
|
147
|
+
case CandidateKind.DEPENDENCY:
|
|
148
|
+
return DependencyCandidate(id=cid, evidence=span)
|
|
149
|
+
case CandidateKind.SEGMENT:
|
|
150
|
+
return SegmentCandidate(id=cid, evidence=span)
|
|
151
|
+
case CandidateKind.FORECAST:
|
|
152
|
+
return ForecastCandidate(id=cid, evidence=span)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def load_gold_labels(path: Path) -> list[GoldLabel]:
|
|
156
|
+
return [GoldLabel.model_validate(raw) for raw in json.loads(path.read_text())]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Registered pure functions. Every numeric field points here (I4). mypy strict."""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Phase machine, Committer, gates and budgets."""
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Turn a folder of ordinary documents into `Source` and `EvidenceSpan`
|
|
2
|
+
records whose offsets survive re-extraction (PROBATIVE_PHASE_SPECS.md, PB1).
|
|
3
|
+
|
|
4
|
+
Public API: `ingest`, `spans`, `reextract`. Everything else in this package
|
|
5
|
+
is per-format extraction plumbing.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
from bisect import bisect_right
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from probative.core.evidence import CorruptSourceError as CorruptSourceError
|
|
16
|
+
from probative.core.evidence import (
|
|
17
|
+
EmptySourceError,
|
|
18
|
+
EvidenceKind,
|
|
19
|
+
EvidenceSpan,
|
|
20
|
+
Locator,
|
|
21
|
+
LocatorRegion,
|
|
22
|
+
Source,
|
|
23
|
+
SourceFormat,
|
|
24
|
+
SpanOutOfRangeError,
|
|
25
|
+
StaleNormalizationError,
|
|
26
|
+
Tier,
|
|
27
|
+
UnsupportedFormatError,
|
|
28
|
+
)
|
|
29
|
+
from probative.ingest import csv_, docx_, markdown, pdf, text, xlsx
|
|
30
|
+
from probative.ingest._extracted import ExtractedDocument
|
|
31
|
+
|
|
32
|
+
__all__ = ["ingest", "reextract", "spans"]
|
|
33
|
+
|
|
34
|
+
_EXTENSION_FORMAT: dict[str, SourceFormat] = {
|
|
35
|
+
".pdf": SourceFormat.PDF,
|
|
36
|
+
".docx": SourceFormat.DOCX,
|
|
37
|
+
".xlsx": SourceFormat.XLSX,
|
|
38
|
+
".csv": SourceFormat.CSV,
|
|
39
|
+
".md": SourceFormat.MARKDOWN,
|
|
40
|
+
".markdown": SourceFormat.MARKDOWN,
|
|
41
|
+
".txt": SourceFormat.TEXT,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
_EXTRACTORS = {
|
|
45
|
+
SourceFormat.PDF: pdf.extract,
|
|
46
|
+
SourceFormat.DOCX: docx_.extract,
|
|
47
|
+
SourceFormat.XLSX: xlsx.extract,
|
|
48
|
+
SourceFormat.CSV: csv_.extract,
|
|
49
|
+
SourceFormat.MARKDOWN: markdown.extract,
|
|
50
|
+
SourceFormat.TEXT: text.extract,
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _detect_format(path: Path) -> SourceFormat:
|
|
55
|
+
fmt = _EXTENSION_FORMAT.get(path.suffix.lower())
|
|
56
|
+
if fmt is None:
|
|
57
|
+
raise UnsupportedFormatError(path, f"unrecognised extension {path.suffix!r}")
|
|
58
|
+
return fmt
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _extract(path: Path, fmt: SourceFormat) -> ExtractedDocument:
|
|
62
|
+
return _EXTRACTORS[fmt](path)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def ingest(path: Path, *, tier: Tier, kind: EvidenceKind) -> Source:
|
|
66
|
+
"""Ingest one file, producing a `Source` whose `id`/`sha256` are pure
|
|
67
|
+
functions of its bytes — re-ingesting the same file is idempotent."""
|
|
68
|
+
raw = path.read_bytes()
|
|
69
|
+
if len(raw) == 0:
|
|
70
|
+
raise EmptySourceError(path, "file is empty")
|
|
71
|
+
sha256 = hashlib.sha256(raw).hexdigest()
|
|
72
|
+
fmt = _detect_format(path)
|
|
73
|
+
doc = _extract(path, fmt)
|
|
74
|
+
return Source(
|
|
75
|
+
id=f"src_{sha256[:16]}",
|
|
76
|
+
path=path,
|
|
77
|
+
sha256=sha256,
|
|
78
|
+
format=fmt,
|
|
79
|
+
tier=tier,
|
|
80
|
+
kind=kind,
|
|
81
|
+
ingested_at=datetime.now(UTC),
|
|
82
|
+
extractor=f"probative.ingest.{fmt.value}",
|
|
83
|
+
extractor_version=doc.normalization_version,
|
|
84
|
+
text=doc.text,
|
|
85
|
+
locator_regions=doc.locator_regions,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _locator_for(regions: list[LocatorRegion], offset: int) -> Locator:
|
|
90
|
+
starts = [r.start for r in regions]
|
|
91
|
+
idx = bisect_right(starts, offset) - 1
|
|
92
|
+
if idx < 0 or not (regions[idx].start <= offset < regions[idx].end):
|
|
93
|
+
raise AssertionError(f"locator_regions do not cover offset {offset} — extractor bug")
|
|
94
|
+
return regions[idx].locator
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def spans(source: Source, ranges: list[tuple[int, int]]) -> list[EvidenceSpan]:
|
|
98
|
+
"""Take spans at `ranges` (character offsets into `source.text`).
|
|
99
|
+
|
|
100
|
+
A range that straddles two locator regions is located by its first
|
|
101
|
+
character — offsets are the source of truth for provenance; the
|
|
102
|
+
locator is a best-effort human aid.
|
|
103
|
+
"""
|
|
104
|
+
result = []
|
|
105
|
+
for start, end in ranges:
|
|
106
|
+
if not (0 <= start < end <= len(source.text)):
|
|
107
|
+
raise SpanOutOfRangeError(
|
|
108
|
+
source.path,
|
|
109
|
+
f"range ({start}, {end}) invalid for text of length {len(source.text)}",
|
|
110
|
+
)
|
|
111
|
+
locator = _locator_for(source.locator_regions, start)
|
|
112
|
+
result.append(
|
|
113
|
+
EvidenceSpan(
|
|
114
|
+
source_id=source.id,
|
|
115
|
+
start=start,
|
|
116
|
+
end=end,
|
|
117
|
+
text=source.text[start:end],
|
|
118
|
+
locator=locator,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def reextract(source: Source, span: EvidenceSpan) -> str:
|
|
125
|
+
"""Re-run extraction on `source.path` and slice at the span's offsets.
|
|
126
|
+
|
|
127
|
+
Raises `StaleNormalizationError` if the normalisation algorithm has
|
|
128
|
+
changed since `source` was ingested (its offsets are not guaranteed
|
|
129
|
+
valid any more), and `CorruptSourceError` if the file's bytes have
|
|
130
|
+
changed on disk since ingestion.
|
|
131
|
+
"""
|
|
132
|
+
if span.source_id != source.id:
|
|
133
|
+
raise ValueError(f"span belongs to source {span.source_id!r}, not {source.id!r}")
|
|
134
|
+
fresh = ingest(source.path, tier=source.tier, kind=source.kind)
|
|
135
|
+
if fresh.extractor_version != source.extractor_version:
|
|
136
|
+
raise StaleNormalizationError(
|
|
137
|
+
source.path,
|
|
138
|
+
f"normalisation changed ({source.extractor_version} -> "
|
|
139
|
+
f"{fresh.extractor_version}); offsets recorded against the old "
|
|
140
|
+
f"version are not guaranteed valid",
|
|
141
|
+
)
|
|
142
|
+
if fresh.sha256 != source.sha256:
|
|
143
|
+
raise CorruptSourceError(source.path, "file contents changed since ingestion")
|
|
144
|
+
return fresh.text[span.start : span.end]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Internal extraction-pipeline shape — not part of the public evidence model.
|
|
2
|
+
|
|
3
|
+
Each per-format module returns one of these; `probative.ingest.ingest`
|
|
4
|
+
turns it into a `Source`.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
from probative.core.evidence import LocatorRegion
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class ExtractedDocument:
|
|
16
|
+
text: str
|
|
17
|
+
locator_regions: list[LocatorRegion]
|
|
18
|
+
normalization_version: str
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Generic HTML -> plain text (used by ado_csv's rich-text Description and
|
|
2
|
+
jira_xml's rendered-HTML description — as opposed to jira_csv/jira_html,
|
|
3
|
+
which carry wiki markup and go through `probative.ingest._wiki` instead).
|
|
4
|
+
|
|
5
|
+
Block-level tags become line breaks, everything else is stripped, and
|
|
6
|
+
entities are unescaped. No attempt at layout fidelity (tables, nested
|
|
7
|
+
lists) — this is a normalisation for evidence text, not a renderer.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import html
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
_BLOCK_BREAK_RE = re.compile(r"</?(?:br|p|div|li|ol|ul|h[1-6]|tr|table)\b[^>]*>", re.IGNORECASE)
|
|
16
|
+
_TAG_RE = re.compile(r"<[^>]+>")
|
|
17
|
+
_BLANK_RUN_RE = re.compile(r"\n{3,}")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def to_text(markup: str) -> str:
|
|
21
|
+
"""Best-effort normalisation of an HTML fragment to plain text."""
|
|
22
|
+
text = _BLOCK_BREAK_RE.sub("\n", markup)
|
|
23
|
+
text = _TAG_RE.sub("", text)
|
|
24
|
+
text = html.unescape(text)
|
|
25
|
+
text = "\n".join(line.strip() for line in text.split("\n"))
|
|
26
|
+
text = _BLANK_RUN_RE.sub("\n\n", text)
|
|
27
|
+
return text.strip("\n")
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Shared line-splitting helper for the line-oriented formats (text, CSV,
|
|
2
|
+
Markdown): decode, normalise line endings, and build one LocatorRegion per
|
|
3
|
+
physical line without losing any characters (offsets must stay exact)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from probative.core.evidence import CorruptSourceError, Locator, LocatorRegion
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def decode_and_normalize_endings(path: Path) -> str:
|
|
14
|
+
"""Decode UTF-8 (tolerating a leading BOM) and normalise CRLF/CR to LF."""
|
|
15
|
+
raw = path.read_bytes()
|
|
16
|
+
try:
|
|
17
|
+
text = raw.decode("utf-8-sig")
|
|
18
|
+
except UnicodeDecodeError as exc:
|
|
19
|
+
raise CorruptSourceError(path, f"not valid UTF-8: {exc}") from exc
|
|
20
|
+
return text.replace("\r\n", "\n").replace("\r", "\n")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def split_keepends(text: str) -> list[str]:
|
|
24
|
+
"""Split into physical lines, each carrying its own trailing "\\n"
|
|
25
|
+
(the last line may lack one) — so ''.join(lines) == text exactly."""
|
|
26
|
+
return text.splitlines(keepends=True)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def line_regions(
|
|
30
|
+
lines: list[str], locator_for_line: Callable[[int, str], Locator]
|
|
31
|
+
) -> list[LocatorRegion]:
|
|
32
|
+
"""Build one LocatorRegion per line in `lines`, given a callable
|
|
33
|
+
`locator_for_line(1_indexed_line_number, line_text) -> Locator`."""
|
|
34
|
+
regions: list[LocatorRegion] = []
|
|
35
|
+
offset = 0
|
|
36
|
+
for i, line in enumerate(lines, start=1):
|
|
37
|
+
start = offset
|
|
38
|
+
end = offset + len(line)
|
|
39
|
+
regions.append(LocatorRegion(start=start, end=end, locator=locator_for_line(i, line)))
|
|
40
|
+
offset = end
|
|
41
|
+
return regions
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""Shared normalised-text assembly for the four PB2 tracker extractors.
|
|
2
|
+
|
|
3
|
+
Every extractor writes one block per issue: a `field="header"` line
|
|
4
|
+
(`key\\ttype\\tstatus\\tparent_key`) followed by exactly-bounded regions for
|
|
5
|
+
`summary`, and — only when present — `description` and
|
|
6
|
+
`acceptance_criteria`. Region boundaries match field content exactly (no
|
|
7
|
+
trimming needed downstream); the blank-line padding between fields gets
|
|
8
|
+
its own untagged region purely to keep `LocatorRegion`'s "no gaps" cover
|
|
9
|
+
invariant intact.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from probative.core.evidence import Locator, LocatorRegion
|
|
15
|
+
from probative.ingest._extracted import ExtractedDocument
|
|
16
|
+
|
|
17
|
+
HEADER_FIELD = "header"
|
|
18
|
+
SUMMARY_FIELD = "summary"
|
|
19
|
+
DESCRIPTION_FIELD = "description"
|
|
20
|
+
ACCEPTANCE_CRITERIA_FIELD = "acceptance_criteria"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TrackerTextBuilder:
|
|
24
|
+
"""Accumulates one Source's worth of issue blocks."""
|
|
25
|
+
|
|
26
|
+
def __init__(self) -> None:
|
|
27
|
+
self._parts: list[str] = []
|
|
28
|
+
self._regions: list[LocatorRegion] = []
|
|
29
|
+
self._offset = 0
|
|
30
|
+
|
|
31
|
+
def _write(self, content: str, *, issue_key: str | None, field: str | None) -> None:
|
|
32
|
+
start = self._offset
|
|
33
|
+
self._parts.append(content)
|
|
34
|
+
self._offset += len(content)
|
|
35
|
+
self._regions.append(
|
|
36
|
+
LocatorRegion(
|
|
37
|
+
start=start,
|
|
38
|
+
end=self._offset,
|
|
39
|
+
locator=Locator(issue_key=issue_key, field=field),
|
|
40
|
+
)
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
def add_issue(
|
|
44
|
+
self,
|
|
45
|
+
*,
|
|
46
|
+
key: str,
|
|
47
|
+
type_: str,
|
|
48
|
+
status: str,
|
|
49
|
+
parent_key: str | None,
|
|
50
|
+
summary: str,
|
|
51
|
+
description: str | None,
|
|
52
|
+
acceptance_criteria: str | None,
|
|
53
|
+
) -> None:
|
|
54
|
+
header = f"{key}\t{type_}\t{status}\t{parent_key or ''}\n"
|
|
55
|
+
self._write(header, issue_key=key, field=HEADER_FIELD)
|
|
56
|
+
self._write(summary, issue_key=key, field=SUMMARY_FIELD)
|
|
57
|
+
self._write("\n\n", issue_key=key, field=None)
|
|
58
|
+
if description:
|
|
59
|
+
self._write(description, issue_key=key, field=DESCRIPTION_FIELD)
|
|
60
|
+
self._write("\n\n", issue_key=key, field=None)
|
|
61
|
+
if acceptance_criteria:
|
|
62
|
+
self._write(acceptance_criteria, issue_key=key, field=ACCEPTANCE_CRITERIA_FIELD)
|
|
63
|
+
self._write("\n\n", issue_key=key, field=None)
|
|
64
|
+
self._write("---\n", issue_key=None, field=None)
|
|
65
|
+
|
|
66
|
+
def build(self, normalization_version: str) -> ExtractedDocument:
|
|
67
|
+
return ExtractedDocument(
|
|
68
|
+
text="".join(self._parts),
|
|
69
|
+
locator_regions=self._regions,
|
|
70
|
+
normalization_version=normalization_version,
|
|
71
|
+
)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Jira wiki-markup -> plain text (used by jira_csv and, after its own
|
|
2
|
+
<br/> substitution, jira_html — both export description/comment bodies in
|
|
3
|
+
wiki markup rather than real HTML).
|
|
4
|
+
|
|
5
|
+
v1 scope, deliberately narrow (mirrors PB1's documented-gap approach):
|
|
6
|
+
list-item leaders, the common emphasis markers, image macros, links and
|
|
7
|
+
account mentions. Anything else (tables, panels, nested macros) passes
|
|
8
|
+
through verbatim rather than being silently mangled.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import re
|
|
14
|
+
|
|
15
|
+
_LIST_LEADER_RE = re.compile(r"^[ \t]*[#*]+[ \t]+", re.MULTILINE)
|
|
16
|
+
_EMPHASIS_RE = re.compile(r"(?<![\w\\])([*_+^~-])(?=\S)(.*?)(?<=\S)\1(?![\w\\])")
|
|
17
|
+
_IMAGE_MACRO_RE = re.compile(r"!([^!\n]+)!")
|
|
18
|
+
_LINK_RE = re.compile(r"\[([^\]|\n]+)\|[^\]\n]*\]")
|
|
19
|
+
_MENTION_RE = re.compile(r"\[~[^\]\n]*\]")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def to_text(markup: str) -> str:
|
|
23
|
+
"""Best-effort normalisation of Jira wiki markup to plain text."""
|
|
24
|
+
text = markup
|
|
25
|
+
text = _MENTION_RE.sub("", text)
|
|
26
|
+
text = _IMAGE_MACRO_RE.sub("", text)
|
|
27
|
+
text = _LINK_RE.sub(r"\1", text)
|
|
28
|
+
text = _LIST_LEADER_RE.sub("", text)
|
|
29
|
+
text = _EMPHASIS_RE.sub(r"\2", text)
|
|
30
|
+
return text
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Azure DevOps work-item CSV export.
|
|
2
|
+
|
|
3
|
+
`Parent` is a numeric work-item ID, not a key, and in a real export it
|
|
4
|
+
commonly points outside the exported set (confirmed: 0 of 17 distinct
|
|
5
|
+
parents resolved within a real 40-row sample) — PB2 records it verbatim
|
|
6
|
+
and does not attempt to resolve it; that is a graph-era concern (PB10+),
|
|
7
|
+
not this phase's.
|
|
8
|
+
|
|
9
|
+
`Description` (and, when present, `Acceptance Criteria`) are genuine HTML
|
|
10
|
+
from ADO's rich-text editor (confirmed: `<div>`, ` `) — normalised via
|
|
11
|
+
`probative.ingest._html`, not the Jira wiki-markup path.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import csv
|
|
17
|
+
import io
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from probative.core.evidence import UnrecognisedTrackerFormatError
|
|
21
|
+
from probative.ingest import _html
|
|
22
|
+
from probative.ingest._extracted import ExtractedDocument
|
|
23
|
+
from probative.ingest._lines import decode_and_normalize_endings
|
|
24
|
+
from probative.ingest._tracker_text import TrackerTextBuilder
|
|
25
|
+
|
|
26
|
+
NORMALIZATION_VERSION = "ado_csv/1"
|
|
27
|
+
|
|
28
|
+
_REQUIRED_COLUMNS = ["ID", "Work Item Type", "State", "Title"]
|
|
29
|
+
_DESCRIPTION_COLUMN = "Description"
|
|
30
|
+
_PARENT_COLUMN = "Parent"
|
|
31
|
+
_ACCEPTANCE_CRITERIA_COLUMN = "Acceptance Criteria"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def extract(path: Path) -> ExtractedDocument:
|
|
35
|
+
text = decode_and_normalize_endings(path)
|
|
36
|
+
rows = list(csv.reader(io.StringIO(text)))
|
|
37
|
+
if not rows:
|
|
38
|
+
raise UnrecognisedTrackerFormatError(path, "file has no header row")
|
|
39
|
+
header = rows[0]
|
|
40
|
+
|
|
41
|
+
missing = [c for c in _REQUIRED_COLUMNS if c not in header]
|
|
42
|
+
if missing:
|
|
43
|
+
raise UnrecognisedTrackerFormatError(
|
|
44
|
+
path, f"missing required column(s) for ado_csv: {', '.join(missing)}"
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
id_i = header.index("ID")
|
|
48
|
+
type_i = header.index("Work Item Type")
|
|
49
|
+
state_i = header.index("State")
|
|
50
|
+
title_i = header.index("Title")
|
|
51
|
+
desc_i = header.index(_DESCRIPTION_COLUMN) if _DESCRIPTION_COLUMN in header else None
|
|
52
|
+
parent_i = header.index(_PARENT_COLUMN) if _PARENT_COLUMN in header else None
|
|
53
|
+
ac_i = (
|
|
54
|
+
header.index(_ACCEPTANCE_CRITERIA_COLUMN) if _ACCEPTANCE_CRITERIA_COLUMN in header else None
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
builder = TrackerTextBuilder()
|
|
58
|
+
for row in rows[1:]:
|
|
59
|
+
if not row:
|
|
60
|
+
continue
|
|
61
|
+
description = _html.to_text(row[desc_i]) if desc_i is not None and row[desc_i] else None
|
|
62
|
+
acceptance_criteria = _html.to_text(row[ac_i]) if ac_i is not None and row[ac_i] else None
|
|
63
|
+
parent_key = row[parent_i] if parent_i is not None and row[parent_i] else None
|
|
64
|
+
builder.add_issue(
|
|
65
|
+
key=row[id_i],
|
|
66
|
+
type_=row[type_i],
|
|
67
|
+
status=row[state_i],
|
|
68
|
+
parent_key=parent_key,
|
|
69
|
+
summary=row[title_i],
|
|
70
|
+
description=description,
|
|
71
|
+
acceptance_criteria=acceptance_criteria,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return builder.build(NORMALIZATION_VERSION)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Confluence exports (PB2-p2): a per-page "Export to Word" (MHTML behind a
|
|
2
|
+
`.doc` extension) becomes a plain `Source` — no derived record type, unlike
|
|
3
|
+
PB2's tracker `Issue`s, because a Confluence page carries no issue key,
|
|
4
|
+
status or hierarchy (confirmed against two real exports; see
|
|
5
|
+
`probative.ingest.confluence_word`).
|
|
6
|
+
|
|
7
|
+
Public API: `ingest_confluence`, `reextract_confluence`. Deliberately
|
|
8
|
+
separate from `probative.ingest`'s `ingest`/`reextract` (PB1), for the same
|
|
9
|
+
reason PB2's `tracker.py` is separate from it: a Confluence Word export's
|
|
10
|
+
real format can't be sniffed from its `.doc` extension — that extension
|
|
11
|
+
also means genuine legacy binary Word, which this codebase does not
|
|
12
|
+
support — so the caller states `format` explicitly instead of it being
|
|
13
|
+
guessed. Provenance is not reimplemented: callers use PB1's existing
|
|
14
|
+
`probative.ingest.spans()` directly against the resulting `Source`, since
|
|
15
|
+
there is no `issues()`-style derived view to build here.
|
|
16
|
+
|
|
17
|
+
The other real Confluence export variant — "Export to PDF" — needs no
|
|
18
|
+
module here at all: it is a well-formed PDF and is ingested through PB1's
|
|
19
|
+
existing `probative.ingest.ingest()` / `SourceFormat.PDF` unchanged.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import hashlib
|
|
25
|
+
from datetime import UTC, datetime
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
|
|
28
|
+
from probative.core.evidence import (
|
|
29
|
+
CorruptSourceError,
|
|
30
|
+
EmptySourceError,
|
|
31
|
+
EvidenceKind,
|
|
32
|
+
EvidenceSpan,
|
|
33
|
+
Source,
|
|
34
|
+
SourceFormat,
|
|
35
|
+
StaleNormalizationError,
|
|
36
|
+
Tier,
|
|
37
|
+
)
|
|
38
|
+
from probative.ingest import confluence_word
|
|
39
|
+
from probative.ingest._extracted import ExtractedDocument
|
|
40
|
+
|
|
41
|
+
_EXTRACTORS = {SourceFormat.CONFLUENCE_WORD: confluence_word.extract}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _extract(path: Path, fmt: SourceFormat) -> ExtractedDocument:
|
|
45
|
+
if fmt not in _EXTRACTORS:
|
|
46
|
+
raise ValueError(f"{fmt!r} is not a Confluence format PB2-p2 recognises")
|
|
47
|
+
return _EXTRACTORS[fmt](path)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def ingest_confluence(
|
|
51
|
+
path: Path, *, format: SourceFormat, tier: Tier, kind: EvidenceKind
|
|
52
|
+
) -> Source:
|
|
53
|
+
"""Ingest one Confluence export, producing a `Source` whose `id`/`sha256`
|
|
54
|
+
are pure functions of its bytes (idempotent, same as `ingest()`)."""
|
|
55
|
+
raw = path.read_bytes()
|
|
56
|
+
if len(raw) == 0:
|
|
57
|
+
raise EmptySourceError(path, "file is empty")
|
|
58
|
+
sha256 = hashlib.sha256(raw).hexdigest()
|
|
59
|
+
doc = _extract(path, format)
|
|
60
|
+
return Source(
|
|
61
|
+
id=f"src_{sha256[:16]}",
|
|
62
|
+
path=path,
|
|
63
|
+
sha256=sha256,
|
|
64
|
+
format=format,
|
|
65
|
+
tier=tier,
|
|
66
|
+
kind=kind,
|
|
67
|
+
ingested_at=datetime.now(UTC),
|
|
68
|
+
extractor=f"probative.ingest.confluence.{format.value}",
|
|
69
|
+
extractor_version=doc.normalization_version,
|
|
70
|
+
text=doc.text,
|
|
71
|
+
locator_regions=doc.locator_regions,
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def reextract_confluence(source: Source, span: EvidenceSpan) -> str:
|
|
76
|
+
"""Re-run Confluence extraction on `source.path` and slice at the
|
|
77
|
+
span's offsets — the Confluence counterpart to
|
|
78
|
+
`probative.ingest.reextract`."""
|
|
79
|
+
if span.source_id != source.id:
|
|
80
|
+
raise ValueError(f"span belongs to source {span.source_id!r}, not {source.id!r}")
|
|
81
|
+
fresh = ingest_confluence(source.path, format=source.format, tier=source.tier, kind=source.kind)
|
|
82
|
+
if fresh.extractor_version != source.extractor_version:
|
|
83
|
+
raise StaleNormalizationError(
|
|
84
|
+
source.path,
|
|
85
|
+
f"normalisation changed ({source.extractor_version} -> "
|
|
86
|
+
f"{fresh.extractor_version}); offsets recorded against the old "
|
|
87
|
+
f"version are not guaranteed valid",
|
|
88
|
+
)
|
|
89
|
+
if fresh.sha256 != source.sha256:
|
|
90
|
+
raise CorruptSourceError(source.path, "file contents changed since ingestion")
|
|
91
|
+
return fresh.text[span.start : span.end]
|