File size: 7,119 Bytes
1f5647a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | """Offset-preserving target/context packing and hierarchical coverage.
Every input token is either an original source token or a declared BERT
separator. Targets are never silently truncated. Context uses a bounded,
measured neighborhood, so a long document's uninspected context stays visible.
"""
from __future__ import annotations
from dataclasses import dataclass, asdict
from typing import Any
from contracts import sha256, source_anchor
@dataclass(frozen=True)
class SourceSentence:
id: str
text: str
start: int | None = None
end: int | None = None
paragraph_id: str | None = None
section_id: str | None = None
def _tokens(tokenizer, text):
value = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True, truncation=False)
return value["input_ids"], value["offset_mapping"]
def pack(tokenizer, target: SourceSentence, before: list[SourceSentence], after: list[SourceSentence],
*, include_context: bool = True, maximum_tokens: int = 256) -> dict[str, Any]:
target_ids, _ = _tokens(tokenizer, target.text)
base = {"target_id": target.id, "target_sha256": sha256(target.text), "target_tokens": len(target_ids),
"maximum_tokens": maximum_tokens, "target_start": target.start, "target_end": target.end,
"context_used": include_context, "context_sentences_available": len(before[-2:]) + len(after[:2]),
"context_tokens_available": 0, "context_tokens_retained": 0, "context_available": False}
if not target_ids:
return base | {"status": "invalid_input", "reason": "empty_target", "target_tokens_retained": 0}
if len(target_ids) + 2 > maximum_tokens:
return base | {"status": "unresolved", "reason": "target_too_long", "target_tokens_retained": 0,
"context_tokens_available": 0, "context_tokens_retained": 0}
def side(sentences):
ids, anchors = [], []
for sentence in sentences:
encoded, offsets = _tokens(tokenizer, sentence.text)
for token, (start, end) in zip(encoded, offsets):
ids.append(token)
anchors.append({"sentence_id": sentence.id, "start": start + sentence.start if sentence.start is not None else None,
"end": end + sentence.start if sentence.start is not None else None})
return ids, anchors
left, left_spans = side(before[-2:]) if include_context else ([], [])
right, right_spans = side(after[:2]) if include_context else ([], [])
available = len(left) + len(right)
budget = max(0, maximum_tokens - len(target_ids) - 4)
keep_left = min(len(left), budget // 2)
keep_right = min(len(right), budget - keep_left)
keep_left = min(len(left), budget - keep_right)
left_ids, left_anchors = (left[-keep_left:], left_spans[-keep_left:]) if keep_left else ([], [])
right_ids, right_anchors = right[:keep_right], right_spans[:keep_right]
cls, sep = tokenizer.cls_token_id, tokenizer.sep_token_id
ids = [cls] + target_ids + [sep]
types = [0] * len(ids)
target_mask = [0] + [1] * len(target_ids) + [0]
context_mask = [0] * len(ids)
if left_ids or right_ids:
tail = left_ids + [sep] + right_ids + [sep]
ids += tail
types += [1] * len(tail)
target_mask += [0] * len(tail)
context_mask += [1] * len(left_ids) + [0] + [1] * len(right_ids) + [0]
assert len(ids) <= maximum_tokens
return base | {"status": "ok", "reason": None, "input_ids": ids, "attention_mask": [1] * len(ids),
"token_type_ids": types, "target_mask": target_mask, "context_mask": context_mask,
"target_tokens_retained": len(target_ids), "context_tokens_available": available,
"context_tokens_retained": len(left_ids) + len(right_ids), "context_token_anchors": left_anchors + right_anchors,
"actual_tokens": len(ids), "context_available": available > 0,
"paragraph_id": target.paragraph_id, "section_id": target.section_id}
def document_inputs(tokenizer, document_id: str, text: str, sentences: list[SourceSentence], *, include_context=True):
if len({sentence.id for sentence in sentences}) != len(sentences):
raise ValueError("Source sentence IDs must be unique within a document")
previous_end = -1
for sentence in sentences:
if sentence.start is None or sentence.end is None or not 0 <= sentence.start < sentence.end <= len(text):
raise ValueError("Every target needs an exact original-document source location")
if sentence.start < previous_end or text[sentence.start:sentence.end] != sentence.text:
raise ValueError("Sentence spans must follow source order and reproduce source text")
previous_end = sentence.end
records = []
for index, sentence in enumerate(sentences):
value = pack(tokenizer, sentence, sentences[max(0, index - 2):index], sentences[index + 1:index + 3],
include_context=include_context)
value["source_anchor"] = source_anchor(document_id, text, sentence.start, sentence.end)
records.append(value)
eligible = [row for row in records if row["status"] == "ok"]
chars = sum(row["source_anchor"]["end"] - row["source_anchor"]["start"] for row in eligible)
total_target_chars = sum(len(sentence.text) for sentence in sentences)
summary = {"document_id": document_id, "document_sha256": sha256(text), "document_characters": len(text),
"sentences_attempted": len(sentences), "sentences_eligible": len(eligible),
"sentences_unresolved": len(records) - len(eligible), "eligible_target_characters": chars,
"target_character_coverage": chars / total_target_chars if total_target_chars else 0,
"document_character_coverage": chars / len(text) if text else 0,
"target_tokens_attempted": sum(row["target_tokens"] for row in records),
"target_tokens_retained": sum(row["target_tokens_retained"] for row in records),
"context_tokens_available": sum(row["context_tokens_available"] for row in records),
"context_tokens_retained": sum(row["context_tokens_retained"] for row in records),
"paragraphs_with_eligible_targets": len({row["paragraph_id"] for row in eligible if row["paragraph_id"] is not None}),
"sections_with_eligible_targets": len({row["section_id"] for row in eligible if row["section_id"] is not None}),
"global_context_claim": False, "page_limit": None,
"scope": "All supplied source sentences are attempted. Neighbor context is bounded; absence of findings is not whole-document neutrality."}
return records, summary
def attribution_boundary(*, quoted_source_annotation: bool | None, predicted_source_bias: bool) -> dict[str, Any]:
return {"source_bias_flag": predicted_source_bias, "quoted_source_annotation": quoted_source_annotation,
"reporter_endorsement": "unresolved", "speaker_stance_model": "not_qualified",
"interpretation": "A source-task bias flag identifies language for review; it does not attribute the quoted position to the reporter."}
|