"""Corpus loading, validation, conservative normalization and duplicate grouping. The CLAUDETTE ToS corpus stores one sentence per line (PTB-tokenized, lowercased) in ``Sentences/.txt`` with line-aligned label files: ``Labels/`` holds the binary potentially-unfair flag (1 / -1) and ``Labels_/`` one binary file per unfair-clause category. """ from __future__ import annotations import hashlib import logging import re from dataclasses import dataclass, field from pathlib import Path log = logging.getLogger(__name__) PREPROCESSING_VERSION = "1.0" CATEGORIES = ["A", "CH", "CR", "J", "LAW", "LTD", "TER", "USE"] CATEGORY_NAMES = { "A": "Arbitration", "CH": "Unilateral change", "CR": "Content removal", "J": "Jurisdiction", "LAW": "Choice of law", "LTD": "Limitation of liability", "TER": "Unilateral termination", "USE": "Contract by using", } # PTB bracket / quote tokens -> plain characters. _PTB_TOKENS = { "-lrb-": "(", "-rrb-": ")", "-lsb-": "[", "-rsb-": "]", "-lcb-": "{", "-rcb-": "}", "``": '"', "''": '"', } _PTB_RE = re.compile("|".join(re.escape(t) for t in _PTB_TOKENS), flags=re.IGNORECASE) # Re-attach PTB-split contractions; "n't" is kept so negation is preserved. _CONTRACTION_RE = re.compile(r"(\w) (n't|'s|'re|'ve|'ll|'d|'m)\b") _SPACE_BEFORE_PUNCT_RE = re.compile(r" ([,.;:!?%)\]}])") _SPACE_AFTER_OPEN_RE = re.compile(r"([(\[{]) ") _WS_RE = re.compile(r"\s+") def normalize(text: str) -> str: """Conservative normalization shared by the corpus and incoming queries. Undoes PTB artifacts, lowercases and collapses whitespace. No stemming, stop-word removal or token deletion: negations and qualifiers survive. """ t = _PTB_RE.sub(lambda m: _PTB_TOKENS[m.group(0).lower()], text) t = t.replace("“", '"').replace("”", '"').replace("’", "'").replace("‘", "'") t = _WS_RE.sub(" ", t).strip().lower() t = _CONTRACTION_RE.sub(r"\1\2", t) t = _SPACE_BEFORE_PUNCT_RE.sub(r"\1", t) t = _SPACE_AFTER_OPEN_RE.sub(r"\1", t) return t @dataclass class Occurrence: contract: str position: int # 0-based line index in the source contract original: str # sentence exactly as stored in the corpus file unfair: bool categories: list[str] @dataclass class SentenceGroup: """All occurrences of one exact normalized sentence.""" group_id: str text: str occurrences: list[Occurrence] = field(default_factory=list) @property def categories(self) -> list[str]: return sorted({c for o in self.occurrences for c in o.categories}) @property def unfair(self) -> bool: return any(o.unfair for o in self.occurrences) @property def contracts(self) -> set[str]: return {o.contract for o in self.occurrences} def to_dict(self) -> dict: return { "group_id": self.group_id, "text": self.text, "categories": self.categories, "unfair": self.unfair, "occurrences": [o.__dict__ for o in self.occurrences], } @classmethod def from_dict(cls, d: dict) -> "SentenceGroup": return cls(d["group_id"], d["text"], [Occurrence(**o) for o in d["occurrences"]]) def _read_lines(path: Path) -> list[str]: # Files are UTF-8; fail loudly on encoding problems instead of guessing. return path.read_text(encoding="utf-8").splitlines() def load_occurrences(data_dir: Path) -> list[Occurrence]: """Read every contract, validating sentence/label alignment and label values.""" data_dir = Path(data_dir) sentence_dir = data_dir / "Sentences" contracts = sorted(p.stem for p in sentence_dir.glob("*.txt")) if not contracts: raise FileNotFoundError(f"No sentence files in {sentence_dir}") occurrences: list[Occurrence] = [] for contract in contracts: sentences = _read_lines(sentence_dir / f"{contract}.txt") unfair = _read_lines(data_dir / "Labels" / f"{contract}.txt") cat_labels = {c: _read_lines(data_dir / f"Labels_{c}" / f"{contract}.txt") for c in CATEGORIES} for name, labels in [("Labels", unfair), *((f"Labels_{c}", v) for c, v in cat_labels.items())]: if len(labels) != len(sentences): raise ValueError(f"{contract}: {name} has {len(labels)} rows, Sentences has {len(sentences)}") bad = {v.strip() for v in labels} - {"1", "-1"} if bad: raise ValueError(f"{contract}: unexpected values {bad} in {name}") for i, sentence in enumerate(sentences): cats = [c for c in CATEGORIES if cat_labels[c][i].strip() == "1"] is_unfair = unfair[i].strip() == "1" if is_unfair != bool(cats): log.warning("%s:%d unfair flag disagrees with category labels", contract, i) occurrences.append(Occurrence(contract, i, sentence.strip(), is_unfair, cats)) return occurrences def group_id_for(text: str) -> str: return "s_" + hashlib.sha1(text.encode("utf-8")).hexdigest()[:12] def group_duplicates(occurrences: list[Occurrence]) -> tuple[list[SentenceGroup], list[dict]]: """Group exact normalized duplicates; return groups plus annotation conflicts. Blank sentences are dropped. Groups are ordered by first occurrence, which makes indices deterministic for a fixed input. """ groups: dict[str, SentenceGroup] = {} for occ in occurrences: text = normalize(occ.original) if not text: continue g = groups.get(text) if g is None: g = groups[text] = SentenceGroup(group_id_for(text), text) g.occurrences.append(occ) conflicts = [] for g in groups.values(): labelings = {(o.unfair, tuple(o.categories)) for o in g.occurrences} if len(labelings) > 1: conflicts.append({ "group_id": g.group_id, "text": g.text, "labelings": [ {"contract": o.contract, "position": o.position, "unfair": o.unfair, "categories": o.categories} for o in g.occurrences ], }) if conflicts: log.warning("%d duplicate groups carry conflicting annotations (kept, labels unioned)", len(conflicts)) return list(groups.values()), conflicts def fingerprint(data_dir: Path) -> str: """SHA-256 over all sentence and label files (path + content).""" data_dir = Path(data_dir) h = hashlib.sha256() for sub in ["Sentences", "Labels", *(f"Labels_{c}" for c in CATEGORIES)]: for p in sorted((data_dir / sub).glob("*.txt")): h.update(f"{sub}/{p.name}".encode()) h.update(p.read_bytes()) return h.hexdigest()