anonymous-md's picture
Add prose-repair pipeline implementation (10 stages, DMNR masking, typed repair, 6-tool quality ensemble)
b7d696b verified
Raw
History Blame Contribute Delete
4.82 kB
"""
Document object: the single atomic unit threading the whole pipeline.
It carries:
- the current (possibly masked) text
- structured segments (code/math/structured) sliced out by masking, kept in
LIFO order
- an audit record for every change (stage number, operation, target segment,
pre/post SHA-256)
- rollbackable snapshots (pre-stage text snapshots that allow whole-stage undo)
Design principles (paper Section 3.6): integrity, rollbackability,
traceability, byte-level fidelity.
"""
from __future__ import annotations
import enum
import hashlib
import time
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
def sha256_text(text: str) -> str:
"""Compute SHA-256 over the UTF-8 encoding of the text (used for integrity checks and auditing)."""
return hashlib.sha256(text.encode("utf-8")).hexdigest()
class SegmentType(enum.Enum):
PROSE = "PROSE"
CODE = "CODE"
MATH = "MATH"
STRUCTURED = "STRUCTURED" # tables / JSON / YAML / TOML / XML / CSV / Markdown
@dataclass
class Segment:
"""A non-prose segment sliced out by masking."""
seg_type: SegmentType
placeholder: str # placeholder that replaces it in the text (includes PUA sentinels)
original_content: str # original content (used for LIFO restore / SHA check)
content_sha256: str # hash of content at the moment of masking
repaired_content: Optional[str] = None # type-specific-repaired content
repaired_validated: bool = False # whether pre-restore type-specific validation passed
nesting_depth: int = 0 # inner-to-outer extraction depth (basis for LIFO restore)
meta: Dict[str, Any] = field(default_factory=dict)
@classmethod
def make(cls, seg_type: SegmentType, placeholder: str, content: str,
nesting_depth: int = 0, **meta) -> "Segment":
return cls(
seg_type=seg_type,
placeholder=placeholder,
original_content=content,
content_sha256=sha256_text(content),
nesting_depth=nesting_depth,
meta=meta,
)
@dataclass
class AuditRecord:
"""A single-change audit record (paper Section 3.6, fourth principle)."""
stage: int
operation: str
target: str # target object ("document" / segment placeholder, etc.)
sha_before: str
sha_after: str
note: str = ""
ts: float = field(default_factory=time.time)
@dataclass
class Document:
# --- raw + current state ---
raw_bytes: bytes = b""
original_text: str = "" # text after Stage 1 decoding (basis for rollback)
text: str = "" # current (possibly masked) text
# --- upstream metadata (used by the Stage 1 priority cascade) ---
http_charset: Optional[str] = None # HTTP Content-Type declaration
html_meta_charset: Optional[str] = None # <meta charset>
has_dom: bool = False # upstream retains an HTML DOM
dom_html: Optional[str] = None # raw HTML (used by the DOM-priority path)
source_hint: Optional[str] = None # e.g. "ocr" / "rfc" / "email"
# --- masked segments (LIFO) ---
segments: List[Segment] = field(default_factory=list)
# --- quality + state ---
detected_encoding: Optional[str] = None
quality_passed: Optional[bool] = None
quality_score: Optional[float] = None
discarded: bool = False
discard_reason: str = ""
# --- audit + rollback ---
audit: List[AuditRecord] = field(default_factory=list)
_snapshots: Dict[int, str] = field(default_factory=dict) # stage -> text snapshot
meta: Dict[str, Any] = field(default_factory=dict)
# ---------------------------------------------------------------- #
def snapshot(self, stage: int) -> None:
"""Save a text snapshot before a stage starts, enabling whole-stage rollback."""
self._snapshots[stage] = self.text
def rollback(self, stage: int) -> None:
if stage in self._snapshots:
self.text = self._snapshots[stage]
def record(self, stage: int, operation: str, sha_before: str,
target: str = "document", note: str = "") -> None:
self.audit.append(AuditRecord(
stage=stage, operation=operation, target=target,
sha_before=sha_before, sha_after=sha256_text(self.text), note=note,
))
def apply(self, stage: int, operation: str, new_text: str,
target: str = "document", note: str = "") -> None:
"""Apply a text-level change and auto-record it."""
sha_before = sha256_text(self.text)
self.text = new_text
self.record(stage, operation, sha_before, target, note)
def next_segment_index(self) -> int:
return len(self.segments)