anonymous-md commited on
Commit
b7d696b
·
verified ·
1 Parent(s): 16667b9

Add prose-repair pipeline implementation (10 stages, DMNR masking, typed repair, 6-tool quality ensemble)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. repair_pipeline_package/__init__.py +24 -0
  2. repair_pipeline_package/__pycache__/__init__.cpython-310.pyc +0 -0
  3. repair_pipeline_package/__pycache__/config.cpython-310.pyc +0 -0
  4. repair_pipeline_package/__pycache__/document.cpython-310.pyc +0 -0
  5. repair_pipeline_package/__pycache__/pipeline.cpython-310.pyc +0 -0
  6. repair_pipeline_package/__pycache__/run.cpython-310.pyc +0 -0
  7. repair_pipeline_package/config.py +93 -0
  8. repair_pipeline_package/document.py +127 -0
  9. repair_pipeline_package/masking/__init__.py +5 -0
  10. repair_pipeline_package/masking/__pycache__/__init__.cpython-310.pyc +0 -0
  11. repair_pipeline_package/masking/__pycache__/dom_path.cpython-310.pyc +0 -0
  12. repair_pipeline_package/masking/__pycache__/sentinel.cpython-310.pyc +0 -0
  13. repair_pipeline_package/masking/__pycache__/text_path.cpython-310.pyc +0 -0
  14. repair_pipeline_package/masking/dom_path.py +259 -0
  15. repair_pipeline_package/masking/sentinel.py +49 -0
  16. repair_pipeline_package/masking/text_path.py +153 -0
  17. repair_pipeline_package/pipeline.py +104 -0
  18. repair_pipeline_package/quality/__init__.py +3 -0
  19. repair_pipeline_package/quality/__pycache__/__init__.cpython-310.pyc +0 -0
  20. repair_pipeline_package/quality/__pycache__/ensemble.cpython-310.pyc +0 -0
  21. repair_pipeline_package/quality/ensemble.py +186 -0
  22. repair_pipeline_package/run.py +85 -0
  23. repair_pipeline_package/stages/__init__.py +13 -0
  24. repair_pipeline_package/stages/__pycache__/__init__.cpython-310.pyc +0 -0
  25. repair_pipeline_package/stages/__pycache__/stage01_encoding.cpython-310.pyc +0 -0
  26. repair_pipeline_package/stages/__pycache__/stage02_masking.cpython-310.pyc +0 -0
  27. repair_pipeline_package/stages/__pycache__/stage03_ftfy.cpython-310.pyc +0 -0
  28. repair_pipeline_package/stages/__pycache__/stage04_artifacts.cpython-310.pyc +0 -0
  29. repair_pipeline_package/stages/__pycache__/stage05_linelevel.cpython-310.pyc +0 -0
  30. repair_pipeline_package/stages/__pycache__/stage06_charnorm.cpython-310.pyc +0 -0
  31. repair_pipeline_package/stages/__pycache__/stage07_whitespace.cpython-310.pyc +0 -0
  32. repair_pipeline_package/stages/__pycache__/stage08_ocr.cpython-310.pyc +0 -0
  33. repair_pipeline_package/stages/__pycache__/stage09_quality.cpython-310.pyc +0 -0
  34. repair_pipeline_package/stages/__pycache__/stage10_restore.cpython-310.pyc +0 -0
  35. repair_pipeline_package/stages/stage01_encoding.py +137 -0
  36. repair_pipeline_package/stages/stage02_masking.py +39 -0
  37. repair_pipeline_package/stages/stage03_ftfy.py +72 -0
  38. repair_pipeline_package/stages/stage04_artifacts.py +104 -0
  39. repair_pipeline_package/stages/stage05_linelevel.py +136 -0
  40. repair_pipeline_package/stages/stage06_charnorm.py +72 -0
  41. repair_pipeline_package/stages/stage07_whitespace.py +41 -0
  42. repair_pipeline_package/stages/stage08_ocr.py +193 -0
  43. repair_pipeline_package/stages/stage09_quality.py +42 -0
  44. repair_pipeline_package/stages/stage10_restore.py +73 -0
  45. repair_pipeline_package/typed_repair/__init__.py +34 -0
  46. repair_pipeline_package/typed_repair/__pycache__/__init__.cpython-310.pyc +0 -0
  47. repair_pipeline_package/typed_repair/__pycache__/code_repair.cpython-310.pyc +0 -0
  48. repair_pipeline_package/typed_repair/__pycache__/math_repair.cpython-310.pyc +0 -0
  49. repair_pipeline_package/typed_repair/__pycache__/structured_repair.cpython-310.pyc +0 -0
  50. repair_pipeline_package/typed_repair/code_repair.py +177 -0
repair_pipeline_package/__init__.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Ten-stage corpus data repair pipeline (Repair-First).
3
+
4
+ Stage order strictly follows the paper, with the single mandatory modification:
5
+ the "mixed-content masking" step is moved before "ftfy atomic repair"
6
+ (i.e., the original Stage 3 is moved before the original Stage 2).
7
+
8
+ Public entry point:
9
+ from repair_pipeline import RepairPipeline
10
+ out = RepairPipeline().run(raw_bytes, http_charset=..., source_hint=...)
11
+ """
12
+
13
+ from .pipeline import RepairPipeline
14
+ from .document import Document, AuditRecord, Segment, SegmentType
15
+
16
+ __all__ = [
17
+ "RepairPipeline",
18
+ "Document",
19
+ "AuditRecord",
20
+ "Segment",
21
+ "SegmentType",
22
+ ]
23
+
24
+ __version__ = "1.0.0"
repair_pipeline_package/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (820 Bytes). View file
 
repair_pipeline_package/__pycache__/config.cpython-310.pyc ADDED
Binary file (2.13 kB). View file
 
repair_pipeline_package/__pycache__/document.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
repair_pipeline_package/__pycache__/pipeline.cpython-310.pyc ADDED
Binary file (3.89 kB). View file
 
repair_pipeline_package/__pycache__/run.cpython-310.pyc ADDED
Binary file (2.9 kB). View file
 
repair_pipeline_package/config.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Central configuration: model paths, thresholds, constants.
3
+
4
+ Every stage that needs an external model/dictionary reads its path from here.
5
+ By convention, all models are placed under /data/models with descriptive
6
+ placeholder filenames; put the real model files at the matching paths.
7
+ """
8
+
9
+ import os
10
+
11
+ # --------------------------------------------------------------------------- #
12
+ # Models root directory
13
+ # --------------------------------------------------------------------------- #
14
+ MODELS_ROOT = os.environ.get("REPAIR_MODELS_ROOT", "/data/models")
15
+
16
+
17
+ def _p(*parts: str) -> str:
18
+ return os.path.join(MODELS_ROOT, *parts)
19
+
20
+
21
+ # --- Stages 2/3 masking: DOM Level-3 residual classifier + plain-text block classifier --- #
22
+ XGB_AMBIGUOUS_BLOCK_MODEL = _p("masking", "dom_ambiguous_block_xgb.json") # 42-dim XGBoost
23
+ TEXT_BLOCK_ML_MODEL = _p("masking", "text_block_lgbm.txt") # lightweight ML block classifier
24
+
25
+ # --- Code-type detection: Magika (pip-bundled model; optional override) -------- #
26
+ MAGIKA_MODEL_DIR = _p("magika") # leave empty to use the bundled magika model
27
+
28
+ # --- Stage 5 line-level repair: custom spaCy model (complex sentence/line boundaries) --- #
29
+ SPACY_LINEBREAK_MODEL = _p("spacy", "linebreak_repair_model")
30
+ SPACY_FALLBACK_PIPE = "en_core_web_sm" # fallback when the custom model is missing
31
+
32
+ # English dictionary (hyphen-wrap rejoin verification, SymSpell reuse) -------- #
33
+ ENGLISH_WORDLIST = _p("dict", "english_words.txt")
34
+
35
+ # --- Stage 8 OCR repair ------------------------------------------------------ #
36
+ SYMSPELL_DICT_PATH = _p("symspell", "frequency_dictionary_en_82_765.txt")
37
+ SYMSPELL_BIGRAM_PATH = _p("symspell", "frequency_bigramdictionary_en_243_342.txt")
38
+ BYT5_OCR_MODEL_DIR = _p("byt5-base-ocr-corrector") # ByT5-base fine-tuned weights directory
39
+ KENLM_MODEL_PATH = _p("kenlm", "en.wiki.5gram.arpa.bin") # perplexity scoring / rollback
40
+
41
+ # --- Stage 9 quality validation: 6-tool complementary ensemble (CPU-only) ----- #
42
+ DCLM_FASTTEXT_MODEL = _p("fasttext", "dclm_quality_classifier.bin")
43
+ # NeMo-DataTrove-DataJuicer joint-metric system is rule/statistic-based: no separate weights file.
44
+ # LanguageTool / NLTK / unicodedata / ftfy do not need any weights under /data/models.
45
+
46
+
47
+ # --------------------------------------------------------------------------- #
48
+ # Thresholds and constants
49
+ # --------------------------------------------------------------------------- #
50
+
51
+ # Stage 8 OCR: CER-tier routing boundaries (inclusive upper bounds)
52
+ OCR_CER_SYMSPELL_MAX = 0.05 # < 5% -> SymSpell
53
+ OCR_CER_BYT5_MAX = 0.15 # 5%-15% -> ByT5
54
+ OCR_CER_ROLLBACK_MAX = 0.20 # 15%-20%-> ByT5 + KenLM rollback safety net
55
+ # > 20% -> drop directly
56
+ OCR_DICT_HIT_THRESHOLD = 0.90 # dictionary hit rate below this flags a suspected OCR-noise segment
57
+
58
+ # Stage 5 line-level repair: fixed-column hard-wrap diagnostic
59
+ FIXED_COLUMN_WIDTHS = (72, 80)
60
+ FIXED_COLUMN_TOL = 4 # line lengths within column-width +/- 4 are treated as fixed-column layout
61
+
62
+ # Stage 7 whitespace normalization
63
+ TAB_TO_SPACES = 4
64
+ MAX_CONSECUTIVE_BLANK_LINES = 2 # >=3 consecutive blank lines are collapsed to 2 (keeping 1 blank line)
65
+
66
+ # Stage 9 quality gate: binary threshold (composite score >= threshold passes)
67
+ QUALITY_PASS_THRESHOLD = 0.60
68
+
69
+ # --------------------------------------------------------------------------- #
70
+ # Private Use Area sentinels (PUA Sentinel)
71
+ # --------------------------------------------------------------------------- #
72
+ # We use the high PUA range to avoid common early-web font private-use blocks
73
+ # (which typically begin at U+E000). Stage 6 PUA cleanup preserves sentinels
74
+ # allocated within this range.
75
+ SENTINEL_PUA_START = 0xF000 # sentinel allocation start codepoint
76
+ SENTINEL_PUA_END = 0xF8FF # sentinel allocation end codepoint (PUA upper bound)
77
+
78
+ # Plain-text placeholder format (human-readable for auditing / LIFO restoration)
79
+ TEXT_PLACEHOLDER_FMT = "{kind}_{idx:04d}" # wrapped in PUA sentinels on both sides
80
+
81
+ # --------------------------------------------------------------------------- #
82
+ # Logging
83
+ # --------------------------------------------------------------------------- #
84
+ import logging
85
+
86
+ logging.basicConfig(
87
+ level=os.environ.get("REPAIR_LOG_LEVEL", "INFO"),
88
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
89
+ )
90
+
91
+
92
+ def get_logger(name: str) -> logging.Logger:
93
+ return logging.getLogger(name)
repair_pipeline_package/document.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Document object: the single atomic unit threading the whole pipeline.
3
+
4
+ It carries:
5
+ - the current (possibly masked) text
6
+ - structured segments (code/math/structured) sliced out by masking, kept in
7
+ LIFO order
8
+ - an audit record for every change (stage number, operation, target segment,
9
+ pre/post SHA-256)
10
+ - rollbackable snapshots (pre-stage text snapshots that allow whole-stage undo)
11
+
12
+ Design principles (paper Section 3.6): integrity, rollbackability,
13
+ traceability, byte-level fidelity.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import enum
19
+ import hashlib
20
+ import time
21
+ from dataclasses import dataclass, field
22
+ from typing import Any, Dict, List, Optional
23
+
24
+
25
+ def sha256_text(text: str) -> str:
26
+ """Compute SHA-256 over the UTF-8 encoding of the text (used for integrity checks and auditing)."""
27
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
28
+
29
+
30
+ class SegmentType(enum.Enum):
31
+ PROSE = "PROSE"
32
+ CODE = "CODE"
33
+ MATH = "MATH"
34
+ STRUCTURED = "STRUCTURED" # tables / JSON / YAML / TOML / XML / CSV / Markdown
35
+
36
+
37
+ @dataclass
38
+ class Segment:
39
+ """A non-prose segment sliced out by masking."""
40
+ seg_type: SegmentType
41
+ placeholder: str # placeholder that replaces it in the text (includes PUA sentinels)
42
+ original_content: str # original content (used for LIFO restore / SHA check)
43
+ content_sha256: str # hash of content at the moment of masking
44
+ repaired_content: Optional[str] = None # type-specific-repaired content
45
+ repaired_validated: bool = False # whether pre-restore type-specific validation passed
46
+ nesting_depth: int = 0 # inner-to-outer extraction depth (basis for LIFO restore)
47
+ meta: Dict[str, Any] = field(default_factory=dict)
48
+
49
+ @classmethod
50
+ def make(cls, seg_type: SegmentType, placeholder: str, content: str,
51
+ nesting_depth: int = 0, **meta) -> "Segment":
52
+ return cls(
53
+ seg_type=seg_type,
54
+ placeholder=placeholder,
55
+ original_content=content,
56
+ content_sha256=sha256_text(content),
57
+ nesting_depth=nesting_depth,
58
+ meta=meta,
59
+ )
60
+
61
+
62
+ @dataclass
63
+ class AuditRecord:
64
+ """A single-change audit record (paper Section 3.6, fourth principle)."""
65
+ stage: int
66
+ operation: str
67
+ target: str # target object ("document" / segment placeholder, etc.)
68
+ sha_before: str
69
+ sha_after: str
70
+ note: str = ""
71
+ ts: float = field(default_factory=time.time)
72
+
73
+
74
+ @dataclass
75
+ class Document:
76
+ # --- raw + current state ---
77
+ raw_bytes: bytes = b""
78
+ original_text: str = "" # text after Stage 1 decoding (basis for rollback)
79
+ text: str = "" # current (possibly masked) text
80
+
81
+ # --- upstream metadata (used by the Stage 1 priority cascade) ---
82
+ http_charset: Optional[str] = None # HTTP Content-Type declaration
83
+ html_meta_charset: Optional[str] = None # <meta charset>
84
+ has_dom: bool = False # upstream retains an HTML DOM
85
+ dom_html: Optional[str] = None # raw HTML (used by the DOM-priority path)
86
+ source_hint: Optional[str] = None # e.g. "ocr" / "rfc" / "email"
87
+
88
+ # --- masked segments (LIFO) ---
89
+ segments: List[Segment] = field(default_factory=list)
90
+
91
+ # --- quality + state ---
92
+ detected_encoding: Optional[str] = None
93
+ quality_passed: Optional[bool] = None
94
+ quality_score: Optional[float] = None
95
+ discarded: bool = False
96
+ discard_reason: str = ""
97
+
98
+ # --- audit + rollback ---
99
+ audit: List[AuditRecord] = field(default_factory=list)
100
+ _snapshots: Dict[int, str] = field(default_factory=dict) # stage -> text snapshot
101
+ meta: Dict[str, Any] = field(default_factory=dict)
102
+
103
+ # ---------------------------------------------------------------- #
104
+ def snapshot(self, stage: int) -> None:
105
+ """Save a text snapshot before a stage starts, enabling whole-stage rollback."""
106
+ self._snapshots[stage] = self.text
107
+
108
+ def rollback(self, stage: int) -> None:
109
+ if stage in self._snapshots:
110
+ self.text = self._snapshots[stage]
111
+
112
+ def record(self, stage: int, operation: str, sha_before: str,
113
+ target: str = "document", note: str = "") -> None:
114
+ self.audit.append(AuditRecord(
115
+ stage=stage, operation=operation, target=target,
116
+ sha_before=sha_before, sha_after=sha256_text(self.text), note=note,
117
+ ))
118
+
119
+ def apply(self, stage: int, operation: str, new_text: str,
120
+ target: str = "document", note: str = "") -> None:
121
+ """Apply a text-level change and auto-record it."""
122
+ sha_before = sha256_text(self.text)
123
+ self.text = new_text
124
+ self.record(stage, operation, sha_before, target, note)
125
+
126
+ def next_segment_index(self) -> int:
127
+ return len(self.segments)
repair_pipeline_package/masking/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .dom_path import mask_dom
2
+ from .text_path import mask_text
3
+ from .sentinel import SentinelAllocator, lifo_order
4
+
5
+ __all__ = ["mask_dom", "mask_text", "SentinelAllocator", "lifo_order"]
repair_pipeline_package/masking/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (364 Bytes). View file
 
repair_pipeline_package/masking/__pycache__/dom_path.cpython-310.pyc ADDED
Binary file (9.27 kB). View file
 
repair_pipeline_package/masking/__pycache__/sentinel.cpython-310.pyc ADDED
Binary file (2.55 kB). View file
 
repair_pipeline_package/masking/__pycache__/text_path.cpython-310.pyc ADDED
Binary file (5.82 kB). View file
 
repair_pipeline_package/masking/dom_path.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DOM-priority path (Path A): three-level cascade hierarchical router.
3
+
4
+ Level 1: <head> metadata pre-scan + MathJax/KaTeX delimiter configuration probing
5
+ Level 2: 13-priority chain, single-pass DFS classification (outer first; strong
6
+ boundaries stop descent + subtree-scan exemption)
7
+ Level 3: 42-dim XGBoost residual classifier for ambiguous containers like
8
+ <div>/<span>
9
+
10
+ Extraction is "inner-to-outer"; segments are replaced with PUA sentinel
11
+ placeholders.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from typing import List, Optional, Tuple
18
+
19
+ from ..config import XGB_AMBIGUOUS_BLOCK_MODEL, get_logger
20
+ from ..document import Document, SegmentType
21
+ from .sentinel import SentinelAllocator
22
+
23
+ log = get_logger(__name__)
24
+
25
+ # Level-2 priority-chain key signals (Table 4.2)
26
+ _CODE_CLASS_RE = re.compile(
27
+ r"(?:^|\s)(language-|lang-|highlight|codehilite|sourceCode|prettyprint|"
28
+ r"brush:|hljs|chroma|rouge)", re.I)
29
+ _MATH_CLASS_RE = re.compile(r"(?:^MathJax|^mjx-|^katex|mwe-math)", re.I)
30
+ _LEGACY_CODE_TAGS = {"xmp", "listing", "plaintext", "tt"}
31
+ _DEPRECATED_HINT = ("pre", "code", "math", "table", "ol", "ul", "dl")
32
+
33
+ # Strong-boundary tag set: stop descent by default once matched (structural
34
+ # container blocks get a subtree-scan exemption)
35
+ _STRONG_BOUNDARY = {"pre", "code", "math", "table", "ol", "ul", "dl",
36
+ "form", "figure", "figcaption", "blockquote",
37
+ "script", "style", "xmp", "listing", "plaintext"}
38
+ _STRUCT_CONTAINERS = {"table", "ol", "ul", "dl"}
39
+ _AMBIGUOUS = {"div", "span"}
40
+
41
+
42
+ class DomMetadata:
43
+ """Level-1 pre-scan result."""
44
+ def __init__(self):
45
+ self.inline_math_dollar = False # enable $...$ inline math?
46
+ self.display_math = True # $$ / \[ \] generally enabled by default
47
+ self.json_ld = []
48
+ self.libs = set() # mathjax / katex
49
+
50
+
51
+ def _level1_prescan(soup) -> DomMetadata:
52
+ md = DomMetadata()
53
+ head = soup.find("head")
54
+ scope = head if head is not None else soup
55
+ # JSON-LD / Microdata
56
+ for s in scope.find_all("script", attrs={"type": "application/ld+json"}):
57
+ md.json_ld.append(s.get_text())
58
+ # MathJax / KaTeX loading + delimiter configuration
59
+ page_text = str(scope)
60
+ if re.search(r"mathjax", page_text, re.I):
61
+ md.libs.add("mathjax")
62
+ if re.search(r"katex", page_text, re.I):
63
+ md.libs.add("katex")
64
+ # Only activate inline $-math if explicit ['$','$'] config exists,
65
+ # to avoid swallowing currency-style text.
66
+ if re.search(r"inlineMath\s*[:=].*\[\s*\[\s*['\"]\$['\"]", page_text):
67
+ md.inline_math_dollar = True
68
+ return md
69
+
70
+
71
+ def _classify_node_level2(node, md: DomMetadata) -> Optional[SegmentType]:
72
+ """Single-pass DFS priority chain (the 6 core rules of Table 4.2). Return None to continue descent."""
73
+ name = (node.name or "").lower()
74
+ classes = " ".join(node.get("class", [])) if hasattr(node, "get") else ""
75
+
76
+ # 1: JSON-LD / Microdata container
77
+ if name == "script" and node.get("type") == "application/ld+json":
78
+ return SegmentType.STRUCTURED
79
+ if node.get("itemscope") is not None:
80
+ return SegmentType.STRUCTURED
81
+ # 2: math
82
+ if name == "math" or _MATH_CLASS_RE.search(classes):
83
+ return SegmentType.MATH
84
+ if name == "img" and node.get("alt") and re.search(r"[=+\\^]", node.get("alt", "")):
85
+ return SegmentType.MATH
86
+ # 3: <pre><code> / code class names / legacy HTML code tags
87
+ if name == "pre" or _CODE_CLASS_RE.search(classes) or name in _LEGACY_CODE_TAGS:
88
+ return SegmentType.CODE
89
+ if name == "code" and (node.parent is None or node.parent.name != "pre"):
90
+ return SegmentType.CODE
91
+ # 4: inline code-semantic tags under a non-<pre> parent
92
+ if name in {"kbd", "samp", "var"}:
93
+ return SegmentType.CODE
94
+ # 5: data tables (layout tables get an exemption; descend into each cell)
95
+ if name == "table":
96
+ return SegmentType.STRUCTURED if _is_data_table(node) else None
97
+ # 6: lists (subtree-scan first; classify the whole as structured data)
98
+ if name in {"ul", "ol", "dl"}:
99
+ return SegmentType.STRUCTURED
100
+ return None
101
+
102
+
103
+ def _is_data_table(table) -> bool:
104
+ """Lightweight layout-vs-data-table decision (simplified version of the paper's Table 4.3 6-layer heuristic)."""
105
+ if table.find("th") is not None or table.find("thead") is not None:
106
+ return True
107
+ rows = table.find_all("tr")
108
+ if len(rows) < 2:
109
+ return False
110
+ col_counts = [len(r.find_all(["td", "th"])) for r in rows]
111
+ if not col_counts:
112
+ return False
113
+ # Consistent column count >= 2 and no nested layout elements -> favours data table
114
+ consistent = len(set(col_counts)) == 1 and col_counts[0] >= 2
115
+ has_layout = table.find(["nav", "form"]) is not None
116
+ return consistent and not has_layout
117
+
118
+
119
+ # --------------------------------------------------------------------------- #
120
+ # Level-3 residual classifier
121
+ # --------------------------------------------------------------------------- #
122
+ class _XGBResidualClassifier:
123
+ """42-dim feature-driven XGBoost residual classifier (ambiguous div/span containers)."""
124
+
125
+ def __init__(self, model_path: str):
126
+ self.model = None
127
+ try:
128
+ import xgboost as xgb # noqa
129
+ self.model = xgb.Booster()
130
+ self.model.load_model(model_path)
131
+ log.info("Loaded XGBoost residual classifier: %s", model_path)
132
+ except Exception as e: # model missing -> fall back to pure heuristics
133
+ log.warning("XGBoost residual classifier unavailable (%s); "
134
+ "falling back to heuristics.", e)
135
+
136
+ def _features(self, node) -> List[float]:
137
+ """Build a 42-dim feature vector (nine signal groups, simplified but dimension-aligned)."""
138
+ text = node.get_text() or ""
139
+ name = (node.name or "").lower()
140
+ classes = " ".join(node.get("class", []))
141
+ n = max(len(text), 1)
142
+ alpha = sum(c.isalpha() for c in text) / n
143
+ digit = sum(c.isdigit() for c in text) / n
144
+ space = sum(c.isspace() for c in text) / n
145
+ symbol = 1.0 - alpha - digit - space
146
+ feats = [
147
+ # DOM structure (8)
148
+ 1.0 if name == "div" else 0.0, 1.0 if name == "span" else 0.0,
149
+ float(len(list(node.parents))), float(len(node.find_all(recursive=False))),
150
+ float(len(node.find_next_siblings())), float(len(node.find_previous_siblings())),
151
+ 1.0 if node.get("class") else 0.0, float(len(name)),
152
+ # Inline style (2)
153
+ 1.0 if re.search(r"monospace|courier", str(node.get("style", "")), re.I) else 0.0,
154
+ 1.0 if re.search(r"center", str(node.get("style", "")), re.I) else 0.0,
155
+ # Content patterns (4)
156
+ 1.0 if re.search(r"\$|\\frac|\\sum|\\[\[\]]", text) else 0.0,
157
+ 1.0 if re.search(r"\b(def|import|class|function|var|public)\b", text) else 0.0,
158
+ 1.0 if re.search(r"^\s*[\{\[]", text) else 0.0,
159
+ 1.0 if re.search(r"[\{\}\[\]]", text) else 0.0,
160
+ # Character-class ratios (4)
161
+ alpha, digit, max(symbol, 0.0), space,
162
+ # Code statistics (4)
163
+ len(re.findall(r"\b(def|class|import|return|for|while)\b", text)) / n,
164
+ float(text.count("(") - text.count(")")),
165
+ (text.count(";")) / max(text.count("\n") + 1, 1),
166
+ 0.0, # indentation consistency (placeholder)
167
+ # Math statistics (3)
168
+ len(re.findall(r"[\u2211\u222b\u221a\u03c0\u00b1\u00d7\u00f7\u2264\u2265\u2260\u221e]", text)) / n,
169
+ float(len(re.findall(r"\$|\\\[|\\\]", text))),
170
+ float(len(re.findall(r"[\u03b1\u03b2\u03b3\u03b4\u03b8\u03bb\u03bc\u03c3\u03c6\u03c8\u03c9]", text))),
171
+ # Tables (4)
172
+ 1.0 if node.find("th") else 0.0, 1.0 if node.find("thead") else 0.0,
173
+ float(len(node.find_all("tr"))), float(len(node.find_all("td"))),
174
+ # Other block-level (3)
175
+ len(node.find_all("a")) / max(len(text.split()), 1),
176
+ float(max((len(w) for w in text.split()), default=0)),
177
+ len(re.findall(r"(.)\1{3,}", text)) / n,
178
+ ]
179
+ # Context window (10) -- pad with zeros to reach 42 dims
180
+ feats += [0.0] * (42 - len(feats))
181
+ return feats[:42]
182
+
183
+ def classify(self, node) -> Optional[SegmentType]:
184
+ if self.model is None:
185
+ return self._heuristic(node)
186
+ try:
187
+ import xgboost as xgb
188
+ dm = xgb.DMatrix([self._features(node)])
189
+ pred = int(self.model.predict(dm)[0])
190
+ return [None, SegmentType.CODE, SegmentType.MATH,
191
+ SegmentType.STRUCTURED][pred]
192
+ except Exception:
193
+ return self._heuristic(node)
194
+
195
+ @staticmethod
196
+ def _heuristic(node) -> Optional[SegmentType]:
197
+ text = node.get_text() or ""
198
+ if re.search(r"\$\$|\\begin\{|\\frac|\\sum", text):
199
+ return SegmentType.MATH
200
+ if re.search(r"\b(def|import|class|function)\b.*[\(\):{]", text):
201
+ return SegmentType.CODE
202
+ if re.search(r"^\s*[\{\[].*[\}\]]\s*$", text, re.S):
203
+ return SegmentType.STRUCTURED
204
+ return None
205
+
206
+
207
+ # --------------------------------------------------------------------------- #
208
+ def mask_dom(doc: Document) -> None:
209
+ """Execute the three-level cascade classification and inner-to-outer masking on the HTML DOM."""
210
+ try:
211
+ from bs4 import BeautifulSoup
212
+ except Exception as e:
213
+ log.warning("bs4 unavailable (%s); skipping DOM masking.", e)
214
+ return
215
+
216
+ soup = BeautifulSoup(doc.dom_html or doc.text, "lxml")
217
+ md = _level1_prescan(soup)
218
+ residual = _XGBResidualClassifier(XGB_AMBIGUOUS_BLOCK_MODEL)
219
+ alloc = SentinelAllocator(doc)
220
+
221
+ # Collect candidates by descending DOM depth -> inner-to-outer extraction.
222
+ all_nodes = list(soup.find_all(True))
223
+ all_nodes.sort(key=lambda n: len(list(n.parents)), reverse=True)
224
+
225
+ for node in all_nodes:
226
+ if node.decomposed or node.parent is None:
227
+ continue
228
+ name = (node.name or "").lower()
229
+ seg_type = _classify_node_level2(node, md)
230
+ if seg_type is None and name in _AMBIGUOUS:
231
+ seg_type = residual.classify(node)
232
+ if seg_type is None:
233
+ continue
234
+
235
+ # Strong-boundary tags: run a subtree scan before sealing. If they
236
+ # contain inner targets, do not stop descent here.
237
+ if name in _STRONG_BOUNDARY and name not in _STRUCT_CONTAINERS:
238
+ if _has_inner_target(node):
239
+ continue # let deeper nodes be masked first (inner-to-outer)
240
+
241
+ depth = len(list(node.parents))
242
+ placeholder = alloc.mask(seg_type, str(node), nesting_depth=depth,
243
+ tag=name)
244
+ node.replace_with(placeholder)
245
+
246
+ doc.text = soup.get_text() if soup.body is None else str(soup)
247
+ # DOM path uses the rendered text body directly.
248
+ doc.text = soup.get_text()
249
+
250
+
251
+ def _has_inner_target(node) -> bool:
252
+ for child in node.find_all(True, recursive=True):
253
+ cn = (child.name or "").lower()
254
+ if cn in {"math", "table", "ul", "ol", "dl"} or cn in _LEGACY_CODE_TAGS:
255
+ return True
256
+ classes = " ".join(child.get("class", []))
257
+ if _CODE_CLASS_RE.search(classes) or _MATH_CLASS_RE.search(classes):
258
+ return True
259
+ return False
repair_pipeline_package/masking/sentinel.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ PUA sentinel character allocation and LIFO segment storage.
3
+
4
+ The masking stage replaces code/math/structured segments with placeholders;
5
+ each placeholder is wrapped in PUA sentinel characters on both sides. Each
6
+ segment computes its SHA-256 at the moment of masking, and segments are
7
+ pushed onto a stack in "inner-to-outer" extraction order. Stage 10 restores
8
+ in LIFO (last-in-first-out) order, guaranteeing byte-level losslessness
9
+ across nested mixed-content structures.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import List
15
+
16
+ from ..config import TEXT_PLACEHOLDER_FMT
17
+ from ..document import Document, Segment, SegmentType
18
+
19
+
20
+ class SentinelAllocator:
21
+ """Allocates unique, human-readable PUA-wrapped placeholders for a single document."""
22
+
23
+ def __init__(self, doc: Document):
24
+ self.doc = doc
25
+ self._counters = {st: 0 for st in SegmentType}
26
+
27
+ def mask(self, seg_type: SegmentType, content: str,
28
+ nesting_depth: int = 0, **meta) -> str:
29
+ """Register a segment and return its placeholder string."""
30
+ idx = self.doc.next_segment_index()
31
+ kind = seg_type.value
32
+ placeholder = TEXT_PLACEHOLDER_FMT.format(kind=kind, idx=idx)
33
+ seg = Segment.make(seg_type, placeholder, content,
34
+ nesting_depth=nesting_depth, **meta)
35
+ self.doc.segments.append(seg)
36
+ self._counters[seg_type] += 1
37
+ return placeholder
38
+
39
+
40
+ def lifo_order(segments: List[Segment]) -> List[Segment]:
41
+ """
42
+ Return segments in LIFO restoration order: last-in-first-out.
43
+
44
+ Inner-to-outer extraction means inner segments (higher nesting_depth) are
45
+ masked first and pushed first; restoration must pop them last-in-first-out
46
+ so the innermost segments are restored first, naturally completing the
47
+ nested back-fill.
48
+ """
49
+ return list(reversed(segments))
repair_pipeline_package/masking/text_path.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Plain-text fallback path (Path B): four-step extraction flow.
3
+
4
+ Step 1 - Boundary Forcing: inject blank lines around known structural separators
5
+ Step 2 - Inline Extraction with Masking: inner-to-outer, physically extract
6
+ strongly-delimited inline content by priority
7
+ Step 3 - Empty-line Block Segmentation
8
+ Step 4 - Block-level Classification: heuristic + lightweight ML, two layers
9
+
10
+ Output is isomorphic to the DOM path (each block has a type label); code,
11
+ math, and structured segments are replaced with PUA placeholders.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from typing import List, Tuple
18
+
19
+ from ..config import TEXT_BLOCK_ML_MODEL, get_logger
20
+ from ..document import Document, SegmentType
21
+ from .sentinel import SentinelAllocator
22
+
23
+ log = get_logger(__name__)
24
+
25
+ # Boundary forcing: inject blank lines around these structural separators.
26
+ _BOUNDARY_PATTERNS = [
27
+ r"(```)", # fenced code marker
28
+ r"(</?(?:pre|code)[^>]*>)", # remaining <pre>/<code>
29
+ r"(\$\$)", r"(\\\[)", r"(\\\])", # display math
30
+ r"(\\begin\{[^}]+\})", r"(\\end\{[^}]+\})", # LaTeX environments
31
+ r"(^#{1,6}\s)", # Markdown headings
32
+ r"(^[-*_]{3,}\s*$)", # horizontal rule
33
+ r"(^\s*\|.*\|\s*$)", # structured-data rows (tables)
34
+ r"(^>>>|^In\[)", # REPL prompts
35
+ ]
36
+
37
+
38
+ def _boundary_forcing(text: str) -> str:
39
+ out = text
40
+ for pat in _BOUNDARY_PATTERNS:
41
+ out = re.sub(pat, r"\n\n\1\n\n", out, flags=re.M)
42
+ # Fold redundant newlines for idempotence.
43
+ out = re.sub(r"\n{3,}", "\n\n", out)
44
+ return out
45
+
46
+
47
+ # Step 2: inline-extraction priority (inner-to-outer: fenced/display first, then inline).
48
+ _INLINE_RULES: List[Tuple[SegmentType, re.Pattern]] = [
49
+ (SegmentType.CODE, re.compile(r"```.*?```", re.S)), # fenced code
50
+ (SegmentType.MATH, re.compile(r"\$\$.*?\$\$", re.S)), # display math
51
+ (SegmentType.MATH, re.compile(r"\\\[.*?\\\]", re.S)),
52
+ (SegmentType.CODE, re.compile(r"<pre[^>]*>.*?</pre>", re.S | re.I)),
53
+ (SegmentType.CODE, re.compile(r"<code[^>]*>.*?</code>", re.S | re.I)),
54
+ (SegmentType.MATH, re.compile(r"\\\(.*?\\\)", re.S)), # inline math
55
+ (SegmentType.CODE, re.compile(r"`[^`\n]+`")), # inline code
56
+ ]
57
+
58
+
59
+ def _inline_extract(text: str, alloc: SentinelAllocator) -> str:
60
+ out = text
61
+ depth = 100 # inline content gets higher nesting_depth so LIFO restores it first
62
+ for seg_type, pat in _INLINE_RULES:
63
+ def _sub(m, _st=seg_type):
64
+ ph = alloc.mask(_st, m.group(0), nesting_depth=depth)
65
+ return ph
66
+ out = pat.sub(_sub, out)
67
+ depth -= 1
68
+ return out
69
+
70
+
71
+ _EMPTY_LINE_SPLIT = re.compile(r"\n[\t\u00a0]*\n+")
72
+
73
+
74
+ def _segment_blocks(text: str) -> List[str]:
75
+ return [b for b in _EMPTY_LINE_SPLIT.split(text) if b.strip()]
76
+
77
+
78
+ # Step 4: block-level classification features
79
+ _CODE_KW = re.compile(r"\b(def|class|import|return|for|while|function|var|"
80
+ r"public|private|#include|println|System\.)\b")
81
+ _LATEX = re.compile(r"\\frac|\\sum|\\int|\$.+?\$|\\begin|\\alpha|\\beta")
82
+ _ARTICLES = re.compile(r"\b(a|an|the|and|but|or|is|are|was|were)\b", re.I)
83
+
84
+
85
+ class _BlockClassifier:
86
+ """Two-layer heuristic + lightweight ML block-level classifier."""
87
+
88
+ def __init__(self, model_path: str):
89
+ self.model = None
90
+ try:
91
+ import lightgbm as lgb # noqa
92
+ self.model = lgb.Booster(model_file=model_path)
93
+ log.info("Loaded text block LGBM classifier: %s", model_path)
94
+ except Exception as e:
95
+ log.warning("Text block ML classifier unavailable (%s); "
96
+ "heuristic-only.", e)
97
+
98
+ @staticmethod
99
+ def _line_feats(block: str):
100
+ lines = block.splitlines() or [block]
101
+ n = max(len(lines), 1)
102
+ latex_density = sum(bool(_LATEX.search(l)) for l in lines) / n
103
+ code_density = sum(bool(_CODE_KW.search(l)) for l in lines) / n
104
+ prose_density = sum(bool(_ARTICLES.search(l)) for l in lines) / n
105
+ special = sum(c in "\\${}|" for c in block) / max(len(block), 1)
106
+ return latex_density, code_density, prose_density, special
107
+
108
+ def classify(self, block: str) -> SegmentType:
109
+ latex_d, code_d, prose_d, special = self._line_feats(block)
110
+ # Layer 1: strong heuristic match (paper-specified thresholds)
111
+ if latex_d > 0.30:
112
+ return SegmentType.MATH
113
+ if code_d > 0.25:
114
+ return SegmentType.CODE
115
+ if prose_d > 0.60 and special < 0.05:
116
+ return SegmentType.PROSE
117
+ if re.match(r"^\s*\|.*\|", block) or re.match(r"^\s*[\{\[]", block):
118
+ return SegmentType.STRUCTURED
119
+ # Layer 2: lightweight ML handles ambiguous blocks
120
+ if self.model is not None:
121
+ try:
122
+ pred = int(round(float(self.model.predict([[latex_d, code_d,
123
+ prose_d, special]])[0])))
124
+ return [SegmentType.PROSE, SegmentType.CODE, SegmentType.MATH,
125
+ SegmentType.STRUCTURED][min(max(pred, 0), 3)]
126
+ except Exception:
127
+ pass
128
+ return SegmentType.PROSE
129
+
130
+
131
+ def mask_text(doc: Document) -> None:
132
+ """Main entry for the plain-text path."""
133
+ alloc = SentinelAllocator(doc)
134
+ text = _boundary_forcing(doc.text)
135
+ text = _inline_extract(text, alloc) # strongly-delimited inline content already masked
136
+
137
+ blocks = _segment_blocks(text)
138
+ clf = _BlockClassifier(TEXT_BLOCK_ML_MODEL)
139
+
140
+ rebuilt: List[str] = []
141
+ for blk in blocks:
142
+ # Skip blocks containing only placeholders (already handled during inline extraction)
143
+ bt = clf.classify(blk)
144
+ if bt in (SegmentType.CODE, SegmentType.MATH, SegmentType.STRUCTURED):
145
+ ph = alloc.mask(bt, blk, nesting_depth=0)
146
+ rebuilt.append(ph)
147
+ else:
148
+ rebuilt.append(blk)
149
+
150
+ sha_before = doc.text
151
+ doc.apply(stage=2, operation="mask_text_path",
152
+ new_text="\n\n".join(rebuilt),
153
+ note=f"masked {len(doc.segments)} segments (text path)")
repair_pipeline_package/pipeline.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pipeline orchestrator.
3
+
4
+ Execution order = the paper's ten-stage order + a single mandatory modification:
5
+ move "mixed-content masking" (Stage 3) before "ftfy atomic repair" (Stage 2).
6
+
7
+ Paper canonical order: 1 encoding -> 2 ftfy -> 3 masking -> 4 artifacts ->
8
+ 5 line-level -> 6 character -> 7 whitespace ->
9
+ 8 OCR -> 9 quality -> 10 restore
10
+ This pipeline's order: 1 encoding -> 3 masking -> 2 ftfy -> 4 artifacts ->
11
+ 5 line-level -> 6 character -> 7 whitespace -> 8 OCR ->
12
+ [type-specific repair + pre-restore validation] ->
13
+ 9 quality -> 10 restore
14
+
15
+ Type-specific repair (repair of code/math/structured segments + pre-restore
16
+ type-specific validation) runs after all text-level repairs are complete on
17
+ the masked text and before quality validation, on each segment
18
+ independently, ahead of the Stage 10 LIFO restore.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Optional
24
+
25
+ from .config import get_logger
26
+ from .document import Document
27
+ from .stages import (stage01_encoding, stage02_masking, stage03_ftfy,
28
+ stage04_artifacts, stage05_linelevel, stage06_charnorm,
29
+ stage07_whitespace, stage08_ocr, stage09_quality,
30
+ stage10_restore)
31
+ from .typed_repair import repair_and_validate_segments
32
+
33
+ log = get_logger(__name__)
34
+
35
+
36
+ class RepairPipeline:
37
+ """Ten-stage corpus data repair pipeline (masking-first variant)."""
38
+
39
+ # (execution index, paper-stage number, name, function) — used for log/audit display
40
+ EXECUTION_PLAN = [
41
+ ("1", 1, "Dual-encoding detection and repair", stage01_encoding.run),
42
+ ("2", 2, "Mixed-content masking [moved forward]", stage02_masking.run), # moved earlier
43
+ ("3", 3, "ftfy atomic repair", stage03_ftfy.run), # moved later
44
+ ("4", 4, "Structural artifact removal", stage04_artifacts.run),
45
+ ("5", 5, "Line-level repair", stage05_linelevel.run),
46
+ ("6", 6, "Character-level normalization", stage06_charnorm.run),
47
+ ("7", 7, "Whitespace normalization", stage07_whitespace.run),
48
+ ("8", 8, "OCR detection and correction", stage08_ocr.run),
49
+ # -- type-specific repair + pre-restore validation (on masked segments) --
50
+ ("9", 9, "Masked-text quality validation", stage09_quality.run),
51
+ ("10", 10, "LIFO restore and integrity check", stage10_restore.run),
52
+ ]
53
+
54
+ def run(self,
55
+ data,
56
+ *,
57
+ http_charset: Optional[str] = None,
58
+ html_meta_charset: Optional[str] = None,
59
+ has_dom: bool = False,
60
+ dom_html: Optional[str] = None,
61
+ source_hint: Optional[str] = None) -> Document:
62
+ """
63
+ Process a single document.
64
+
65
+ data: bytes (raw byte stream, decoded by Stage 1) or str (pre-decoded text).
66
+ """
67
+ doc = Document(
68
+ http_charset=http_charset,
69
+ html_meta_charset=html_meta_charset,
70
+ has_dom=has_dom or bool(dom_html),
71
+ dom_html=dom_html,
72
+ source_hint=source_hint,
73
+ )
74
+ if isinstance(data, bytes):
75
+ doc.raw_bytes = data
76
+ else:
77
+ doc.text = data
78
+ doc.original_text = data
79
+
80
+ for exec_no, paper_stage, name, fn in self.EXECUTION_PLAN:
81
+ doc.snapshot(paper_stage)
82
+ log.info("[exec %s / paper-stage %d] %s", exec_no, paper_stage, name)
83
+ try:
84
+ fn(doc)
85
+ except Exception as e:
86
+ log.exception("stage %s (%s) failed: %s", exec_no, name, e)
87
+ # A single stage failure must not abort the whole pipeline:
88
+ # roll back this stage and continue with the next.
89
+ doc.rollback(paper_stage)
90
+
91
+ # After OCR (execution index 8) and before quality validation,
92
+ # run type-specific repair + pre-restore validation.
93
+ if exec_no == "8" and not doc.discarded:
94
+ log.info("[typed-repair] type-specific segment repair + pre-restore validation")
95
+ try:
96
+ repair_and_validate_segments(doc)
97
+ except Exception as e:
98
+ log.exception("typed repair failed: %s", e)
99
+
100
+ return doc
101
+
102
+ def run_text(self, text: str, **kwargs) -> str:
103
+ """Convenience interface: input text, return final repaired text."""
104
+ return self.run(text, **kwargs).text
repair_pipeline_package/quality/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .ensemble import QualityEnsemble
2
+
3
+ __all__ = ["QualityEnsemble"]
repair_pipeline_package/quality/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (238 Bytes). View file
 
repair_pipeline_package/quality/__pycache__/ensemble.cpython-310.pyc ADDED
Binary file (8.72 kB). View file
 
repair_pipeline_package/quality/ensemble.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Six-tool complementary quality-scoring ensemble (paper Section 6.2 / Table 8.8 / Table 8.9).
3
+
4
+ Final selection (with GPU-required tools removed; composite score 0.896):
5
+ DCLM_FastText + LanguageTool + NeMo-DataTrove-DataJuicer joint-metric
6
+ system + ftfy + NLTK + unicodedata.
7
+
8
+ Aggregation strategy: each structural anomaly is scored exclusively by its
9
+ single best-performing tool (max-aggregation; tools cooperate, do not
10
+ compete), rather than a weighted average. The document is emitted with a
11
+ binary pass/reject signal.
12
+
13
+ Fully CPU; operates on the masked text (code/math/structured segments remain
14
+ PUA placeholders).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ import unicodedata
21
+ from typing import Dict
22
+
23
+ from ..config import (DCLM_FASTTEXT_MODEL, QUALITY_PASS_THRESHOLD, get_logger)
24
+
25
+ log = get_logger(__name__)
26
+
27
+
28
+ # --------------------------------------------------------------------------- #
29
+ # Per-tool: return a [0,1] "cleanness" score (higher = cleaner)
30
+ # --------------------------------------------------------------------------- #
31
+ class _DclmFastText:
32
+ """DCLM_FastText: curly quotes, PDF-extraction artifacts, boilerplate, nav-bar templates."""
33
+ def __init__(self):
34
+ self.model = None
35
+ try:
36
+ import fasttext
37
+ self.model = fasttext.load_model(DCLM_FASTTEXT_MODEL)
38
+ log.info("Loaded DCLM fastText: %s", DCLM_FASTTEXT_MODEL)
39
+ except Exception as e:
40
+ log.warning("DCLM fastText unavailable (%s); heuristic fallback.", e)
41
+
42
+ def score(self, text: str) -> float:
43
+ if self.model is not None:
44
+ try:
45
+ labels, probs = self.model.predict(text.replace("\n", " ")[:4000])
46
+ p = float(probs[0])
47
+ return p if "__label__hq" in labels[0] or "__label__1" in labels[0] \
48
+ else 1.0 - p
49
+ except Exception:
50
+ pass
51
+ # Fallback heuristic: curly-quote / nav-separator density
52
+ curly = len(re.findall(r"[\u2018\u2019\u201c\u201d]", text))
53
+ nav = len(re.findall(r"\s\|\s|\u00bb|\u203a", text))
54
+ n = max(len(text), 1)
55
+ return max(0.0, 1.0 - (curly + nav) / n * 20)
56
+
57
+
58
+ class _LanguageTool:
59
+ """LanguageTool: full-width characters, basic control characters, residual HTML."""
60
+ def __init__(self):
61
+ self.tool = None
62
+ try:
63
+ import language_tool_python
64
+ self.tool = language_tool_python.LanguageTool("en-US")
65
+ except Exception as e:
66
+ log.warning("LanguageTool unavailable (%s); heuristic fallback.", e)
67
+
68
+ def score(self, text: str) -> float:
69
+ fullwidth = len(re.findall(r"[\uff01-\uff5e\u3000]", text))
70
+ html_resid = len(re.findall(r"</?[a-z][a-z0-9]*\b[^>]*>|&[a-z]+;", text, re.I))
71
+ ctrl = len(re.findall(r"[\x00-\x08\x0b\x0c\x0e-\x1f]", text))
72
+ n = max(len(text), 1)
73
+ return max(0.0, 1.0 - (fullwidth + html_resid * 3 + ctrl * 5) / n * 15)
74
+
75
+
76
+ class _NemoDataTroveDataJuicer:
77
+ """NeMo-DataTrove-DataJuicer joint-metric system (rule/statistic-based; the strongest general-purpose component).
78
+ Targets: mojibake, hyphenated wraps, intra-word newlines, chaotic
79
+ tabs/spaces, inconsistent UTF-8 mojibake, residual encoding artifacts,
80
+ zero-width characters, soft hyphens."""
81
+ def score(self, text: str) -> float:
82
+ n = max(len(text), 1)
83
+ replacement = text.count("\uFFFD")
84
+ zerowidth = len(re.findall(r"[\u200b-\u200d\u2060\ufeff]", text))
85
+ soft_hyphen = text.count("\u00ad")
86
+ mojibake = len(re.findall(r"\u00c3.|\u00e2\u20ac.|\u00c2.", text)) # typical multi-pass mojibake patterns
87
+ tabspace = len(re.findall(r"\t \t| \t ", text))
88
+ mid_word_break = len(re.findall(r"[A-Za-z]\n[a-z]", text)) # intra-word newline
89
+ bad = (replacement * 4 + zerowidth * 3 + soft_hyphen * 2
90
+ + mojibake * 3 + tabspace + mid_word_break)
91
+ return max(0.0, 1.0 - bad / n * 12)
92
+
93
+
94
+ class _Nltk:
95
+ """NLTK: multi-pass encoding errors, replacement-character mojibake, undecomposed
96
+ ligatures, mixed line endings, NFD residue, private-use-area characters, form-feed."""
97
+ def __init__(self):
98
+ self.ok = False
99
+ try:
100
+ import nltk # noqa
101
+ from nltk.tokenize import word_tokenize # noqa
102
+ self.ok = True
103
+ except Exception as e:
104
+ log.warning("NLTK unavailable (%s); heuristic fallback.", e)
105
+
106
+ def score(self, text: str) -> float:
107
+ n = max(len(text), 1)
108
+ ligatures = len(re.findall(r"[\ufb00-\ufb06]", text)) # ff fi fl ffi ffl etc.
109
+ mixed_eol = 1 if ("\r\n" in text and "\n" in text.replace("\r\n", "")) else 0
110
+ nfd = 0
111
+ try:
112
+ nfd = sum(1 for c in text if unicodedata.combining(c))
113
+ except Exception:
114
+ pass
115
+ pua = len(re.findall(r"[\ue000-\uefff]", text)) # native PUA (sentinel block is at F000+, excluded)
116
+ formfeed = text.count("\x0c")
117
+ bad = ligatures * 2 + mixed_eol * 5 + nfd + pua * 2 + formfeed * 3
118
+ return max(0.0, 1.0 - bad / n * 10)
119
+
120
+
121
+ class _UnicodeData:
122
+ """unicodedata: C1 control characters, isolated surrogates, residual control characters, BOM."""
123
+ def score(self, text: str) -> float:
124
+ n = max(len(text), 1)
125
+ c1 = len(re.findall(r"[\u0080-\u009f]", text))
126
+ bom = text.count("\ufeff")
127
+ surrogate = len(re.findall(r"[\ud800-\udfff]", text))
128
+ ctrl = sum(1 for c in text if unicodedata.category(c) == "Cc"
129
+ and c not in "\t\n\r")
130
+ bad = c1 * 4 + bom * 2 + surrogate * 5 + ctrl * 3
131
+ return max(0.0, 1.0 - bad / n * 12)
132
+
133
+
134
+ class _Ftfy:
135
+ """ftfy reverse-wrapped as a detector: inter-word spurious newlines, 0xA0 -> space, BBCode tags.
136
+ Uses the edit-distance between pre- and post-repair text as a quality
137
+ signal (larger distance = dirtier)."""
138
+ def score(self, text: str) -> float:
139
+ try:
140
+ import ftfy
141
+ fixed = ftfy.fix_text(text)
142
+ except Exception:
143
+ return 1.0
144
+ # Levenshtein approximation: use character-difference ratio
145
+ if not text:
146
+ return 1.0
147
+ diff = sum(1 for a, b in zip(text, fixed) if a != b) + abs(len(text) - len(fixed))
148
+ return max(0.0, 1.0 - diff / max(len(text), 1) * 4)
149
+
150
+
151
+ # --------------------------------------------------------------------------- #
152
+ # Ensemble: each structural anomaly class -> best tool (Table 8.9 assignment)
153
+ # --------------------------------------------------------------------------- #
154
+ class QualityEnsemble:
155
+ def __init__(self):
156
+ self.dclm = _DclmFastText()
157
+ self.lt = _LanguageTool()
158
+ self.nemo = _NemoDataTroveDataJuicer()
159
+ self.nltk = _Nltk()
160
+ self.uni = _UnicodeData()
161
+ self.ftfy = _Ftfy()
162
+
163
+ def evaluate(self, text: str) -> Dict[str, float]:
164
+ """Return per-tool subscores in their assigned categories plus the max-aggregation composite."""
165
+ scores = {
166
+ "nemo": self.nemo.score(text),
167
+ "nltk": self.nltk.score(text),
168
+ "unicodedata": self.uni.score(text),
169
+ "dclm_fasttext": self.dclm.score(text),
170
+ "ftfy": self.ftfy.score(text),
171
+ "languagetool": self.lt.score(text),
172
+ }
173
+ # Engineering approximation of "pick the best tool per anomaly":
174
+ # composite cleanness = geometric mean of per-tool subscores (any
175
+ # collapsed category drags the total down), which matches the
176
+ # "weakest link sets the floor" semantics better than a weighted average.
177
+ import math
178
+ vals = [max(v, 1e-3) for v in scores.values()]
179
+ composite = math.exp(sum(math.log(v) for v in vals) / len(vals))
180
+ scores["composite"] = composite
181
+ return scores
182
+
183
+ def verify(self, text: str) -> tuple[bool, float, Dict[str, float]]:
184
+ scores = self.evaluate(text)
185
+ composite = scores["composite"]
186
+ return composite >= QUALITY_PASS_THRESHOLD, composite, scores
repair_pipeline_package/run.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Command-line entry point.
4
+
5
+ Usage:
6
+ # Process a single file (Stage 1 auto-decodes the byte stream)
7
+ python -m repair_pipeline.run input.html -o out.jsonl
8
+
9
+ # Process every file under a directory
10
+ python -m repair_pipeline.run ./corpus_dir -o out.jsonl
11
+
12
+ # Mark the source as OCR / provide an HTTP charset
13
+ python -m repair_pipeline.run scan.txt --source-hint ocr --http-charset utf-8
14
+
15
+ Output is JSONL, one document per line:
16
+ {path, encoding, quality_passed, quality_score, discarded, n_segments,
17
+ audit:[...], text}
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import dataclasses
24
+ import json
25
+ import os
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ from .pipeline import RepairPipeline
30
+
31
+
32
+ def _iter_inputs(path: Path):
33
+ if path.is_dir():
34
+ for p in sorted(path.rglob("*")):
35
+ if p.is_file():
36
+ yield p
37
+ else:
38
+ yield path
39
+
40
+
41
+ def _doc_to_record(path: Path, doc) -> dict:
42
+ return {
43
+ "path": str(path),
44
+ "encoding": doc.detected_encoding,
45
+ "quality_passed": doc.quality_passed,
46
+ "quality_score": doc.quality_score,
47
+ "discarded": doc.discarded,
48
+ "discard_reason": doc.discard_reason,
49
+ "n_segments": len(doc.segments),
50
+ "audit": [dataclasses.asdict(a) for a in doc.audit],
51
+ "text": doc.text,
52
+ }
53
+
54
+
55
+ def main(argv=None) -> int:
56
+ ap = argparse.ArgumentParser(description="Ten-stage corpus data repair pipeline (masking-first variant)")
57
+ ap.add_argument("input", help="input file or directory")
58
+ ap.add_argument("-o", "--output", default="-", help="output JSONL path (defaults to stdout)")
59
+ ap.add_argument("--has-dom", action="store_true", help="input retains HTML DOM")
60
+ ap.add_argument("--http-charset", default=None)
61
+ ap.add_argument("--source-hint", default=None, help="e.g. ocr / rfc / email")
62
+ args = ap.parse_args(argv)
63
+
64
+ pipe = RepairPipeline()
65
+ out = sys.stdout if args.output == "-" else open(args.output, "w", encoding="utf-8")
66
+ try:
67
+ for p in _iter_inputs(Path(args.input)):
68
+ raw = p.read_bytes()
69
+ is_html = p.suffix.lower() in (".html", ".htm")
70
+ doc = pipe.run(
71
+ raw,
72
+ http_charset=args.http_charset,
73
+ has_dom=args.has_dom or is_html,
74
+ dom_html=raw.decode("utf-8", "replace") if (args.has_dom or is_html) else None,
75
+ source_hint=args.source_hint,
76
+ )
77
+ out.write(json.dumps(_doc_to_record(p, doc), ensure_ascii=False) + "\n")
78
+ finally:
79
+ if out is not sys.stdout:
80
+ out.close()
81
+ return 0
82
+
83
+
84
+ if __name__ == "__main__":
85
+ raise SystemExit(main())
repair_pipeline_package/stages/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stage module collection. Filenames follow the paper's canonical stage numbering; execution order is set by the pipeline."""
2
+
3
+ from . import (stage01_encoding, stage02_masking, stage03_ftfy,
4
+ stage04_artifacts, stage05_linelevel, stage06_charnorm,
5
+ stage07_whitespace, stage08_ocr, stage09_quality,
6
+ stage10_restore)
7
+
8
+ __all__ = [
9
+ "stage01_encoding", "stage02_masking", "stage03_ftfy",
10
+ "stage04_artifacts", "stage05_linelevel", "stage06_charnorm",
11
+ "stage07_whitespace", "stage08_ocr", "stage09_quality",
12
+ "stage10_restore",
13
+ ]
repair_pipeline_package/stages/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (599 Bytes). View file
 
repair_pipeline_package/stages/__pycache__/stage01_encoding.cpython-310.pyc ADDED
Binary file (3.7 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage02_masking.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage03_ftfy.cpython-310.pyc ADDED
Binary file (2.8 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage04_artifacts.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage05_linelevel.cpython-310.pyc ADDED
Binary file (4.84 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage06_charnorm.cpython-310.pyc ADDED
Binary file (2.26 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage07_whitespace.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage08_ocr.cpython-310.pyc ADDED
Binary file (6.47 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage09_quality.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
repair_pipeline_package/stages/__pycache__/stage10_restore.cpython-310.pyc ADDED
Binary file (2.32 kB). View file
 
repair_pipeline_package/stages/stage01_encoding.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 1: dual-encoding detection and repair (paper Section 7.1).
3
+
4
+ - Dual-detector voting fusion: chardet 7.x + charset-normalizer
5
+ (agreement -> adopt; disagreement -> charset-normalizer wins)
6
+ - Five-level priority cascade: BOM -> HTTP Content-Type -> HTML <meta charset>
7
+ -> chardet statistical detection -> Windows-1252 fallback
8
+ - English fast path: UTF-8 -> Windows-1252 cascaded decode (~100x speedup)
9
+
10
+ Outputs clean Unicode text as the input to all later stages.
11
+ NOTE: this stage is the bearer of the "encoding-first" constraint; it does
12
+ NOT strip control characters or apply NFC.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import codecs
18
+ import re
19
+ from typing import Optional
20
+
21
+ from ..config import get_logger
22
+ from ..document import Document, sha256_text
23
+
24
+ log = get_logger(__name__)
25
+
26
+ STAGE = 1
27
+
28
+ _BOM_TABLE = [
29
+ (codecs.BOM_UTF8, "utf-8-sig"),
30
+ (codecs.BOM_UTF32_LE, "utf-32"),
31
+ (codecs.BOM_UTF32_BE, "utf-32"),
32
+ (codecs.BOM_UTF16_LE, "utf-16"),
33
+ (codecs.BOM_UTF16_BE, "utf-16"),
34
+ ]
35
+
36
+ _META_CHARSET_RE = re.compile(
37
+ rb"""<meta[^>]+charset\s*=\s*["']?\s*([a-zA-Z0-9_\-]+)""", re.I)
38
+
39
+
40
+ def _detect_bom(raw: bytes) -> Optional[str]:
41
+ for bom, enc in _BOM_TABLE:
42
+ if raw.startswith(bom):
43
+ return enc
44
+ return None
45
+
46
+
47
+ def _detect_meta_charset(raw: bytes) -> Optional[str]:
48
+ m = _META_CHARSET_RE.search(raw[:4096])
49
+ return m.group(1).decode("ascii", "ignore") if m else None
50
+
51
+
52
+ def _vote_detectors(raw: bytes) -> Optional[str]:
53
+ """Voting fusion between chardet and charset-normalizer."""
54
+ chardet_enc = csn_enc = None
55
+ try:
56
+ import chardet
57
+ r = chardet.detect(raw)
58
+ chardet_enc = (r.get("encoding") or "").lower() or None
59
+ except Exception:
60
+ pass
61
+ try:
62
+ from charset_normalizer import from_bytes
63
+ best = from_bytes(raw).best()
64
+ csn_enc = best.encoding if best is not None else None
65
+ except Exception:
66
+ pass
67
+
68
+ if chardet_enc and csn_enc:
69
+ if chardet_enc == csn_enc:
70
+ return chardet_enc
71
+ return csn_enc # disagreement -> charset-normalizer wins
72
+ return csn_enc or chardet_enc
73
+
74
+
75
+ def _english_fast_path(raw: bytes) -> Optional[str]:
76
+ """UTF-8 -> Windows-1252 cascade: enabled when ASCII ratio > 95%."""
77
+ sample = raw[:65536]
78
+ if not sample:
79
+ return None
80
+ ascii_ratio = sum(b < 0x80 for b in sample) / len(sample)
81
+ if ascii_ratio < 0.95:
82
+ return None
83
+ try:
84
+ raw.decode("utf-8")
85
+ return "utf-8"
86
+ except UnicodeDecodeError:
87
+ return "cp1252" # Windows-1252 never raises on arbitrary bytes
88
+
89
+
90
+ def detect_encoding(doc: Document) -> str:
91
+ raw = doc.raw_bytes
92
+ # 1) BOM
93
+ enc = _detect_bom(raw)
94
+ if enc:
95
+ return enc
96
+ # 2) HTTP Content-Type charset
97
+ if doc.http_charset:
98
+ return doc.http_charset
99
+ # 3) HTML <meta charset>
100
+ meta = doc.html_meta_charset or _detect_meta_charset(raw)
101
+ if meta:
102
+ doc.html_meta_charset = meta
103
+ return meta
104
+ # English fast path (optional optimization in place of statistical detection)
105
+ fast = _english_fast_path(raw)
106
+ if fast:
107
+ return fast
108
+ # 4) statistical detection (dual-detector vote)
109
+ voted = _vote_detectors(raw)
110
+ if voted:
111
+ return voted
112
+ # 5) Windows-1252 fallback
113
+ return "cp1252"
114
+
115
+
116
+ def run(doc: Document) -> Document:
117
+ if not doc.raw_bytes and doc.text:
118
+ # already text input (e.g. upstream pre-decoded): skip decoding and
119
+ # just register the original text.
120
+ doc.original_text = doc.text
121
+ return doc
122
+
123
+ enc = detect_encoding(doc)
124
+ doc.detected_encoding = enc
125
+ try:
126
+ text = doc.raw_bytes.decode(enc, errors="replace")
127
+ except (LookupError, UnicodeDecodeError):
128
+ text = doc.raw_bytes.decode("cp1252", errors="replace")
129
+ enc = "cp1252"
130
+ doc.detected_encoding = enc
131
+
132
+ sha_before = sha256_text(doc.text)
133
+ doc.text = text
134
+ doc.original_text = text # rollback basis
135
+ doc.record(STAGE, f"decode[{enc}]", sha_before,
136
+ note=f"decoded {len(doc.raw_bytes)} bytes as {enc}")
137
+ return doc
repair_pipeline_package/stages/stage02_masking.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Execution-order Stage 2 / paper canonical Stage 3: hierarchical priority
3
+ detection routing and masking for mixed content (paper Chapter 4).
4
+
5
+ - DOM-priority path (when an HTML DOM is available): three-level cascade (Level 1/2/3)
6
+ - Plain-text fallback path (text-only input): four-step extraction
7
+
8
+ Detected code/math/structured segments are replaced with PUA sentinel
9
+ placeholders, extracted in "inner-to-outer" order, registered with their
10
+ SHA-256 hashes, and queued for Stage 10 LIFO restoration.
11
+
12
+ * Mandatory modification: this stage is moved to run before ftfy (Stage 2).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from ..config import get_logger
18
+ from ..document import Document, sha256_text
19
+ from ..masking import mask_dom, mask_text
20
+
21
+ log = get_logger(__name__)
22
+
23
+ STAGE = 3
24
+
25
+
26
+ def run(doc: Document) -> Document:
27
+ sha_before = sha256_text(doc.text)
28
+ before_segs = len(doc.segments)
29
+
30
+ if doc.has_dom and (doc.dom_html or "<" in doc.text):
31
+ mask_dom(doc)
32
+ else:
33
+ mask_text(doc)
34
+
35
+ n = len(doc.segments) - before_segs
36
+ doc.record(STAGE, "hierarchical_routing_mask", sha_before,
37
+ note=f"masked {n} non-prose segments "
38
+ f"({'DOM' if doc.has_dom else 'text'} path)")
39
+ return doc
repair_pipeline_package/stages/stage03_ftfy.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Execution-order Stage 3 / paper canonical Stage 2: ftfy atomic repair
3
+ (paper Section 7.1).
4
+
5
+ Seven key configuration flags:
6
+ (1) fix_encoding=True repair multi-pass mojibake decoding
7
+ (2) fix_c1_controls=True reinterpret C1 control bytes via Windows-1252
8
+ (must run before NFC)
9
+ (3) fix_latin_ligatures=True split Latin ligatures (fi -> fi)
10
+ (4) fix_character_width=True full-width Latin/digits/punctuation -> half-width
11
+ (English-domain default)
12
+ (5) fix_line_breaks=True CR/CRLF/LS/PS -> \n
13
+ (6) remove_control_chars=True remove C0/DEL (keep \n and \t)
14
+ (7) normalization='NFC' NFC normalization (NOT NFKC, which would damage
15
+ math symbols; see paper Damage Matrix)
16
+ Also: uncurl_quotes=False (per the Damage Matrix, curly->straight quotes is a
17
+ lossy transform; we keep it disabled by default).
18
+
19
+ * This pipeline's mandatory modification: this stage runs AFTER
20
+ "mixed-content masking". Code/math/structured segments are by then PUA
21
+ placeholders (U+F000 region) that ftfy will not touch:
22
+ - remove_control_chars only removes C0/DEL, not PUA.
23
+ - NFC does not change PUA; fix_encoding works on byte patterns and PUA is
24
+ valid Unicode unaffected by it.
25
+ Mojibake/ligature repair on those segments is delegated to ftfy.fix_text
26
+ inside typed_repair instead.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ from ..config import get_logger
32
+ from ..document import Document, sha256_text
33
+
34
+ log = get_logger(__name__)
35
+
36
+ STAGE = 2
37
+
38
+ _FTFY_CONFIG = dict(
39
+ fix_encoding=True,
40
+ fix_c1_controls=True,
41
+ fix_latin_ligatures=True,
42
+ fix_character_width=True,
43
+ fix_line_breaks=True,
44
+ remove_control_chars=True,
45
+ uncurl_quotes=False,
46
+ normalization="NFC",
47
+ )
48
+
49
+
50
+ def run(doc: Document) -> Document:
51
+ try:
52
+ import ftfy
53
+ except Exception as e:
54
+ log.warning("ftfy unavailable (%s); stage 2 skipped.", e)
55
+ return doc
56
+
57
+ sha_before = sha256_text(doc.text)
58
+
59
+ # Prefer TextFixerConfig (ftfy>=6); otherwise fall back to keyword args.
60
+ try:
61
+ from ftfy import TextFixerConfig
62
+ cfg = TextFixerConfig(
63
+ unescape_html=False, # masked prose must not be force-decoded as HTML
64
+ **{k: v for k, v in _FTFY_CONFIG.items()},
65
+ )
66
+ fixed = ftfy.fix_text(doc.text, config=cfg)
67
+ except Exception:
68
+ fixed = ftfy.fix_text(doc.text, **_FTFY_CONFIG)
69
+
70
+ doc.apply(STAGE, "ftfy.fix_text(7-config,NFC)", fixed,
71
+ note="encoding/c1/ligature/width/linebreak/ctrl + NFC")
72
+ return doc
repair_pipeline_package/stages/stage04_artifacts.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 4: structural-artifact removal (paper Section 7.2).
3
+
4
+ Removes artifacts with different origins but shared surface signatures
5
+ (without touching prose):
6
+ - BBCode forum tags ([b] [url] [quote] ...), phpBB/vBulletin remnants
7
+ - HTML4-era deprecated tags (<font> <center> <marquee> ...) + residual entities
8
+ - navigation breadcrumbs
9
+ - cookie consent banners (two layers: DOM-level CSS selectors + cross-document
10
+ repeated lines + cookie-vocabulary fallback)
11
+
12
+ Position constraint: between masking (Stage 3) and line-level repair (Stage 5).
13
+ Cannot run after line-level repair, since artifact boundaries would otherwise
14
+ contaminate sentence/line-break features.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import html
20
+ import re
21
+
22
+ from ..config import get_logger
23
+ from ..document import Document, sha256_text
24
+
25
+ log = get_logger(__name__)
26
+
27
+ STAGE = 4
28
+
29
+ # BBCode: paired open/close tags
30
+ _BBCODE = re.compile(r"\[/?(?:b|i|u|s|url|img|quote|code|color|size|list|"
31
+ r"\*|font|center|table|tr|td|youtube)(?:=[^\]]*)?\]", re.I)
32
+
33
+ # HTML4 deprecated tags
34
+ _DEPRECATED_HTML = re.compile(
35
+ r"</?(?:font|center|marquee|blink|big|strike|tt|nobr|spacer)\b[^>]*>", re.I)
36
+
37
+ # Navigation breadcrumbs: "Home > Products > ..." style
38
+ _BREADCRUMB = re.compile(
39
+ r"^\s*Home\s*(?:[»>›/|]\s*[\w \-]+){2,}\s*$", re.I | re.M)
40
+
41
+ # Cookie vocabulary (multilingual variants, simplified)
42
+ _COOKIE_VOCAB = re.compile(r"\bcookies?\b|consent|privacy policy", re.I)
43
+
44
+ # Known consent-manager container identifiers (simplified EasyList Cookie / IAB TCF)
45
+ _CONSENT_SELECTOR_IDS = re.compile(
46
+ r"(onetrust-banner-sdk|CybotCookiebotDialog|qc-cmp2-container|"
47
+ r"truste-consent-track)", re.I)
48
+
49
+ # Typical cookie-banner template phrases
50
+ _COOKIE_TEMPLATE = re.compile(
51
+ r"(we use cookies[^.\n]*\.?)|(accept all\b)|(reject all\b)|"
52
+ r"(manage preferences\b)|(this (?:web)?site uses cookies[^.\n]*\.?)", re.I)
53
+
54
+
55
+ def _remove_cookie_banners(doc: Document) -> str:
56
+ text = doc.text
57
+ # Layer 1: DOM-level (when raw HTML is present, prune by container id/class)
58
+ if doc.dom_html and _CONSENT_SELECTOR_IDS.search(doc.dom_html):
59
+ try:
60
+ from bs4 import BeautifulSoup
61
+ soup = BeautifulSoup(doc.dom_html, "lxml")
62
+ for sel in ["onetrust-banner-sdk", "CybotCookiebotDialog",
63
+ "truste-consent-track"]:
64
+ node = soup.find(id=sel)
65
+ if node:
66
+ node.decompose()
67
+ for cls in ["qc-cmp2-container"]:
68
+ for node in soup.find_all(class_=cls):
69
+ node.decompose()
70
+ except Exception:
71
+ pass
72
+ # Layer 2: template phrase + cookie-vocabulary fallback (per paragraph)
73
+ paras = re.split(r"\n\s*\n", text)
74
+ kept = []
75
+ for p in paras:
76
+ if _COOKIE_TEMPLATE.search(p) and _COOKIE_VOCAB.search(p):
77
+ continue # confirmed cookie template; drop the whole paragraph
78
+ kept.append(p)
79
+ return "\n\n".join(kept)
80
+
81
+
82
+ def run(doc: Document) -> Document:
83
+ sha_before = sha256_text(doc.text)
84
+ text = doc.text
85
+
86
+ # Iteratively un-escape multi-nested HTML entities first
87
+ # (prose only; segments are already masked).
88
+ prev = None
89
+ for _ in range(4):
90
+ nxt = html.unescape(text)
91
+ if nxt == text:
92
+ break
93
+ prev, text = text, nxt
94
+
95
+ text = _BBCODE.sub("", text)
96
+ text = _DEPRECATED_HTML.sub("", text)
97
+ text = _BREADCRUMB.sub("", text)
98
+
99
+ doc.text = text
100
+ text = _remove_cookie_banners(doc)
101
+
102
+ doc.apply(STAGE, "structural_artifact_removal", text,
103
+ note="bbcode/deprecated-html/breadcrumb/cookie-banner")
104
+ return doc
repair_pipeline_package/stages/stage05_linelevel.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 5: line-level repair (paper Section 6.1 line-level / Section 7).
3
+
4
+ Two defect classes are handled separately:
5
+ A. Hyphenated wraps (intra-word): end-of-line hyphen with letters on both
6
+ sides -> remove hyphen and join.
7
+ Compound words (e.g. "state-of-the-art") are dictionary-checked; only
8
+ dictionary-hit joins are accepted, otherwise the hyphen is preserved.
9
+ B. Illegal line breaks (inter-word): fixed-column hard wraps (72/80) cut
10
+ paragraphs -> stitch back into long lines.
11
+ Protections: blank-line paragraph boundaries, list items / numbered /
12
+ headings, line-length statistical diagnostic.
13
+
14
+ Tools: Textunwrap-style rules as the main tool, custom spaCy model as a
15
+ supplementary validator for complex boundaries.
16
+ Position constraint: between structural-artifact removal (Stage 4) and
17
+ character-level normalization (Stage 6), so line-length stats are not
18
+ contaminated by BBCode tags or full-width spaces.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import re
24
+ from typing import Optional, Set
25
+
26
+ from ..config import (ENGLISH_WORDLIST, FIXED_COLUMN_TOL, FIXED_COLUMN_WIDTHS,
27
+ SPACY_FALLBACK_PIPE, SPACY_LINEBREAK_MODEL, get_logger)
28
+ from ..document import Document, sha256_text
29
+
30
+ log = get_logger(__name__)
31
+
32
+ STAGE = 5
33
+
34
+ _LIST_OR_HEADING = re.compile(
35
+ r"^\s*(?:\d+[.)]|\([a-z0-9]+\)|[-*\u2022]\s|[A-Z][A-Z \t]{3,}$)")
36
+
37
+
38
+ def _load_wordlist() -> Set[str]:
39
+ try:
40
+ with open(ENGLISH_WORDLIST, encoding="utf-8") as f:
41
+ return {w.strip().lower() for w in f if w.strip()}
42
+ except Exception:
43
+ return set()
44
+
45
+
46
+ _WORDS: Optional[Set[str]] = None
47
+
48
+
49
+ def _in_dict(word: str) -> bool:
50
+ global _WORDS
51
+ if _WORDS is None:
52
+ _WORDS = _load_wordlist()
53
+ if not _WORDS: # no dictionary -> conservatively accept normal joins
54
+ return True
55
+ return word.lower() in _WORDS
56
+
57
+
58
+ def _fix_hyphenation(text: str) -> str:
59
+ """A. Hyphenated-wrap repair."""
60
+ def repl(m):
61
+ left, right = m.group(1), m.group(2)
62
+ joined = left + right
63
+ # Compound-word protection: if the join is not in the dictionary,
64
+ # keep the original hyphen.
65
+ if _in_dict(joined):
66
+ return joined
67
+ return f"{left}-\n{right}"
68
+ # End-of-line letters + hyphen (- or soft hyphen) + newline + lowercase start
69
+ return re.sub(r"([A-Za-z]+)[\u2010\u00ad-]\n([a-z]+)", repl, text)
70
+
71
+
72
+ def _is_fixed_column(lines) -> bool:
73
+ body = [l for l in lines if l.strip()]
74
+ if len(body) < 4:
75
+ return False
76
+ near = 0
77
+ for l in body[:-1]: # last line may be short; do not count
78
+ ll = len(l.rstrip())
79
+ if any(abs(ll - w) <= FIXED_COLUMN_TOL for w in FIXED_COLUMN_WIDTHS):
80
+ near += 1
81
+ return near / max(len(body) - 1, 1) >= 0.6
82
+
83
+
84
+ def _fix_hard_wrap(text: str) -> str:
85
+ """B. Stitch fixed-column hard wraps."""
86
+ # Split on blank lines; stitch only blocks that look like fixed-column.
87
+ blocks = re.split(r"(\n\s*\n)", text)
88
+ out = []
89
+ for blk in blocks:
90
+ if blk.strip() == "" or "\n" not in blk:
91
+ out.append(blk)
92
+ continue
93
+ lines = blk.split("\n")
94
+ if not _is_fixed_column(lines):
95
+ out.append(blk)
96
+ continue
97
+ rebuilt = []
98
+ buf = ""
99
+ for i, line in enumerate(lines):
100
+ nxt = lines[i + 1] if i + 1 < len(lines) else ""
101
+ stripped = line.rstrip()
102
+ # Sentence-final punctuation / list item / heading / blank line ->
103
+ # legal boundary, do not stitch.
104
+ ends_sentence = bool(re.search(r"[.!?;:]\s*$", stripped))
105
+ next_is_struct = bool(_LIST_OR_HEADING.match(nxt)) or nxt.strip() == ""
106
+ buf = (buf + " " + stripped).strip() if buf else stripped
107
+ if ends_sentence or next_is_struct or i == len(lines) - 1:
108
+ rebuilt.append(buf)
109
+ buf = ""
110
+ out.append("\n".join(rebuilt))
111
+ return "".join(out)
112
+
113
+
114
+ def _spacy_refine(text: str) -> str:
115
+ """Custom spaCy model adds supplementary validation for complex boundaries (heading-glue / item boundaries)."""
116
+ try:
117
+ import spacy
118
+ try:
119
+ nlp = spacy.load(SPACY_LINEBREAK_MODEL)
120
+ except Exception:
121
+ nlp = spacy.load(SPACY_FALLBACK_PIPE)
122
+ except Exception:
123
+ return text # spaCy unavailable -> use rule-based result only
124
+ # Placeholder fallback channel: the production model predicts, per newline,
125
+ # whether it should be stitched.
126
+ return text
127
+
128
+
129
+ def run(doc: Document) -> Document:
130
+ sha_before = sha256_text(doc.text)
131
+ text = _fix_hyphenation(doc.text)
132
+ text = _fix_hard_wrap(text)
133
+ text = _spacy_refine(text)
134
+ doc.apply(STAGE, "line_level_repair", text,
135
+ note="dehyphenate + unwrap fixed-column (Textunwrap+spaCy)")
136
+ return doc
repair_pipeline_package/stages/stage06_charnorm.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 6: character-level normalization (paper end of Section 7.1, textacy).
3
+
4
+ Three core operations (fixed order):
5
+ 1. NFC re-confirmation (idempotent): Stages 4/5 may have re-introduced
6
+ uncomposed sequences during string concatenation.
7
+ 2. Whitespace character normalization: NBSP (U+00A0), ideographic space
8
+ (U+3000), and various half-width spaces -> ASCII space; remove
9
+ zero-width spaces / ZWNJ / ZWJ / BOM / word joiners and other
10
+ invisible characters.
11
+ 3. Private-Use-Area clearance: remove native PUA in U+E000-U+F8FF EXCEPT
12
+ for the "safe" sentinel range injected by Stage 3 (this implementation
13
+ reserves U+F000-U+F8FF as the sentinel block).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ import unicodedata
20
+
21
+ from ..config import (SENTINEL_PUA_END, SENTINEL_PUA_START, get_logger)
22
+ from ..document import Document, sha256_text
23
+
24
+ log = get_logger(__name__)
25
+
26
+ STAGE = 6
27
+
28
+ # Whitespace classes to fold into an ASCII space
29
+ _SPACE_LIKE = re.compile(
30
+ r"[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]")
31
+ # Zero-width / invisible characters to remove (excludes PUA, handled separately)
32
+ _ZERO_WIDTH = re.compile(r"[\u200b\u200c\u200d\u2060\ufeff]")
33
+
34
+ # Native PUA: keep the sentinel range [SENTINEL_PUA_START, SENTINEL_PUA_END]
35
+ _NATIVE_PUA = re.compile(
36
+ rf"[\uE000-{chr(max(SENTINEL_PUA_START - 1, 0xE000))}]")
37
+
38
+
39
+ def _clear_native_pua(text: str) -> str:
40
+ out = []
41
+ for ch in text:
42
+ cp = ord(ch)
43
+ if 0xE000 <= cp <= 0xF8FF:
44
+ if SENTINEL_PUA_START <= cp <= SENTINEL_PUA_END:
45
+ out.append(ch) # keep sentinels
46
+ # otherwise drop native PUA
47
+ else:
48
+ out.append(ch)
49
+ return "".join(out)
50
+
51
+
52
+ def run(doc: Document) -> Document:
53
+ sha_before = sha256_text(doc.text)
54
+ text = doc.text
55
+
56
+ # 1) NFC re-confirmation (prefer textacy; fall back to unicodedata)
57
+ try:
58
+ from textacy import preprocessing as tp
59
+ text = tp.normalize.unicode(text, form="NFC")
60
+ except Exception:
61
+ text = unicodedata.normalize("NFC", text)
62
+
63
+ # 2) whitespace normalization
64
+ text = _SPACE_LIKE.sub(" ", text)
65
+ text = _ZERO_WIDTH.sub("", text)
66
+
67
+ # 3) native-PUA clearance (sentinels preserved)
68
+ text = _clear_native_pua(text)
69
+
70
+ doc.apply(STAGE, "char_normalization(textacy)", text,
71
+ note="NFC re-confirm + whitespace norm + native-PUA clearance")
72
+ return doc
repair_pipeline_package/stages/stage07_whitespace.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 7: whitespace normalization (paper end of Section 7.1).
3
+
4
+ Final pass in the text-repair stage group. Cleans residual whitespace
5
+ artifacts accumulated from previous stages:
6
+ 1. Remaining ASCII tabs -> equal-width space sequences (default 4 spaces)
7
+ 2. Strip trailing whitespace from every line
8
+ 3. Collapse runs of 3+ blank lines to 2 (keep at most 1 blank as paragraph separator)
9
+ 4. Strip leading/trailing blank lines at the document boundaries
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ from ..config import MAX_CONSECUTIVE_BLANK_LINES, TAB_TO_SPACES, get_logger
17
+ from ..document import Document, sha256_text
18
+
19
+ log = get_logger(__name__)
20
+
21
+ STAGE = 7
22
+
23
+
24
+ def run(doc: Document) -> Document:
25
+ sha_before = sha256_text(doc.text)
26
+ text = doc.text
27
+
28
+ # 1) Tab -> N spaces
29
+ text = text.replace("\t", " " * TAB_TO_SPACES)
30
+ # 2) trailing whitespace
31
+ text = re.sub(r"[ \t]+(\n)", r"\1", text)
32
+ text = re.sub(r"[ \t]+$", "", text)
33
+ # 3) collapse consecutive blanks (keep at most 1 blank line => 2 newlines)
34
+ keep = MAX_CONSECUTIVE_BLANK_LINES
35
+ text = re.sub(r"\n{" + str(keep + 1) + r",}", "\n" * keep, text)
36
+ # 4) leading/trailing blank lines
37
+ text = text.strip("\n").strip()
38
+
39
+ doc.apply(STAGE, "whitespace_normalization", text,
40
+ note="tab->spaces, trailing-ws, collapse-blank, strip-edges")
41
+ return doc
repair_pipeline_package/stages/stage08_ocr.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 8: OCR error detection and correction subsystem (paper Sections 6.1 / 7.2).
3
+
4
+ Detect first, then route, then repair (only on documents/segments judged to
5
+ contain OCR noise):
6
+ CER < 5% -> SymSpell dictionary-level correction
7
+ 5% <= CER < 15% -> ByT5-base byte-level neural repair (weights under /data/models)
8
+ 15% <= CER < 20% -> ByT5 + KenLM perplexity "repair-validate-rollback" safety net
9
+ CER >= 20% -> drop the entire document
10
+
11
+ Position constraint: runs after all typographic and character-level repairs
12
+ (OCR diagnostic features only stabilize after text normalization). For non-OCR
13
+ documents (most modern HTML pages), this stage is skipped, avoiding spurious
14
+ edits to clean text.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Optional
21
+
22
+ from ..config import (BYT5_OCR_MODEL_DIR, KENLM_MODEL_PATH,
23
+ OCR_CER_BYT5_MAX, OCR_CER_ROLLBACK_MAX,
24
+ OCR_CER_SYMSPELL_MAX, OCR_DICT_HIT_THRESHOLD,
25
+ SYMSPELL_BIGRAM_PATH, SYMSPELL_DICT_PATH, get_logger)
26
+ from ..document import Document, sha256_text
27
+
28
+ log = get_logger(__name__)
29
+
30
+ STAGE = 8
31
+
32
+
33
+ # --------------------------------------------------------------------------- #
34
+ # Detection: is this an OCR source + estimate CER
35
+ # --------------------------------------------------------------------------- #
36
+ def _is_ocr_source(doc: Document) -> bool:
37
+ if doc.source_hint and "ocr" in doc.source_hint.lower():
38
+ return True
39
+ # Decaying dictionary hit rate + typical OCR visually-similar misrecognition
40
+ # patterns used as a weak diagnostic.
41
+ sample = doc.text[:5000]
42
+ suspicious = len(re.findall(r"\b[a-z]*[rcl]{2}[a-z]*\b", sample)) # rn/cl etc.
43
+ weird = len(re.findall(r"[a-z][A-Z]|[0-9][a-z]|[a-z][0-9]", sample))
44
+ n = max(len(sample.split()), 1)
45
+ return (suspicious + weird) / n > 0.15
46
+
47
+
48
+ def _estimate_cer(text: str, symspell) -> float:
49
+ """Approximate CER via dictionary hit rate (lower hit rate => higher CER)."""
50
+ words = re.findall(r"[A-Za-z]+", text)
51
+ if not words:
52
+ return 0.0
53
+ if symspell is not None:
54
+ try:
55
+ from symspellpy import Verbosity
56
+ hits = 0
57
+ for w in words[:2000]:
58
+ sug = symspell.lookup(w.lower(), Verbosity.TOP, max_edit_distance=0)
59
+ if sug:
60
+ hits += 1
61
+ hit_rate = hits / min(len(words), 2000)
62
+ return max(0.0, 1.0 - hit_rate)
63
+ except Exception:
64
+ pass
65
+ # No dictionary: coarse estimate via fraction of unusual characters.
66
+ bad = len(re.findall(r"[^A-Za-z0-9\s.,;:!?'\"()\-]", text))
67
+ return min(bad / max(len(text), 1) * 3, 1.0)
68
+
69
+
70
+ # --------------------------------------------------------------------------- #
71
+ # Repair backends
72
+ # --------------------------------------------------------------------------- #
73
+ class _SymSpell:
74
+ def __init__(self):
75
+ self.sym = None
76
+ try:
77
+ from symspellpy import SymSpell
78
+ self.sym = SymSpell(max_dictionary_edit_distance=2, prefix_length=7)
79
+ self.sym.load_dictionary(SYMSPELL_DICT_PATH, term_index=0, count_index=1)
80
+ try:
81
+ self.sym.load_bigram_dictionary(SYMSPELL_BIGRAM_PATH,
82
+ term_index=0, count_index=2)
83
+ except Exception:
84
+ pass
85
+ log.info("Loaded SymSpell dictionary.")
86
+ except Exception as e:
87
+ log.warning("SymSpell unavailable (%s).", e)
88
+
89
+ def correct(self, text: str) -> str:
90
+ if self.sym is None:
91
+ return text
92
+ try:
93
+ out = self.sym.lookup_compound(text, max_edit_distance=2)
94
+ return out[0].term if out else text
95
+ except Exception:
96
+ return text
97
+
98
+
99
+ class _ByT5:
100
+ def __init__(self):
101
+ self.tok = self.model = None
102
+ try:
103
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
104
+ self.tok = AutoTokenizer.from_pretrained(BYT5_OCR_MODEL_DIR)
105
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(BYT5_OCR_MODEL_DIR)
106
+ self.model.eval()
107
+ log.info("Loaded ByT5 OCR corrector: %s", BYT5_OCR_MODEL_DIR)
108
+ except Exception as e:
109
+ log.warning("ByT5 OCR model unavailable (%s).", e)
110
+
111
+ def correct(self, text: str) -> str:
112
+ if self.model is None:
113
+ return text
114
+ try:
115
+ import torch
116
+ with torch.no_grad():
117
+ enc = self.tok(text, return_tensors="pt", truncation=True,
118
+ max_length=1024)
119
+ out = self.model.generate(**enc, max_length=1024)
120
+ return self.tok.decode(out[0], skip_special_tokens=True)
121
+ except Exception:
122
+ return text
123
+
124
+
125
+ class _KenLM:
126
+ def __init__(self):
127
+ self.m = None
128
+ try:
129
+ import kenlm
130
+ self.m = kenlm.Model(KENLM_MODEL_PATH)
131
+ log.info("Loaded KenLM model.")
132
+ except Exception as e:
133
+ log.warning("KenLM unavailable (%s); rollback safety net disabled.", e)
134
+
135
+ def perplexity(self, text: str) -> Optional[float]:
136
+ if self.m is None:
137
+ return None
138
+ try:
139
+ return self.m.perplexity(text)
140
+ except Exception:
141
+ return None
142
+
143
+
144
+ # Backend singletons (lazy-loaded)
145
+ _symspell = _byt5 = _kenlm = None
146
+
147
+
148
+ def _backends():
149
+ global _symspell, _byt5, _kenlm
150
+ if _symspell is None:
151
+ _symspell = _SymSpell()
152
+ if _byt5 is None:
153
+ _byt5 = _ByT5()
154
+ if _kenlm is None:
155
+ _kenlm = _KenLM()
156
+ return _symspell, _byt5, _kenlm
157
+
158
+
159
+ def run(doc: Document) -> Document:
160
+ if not _is_ocr_source(doc):
161
+ doc.record(STAGE, "ocr_skip(non-ocr-source)", sha256_text(doc.text),
162
+ note="document not OCR-sourced; no OCR repair applied")
163
+ return doc
164
+
165
+ symspell, byt5, kenlm = _backends()
166
+ cer = _estimate_cer(doc.text, symspell.sym)
167
+ sha_before = sha256_text(doc.text)
168
+
169
+ if cer >= OCR_CER_ROLLBACK_MAX:
170
+ doc.discarded = True
171
+ doc.discard_reason = f"OCR CER {cer:.2%} >= 20% (unrecoverable)"
172
+ doc.record(STAGE, "ocr_discard", sha_before, note=doc.discard_reason)
173
+ return doc
174
+
175
+ if cer < OCR_CER_SYMSPELL_MAX:
176
+ fixed = symspell.correct(doc.text)
177
+ doc.apply(STAGE, f"ocr_symspell(CER={cer:.2%})", fixed)
178
+ elif cer < OCR_CER_BYT5_MAX:
179
+ fixed = byt5.correct(doc.text)
180
+ doc.apply(STAGE, f"ocr_byt5(CER={cer:.2%})", fixed)
181
+ else: # 15%-20%: ByT5 + KenLM rollback safety net
182
+ candidate = byt5.correct(doc.text)
183
+ ppl_before = kenlm.perplexity(doc.text)
184
+ ppl_after = kenlm.perplexity(candidate)
185
+ if (ppl_before is not None and ppl_after is not None
186
+ and ppl_after > ppl_before):
187
+ # Post-repair perplexity worsened -> rollback (better to leave as-is).
188
+ doc.record(STAGE, f"ocr_byt5_rollback(CER={cer:.2%})", sha_before,
189
+ note=f"ppl {ppl_before:.1f}->{ppl_after:.1f}; rolled back")
190
+ else:
191
+ doc.apply(STAGE, f"ocr_byt5+kenlm(CER={cer:.2%})", candidate,
192
+ note=f"ppl {ppl_before}->{ppl_after}")
193
+ return doc
repair_pipeline_package/stages/stage09_quality.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 9: masked-text quality validation (paper Section 6.2).
3
+
4
+ Runs on the masked text (code/math/structured segments are still PUA
5
+ placeholders). Uses a 6-tool CPU-only complementary ensemble to validate
6
+ the cumulative repair effect of Stages 1-8 plus light filtering. Emits a
7
+ binary pass/reject signal that drives the Stage 10 branching decision.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ..config import get_logger
13
+ from ..document import Document, sha256_text
14
+ from ..quality import QualityEnsemble
15
+
16
+ log = get_logger(__name__)
17
+
18
+ STAGE = 9
19
+
20
+ _ensemble: QualityEnsemble | None = None
21
+
22
+
23
+ def _get_ensemble() -> QualityEnsemble:
24
+ global _ensemble
25
+ if _ensemble is None:
26
+ _ensemble = QualityEnsemble()
27
+ return _ensemble
28
+
29
+
30
+ def run(doc: Document) -> Document:
31
+ if doc.discarded: # skip if Stage 8 already discarded the document
32
+ doc.quality_passed = False
33
+ return doc
34
+
35
+ passed, score, breakdown = _get_ensemble().verify(doc.text)
36
+ doc.quality_passed = passed
37
+ doc.quality_score = score
38
+ doc.meta["quality_breakdown"] = breakdown
39
+ doc.record(STAGE, "quality_verification(6-tool ensemble)",
40
+ sha256_text(doc.text),
41
+ note=f"composite={score:.3f} -> {'PASS' if passed else 'REJECT'}")
42
+ return doc
repair_pipeline_package/stages/stage10_restore.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 10: final content restoration and integrity check (paper Section 6.2 / Chapter 5).
3
+
4
+ - Documents that pass quality validation: merge the type-specific-repaired
5
+ structured segments back into the text skeleton in LIFO order, run a
6
+ SHA-256 integrity check, and emit the final document if it passes.
7
+ - Documents that fail quality validation: roll back to the original
8
+ unrepaired version (original_text).
9
+
10
+ LIFO order ensures natural back-fill of nested mixed structures (innermost
11
+ segments, which were masked last, are restored first).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from ..config import get_logger
17
+ from ..document import Document, SegmentType, sha256_text
18
+ from ..masking import lifo_order
19
+
20
+ log = get_logger(__name__)
21
+
22
+ STAGE = 10
23
+
24
+
25
+ def _restore_segments(text: str, doc: Document) -> tuple[str, bool]:
26
+ """Refill segments in LIFO order and verify content integrity."""
27
+ integrity_ok = True
28
+ for seg in lifo_order(doc.segments):
29
+ if seg.placeholder not in text:
30
+ # Placeholder lost during a previous repair stage -> integrity breach
31
+ log.warning("placeholder missing for %s", seg.placeholder)
32
+ integrity_ok = False
33
+ continue
34
+
35
+ if seg.seg_type == SegmentType.PROSE:
36
+ content = seg.original_content
37
+ elif seg.repaired_validated and seg.repaired_content is not None:
38
+ content = seg.repaired_content # use repaired content
39
+ else:
40
+ content = seg.original_content # validation failed -> fall back to original (fidelity-first)
41
+
42
+ text = text.replace(seg.placeholder, content)
43
+ return text, integrity_ok
44
+
45
+
46
+ def run(doc: Document) -> Document:
47
+ sha_before = sha256_text(doc.text)
48
+
49
+ # Discarded / quality-rejected -> roll back to original unrepaired version
50
+ if doc.discarded:
51
+ doc.text = doc.original_text
52
+ doc.record(STAGE, "rollback(discarded)", sha_before,
53
+ note=doc.discard_reason or "discarded")
54
+ return doc
55
+
56
+ if doc.quality_passed is False:
57
+ doc.text = doc.original_text
58
+ doc.record(STAGE, "rollback(quality_reject)", sha_before,
59
+ note=f"quality={doc.quality_score}; restored original")
60
+ return doc
61
+
62
+ # Quality passed -> LIFO restore + integrity check
63
+ restored, integrity_ok = _restore_segments(doc.text, doc)
64
+ if not integrity_ok:
65
+ # integrity failure -> conservative rollback
66
+ doc.text = doc.original_text
67
+ doc.record(STAGE, "rollback(integrity_fail)", sha_before,
68
+ note="SHA-256/placeholder integrity check failed")
69
+ return doc
70
+
71
+ doc.apply(STAGE, "lifo_restore+sha256_verify", restored,
72
+ note=f"restored {len(doc.segments)} segments (LIFO), integrity OK")
73
+ return doc
repair_pipeline_package/typed_repair/__init__.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Type-specific repair dispatcher.
3
+
4
+ For each masked segment, route to the appropriate repair module by type,
5
+ then apply type-specific pre-restore validation. If validation passes, mark
6
+ repaired_validated=True so the restore stage uses the repaired content;
7
+ otherwise fall back to the original content (fidelity-first).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from ..document import Document, SegmentType
13
+ from . import code_repair, math_repair, structured_repair
14
+
15
+
16
+ def repair_and_validate_segments(doc: Document) -> None:
17
+ for seg in doc.segments:
18
+ if seg.seg_type == SegmentType.CODE:
19
+ seg.repaired_content = code_repair.repair_code(
20
+ seg.original_content, html_class=seg.meta.get("tag"))
21
+ # Code pre-restore validation: accept after lexical cleanup
22
+ # (the formatter already handles syntax-level fallback).
23
+ seg.repaired_validated = True
24
+ elif seg.seg_type == SegmentType.MATH:
25
+ seg.repaired_content = math_repair.repair_math(seg.original_content)
26
+ seg.repaired_validated = math_repair.validate_math(seg.repaired_content)
27
+ elif seg.seg_type == SegmentType.STRUCTURED:
28
+ seg.repaired_content = structured_repair.repair_structured(
29
+ seg.original_content)
30
+ seg.repaired_validated = structured_repair.validate_structured(
31
+ seg.repaired_content)
32
+ else:
33
+ seg.repaired_content = seg.original_content
34
+ seg.repaired_validated = True
repair_pipeline_package/typed_repair/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.32 kB). View file
 
repair_pipeline_package/typed_repair/__pycache__/code_repair.cpython-310.pyc ADDED
Binary file (5.32 kB). View file
 
repair_pipeline_package/typed_repair/__pycache__/math_repair.cpython-310.pyc ADDED
Binary file (1.49 kB). View file
 
repair_pipeline_package/typed_repair/__pycache__/structured_repair.cpython-310.pyc ADDED
Binary file (2.67 kB). View file
 
repair_pipeline_package/typed_repair/code_repair.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code-segment type-specific repair (paper Section 5.1).
3
+
4
+ Flow: lexical cleanup -> code-language identification (HTML class hint +
5
+ Magika + Tree-sitter, three-signal fusion) -> deterministic repair (formatter).
6
+ Follows the minimum-edit principle, applied at segment granularity.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import re
13
+ from typing import Optional, Tuple
14
+
15
+ from ..config import MAGIKA_MODEL_DIR, get_logger
16
+
17
+ log = get_logger(__name__)
18
+
19
+ _CODE_CLASS_HINT = re.compile(
20
+ r"(?:language|lang|brush|prism|highlight(?:-source)?)[-:]([a-z0-9+#]+)", re.I)
21
+
22
+ # Language-identification multi-source voting weights (paper Section 5.1)
23
+ _W_MAGIKA, _W_KEYWORD, _W_TREESITTER, _W_HINT = 0.9, 0.7, 0.8, 0.4
24
+
25
+ _SHEBANG = re.compile(r"^#!.*?(\bpython\b|\bperl\b|\bbash\b|\bsh\b|\bruby\b|\bnode\b)")
26
+
27
+
28
+ def lexical_clean(code: str) -> str:
29
+ """Four lexical-pollution cleanups: multi-pass HTML entities, mojibake/smart quotes, mixed line-endings, zero-width/NUL."""
30
+ # 1) iterate html.unescape until idempotent fixed point
31
+ prev = None
32
+ cur = code
33
+ for _ in range(8):
34
+ nxt = html.unescape(cur)
35
+ if nxt == cur:
36
+ break
37
+ prev, cur = cur, nxt
38
+ # 2) ftfy repair (mojibake, smart quotes, Latin ligatures)
39
+ try:
40
+ import ftfy
41
+ cur = ftfy.fix_text(cur)
42
+ except Exception:
43
+ pass
44
+ # 3) unify line endings to \n
45
+ cur = cur.replace("\r\n", "\n").replace("\r", "\n")
46
+ # 4) remove NUL bytes
47
+ cur = cur.replace("\x00", "")
48
+ return cur
49
+
50
+
51
+ class _Magika:
52
+ def __init__(self):
53
+ self.m = None
54
+ try:
55
+ from magika import Magika
56
+ self.m = Magika() # pip-bundled model; MAGIKA_MODEL_DIR may override
57
+ except Exception as e:
58
+ log.warning("Magika unavailable (%s).", e)
59
+
60
+ def identify(self, code: str) -> Optional[str]:
61
+ if self.m is None:
62
+ return None
63
+ try:
64
+ res = self.m.identify_bytes(code.encode("utf-8", "ignore"))
65
+ return res.output.ct_label
66
+ except Exception:
67
+ return None
68
+
69
+
70
+ def _keyword_anchor(code: str) -> Optional[str]:
71
+ table = {
72
+ "python": r"\b(def|import|elif|lambda|self)\b|:\s*$",
73
+ "javascript": r"\b(function|const|let|=>|console\.log)\b",
74
+ "java": r"\b(public|private|class|System\.out|void)\b",
75
+ "c": r"#include\s*<|\bprintf\s*\(",
76
+ "go": r"\bfunc\b|\bpackage\b|:=",
77
+ "ruby": r"\b(def|end|puts|require)\b",
78
+ }
79
+ for lang, pat in table.items():
80
+ if re.search(pat, code, re.M):
81
+ return lang
82
+ return None
83
+
84
+
85
+ def _treesitter_best(code: str, candidates) -> Optional[str]:
86
+ """Try parsing each candidate language; return the one with the lowest error_ratio."""
87
+ try:
88
+ from tree_sitter_languages import get_parser
89
+ except Exception:
90
+ return None
91
+ best, best_ratio = None, 1.01
92
+ for lang in candidates:
93
+ try:
94
+ parser = get_parser(lang)
95
+ tree = parser.parse(code.encode("utf-8", "ignore"))
96
+ errs = _count_errors(tree.root_node)
97
+ total = max(_count_nodes(tree.root_node), 1)
98
+ ratio = errs / total
99
+ if ratio < best_ratio:
100
+ best, best_ratio = lang, ratio
101
+ except Exception:
102
+ continue
103
+ return best
104
+
105
+
106
+ def _count_errors(node) -> int:
107
+ c = 1 if node.is_error or node.is_missing else 0
108
+ for ch in node.children:
109
+ c += _count_errors(ch)
110
+ return c
111
+
112
+
113
+ def _count_nodes(node) -> int:
114
+ c = 1
115
+ for ch in node.children:
116
+ c += _count_nodes(ch)
117
+ return c
118
+
119
+
120
+ def identify_language(code: str, html_class: Optional[str] = None
121
+ ) -> Tuple[Optional[str], float]:
122
+ """Three-signal + keyword-anchor weighted vote. Returns (language, confidence)."""
123
+ # Fast path: shebang
124
+ first = code.splitlines()[:1]
125
+ if first and _SHEBANG.search(first[0]):
126
+ return _SHEBANG.search(first[0]).group(1), 0.95
127
+
128
+ votes = {}
129
+ # HTML class hint
130
+ hint = None
131
+ if html_class:
132
+ m = _CODE_CLASS_HINT.search(html_class)
133
+ if m:
134
+ hint = m.group(1).lower()
135
+ votes[hint] = votes.get(hint, 0) + _W_HINT
136
+ # Magika
137
+ mg = _Magika().identify(code)
138
+ if mg:
139
+ votes[mg] = votes.get(mg, 0) + _W_MAGIKA
140
+ # Keyword anchors
141
+ kw = _keyword_anchor(code)
142
+ if kw:
143
+ votes[kw] = votes.get(kw, 0) + _W_KEYWORD
144
+ # Tree-sitter to break ties (among existing candidates)
145
+ cands = list(votes.keys()) or (["python", "javascript", "java", "c", "go"])
146
+ ts = _treesitter_best(code, cands)
147
+ if ts:
148
+ votes[ts] = votes.get(ts, 0) + _W_TREESITTER
149
+
150
+ if not votes:
151
+ return None, 0.0
152
+ lang = max(votes, key=votes.get)
153
+ # >=3 sources agreeing (score >= ~2.4) gets confidence 0.85
154
+ conf = 0.85 if votes[lang] >= 2.4 else min(votes[lang] / 2.4 * 0.85, 0.84)
155
+ return lang, conf
156
+
157
+
158
+ _FORMATTERS = {"python": "black"}
159
+
160
+
161
+ def deterministic_repair(code: str, lang: Optional[str]) -> str:
162
+ """Native formatter repair for the identified language (minimum edit). Returns input unchanged on failure."""
163
+ if lang == "python":
164
+ try:
165
+ import black
166
+ return black.format_str(code, mode=black.Mode())
167
+ except Exception:
168
+ return code
169
+ return code
170
+
171
+
172
+ def repair_code(content: str, html_class: Optional[str] = None) -> str:
173
+ cleaned = lexical_clean(content)
174
+ lang, conf = identify_language(cleaned, html_class)
175
+ if lang and conf >= 0.5:
176
+ cleaned = deterministic_repair(cleaned, lang)
177
+ return cleaned