Files
Censor_data/censor_pdfs.py
2026-09-11 09:36:06 +00:00

511 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Hide logos and pseudonymize well names, rig names, and coordinates.
This script is intentionally profiled for the 23 vector PDFs under
``DDR templates``. It combines exact-value search (to catch repeated values on
later pages), synthetic replacements, and top-of-page image detection for logos.
Original sensitive glyphs are permanently removed before fake values are
inserted. Hidden content and metadata are scrubbed. Originals are never modified.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Iterable, Sequence
import pymupdf
CATEGORIES = ("logo", "well_name", "rig_name", "coordinates")
DEFAULT_INPUTS = (Path("DDR_Templates"), Path("DDR templates"))
@dataclass(frozen=True)
class RectRule:
category: str
rect: tuple[float, float, float, float]
pages: tuple[int, ...] = (0,)
@dataclass(frozen=True)
class WordRegion:
category: str
rect: tuple[float, float, float, float]
pages: tuple[int, ...] = (0,)
@dataclass(frozen=True)
class Profile:
terms: dict[str, tuple[str, ...]] = field(default_factory=dict)
rectangles: tuple[RectRule, ...] = ()
word_regions: tuple[WordRegion, ...] = ()
not_applicable: tuple[str, ...] = ()
scrub: bool = True
@dataclass
class FileAudit:
input: str
output: str
status: str
pages: int = 0
redactions: dict[str, int] = field(default_factory=lambda: {name: 0 for name in CATEGORIES})
synthetic_values: dict[str, list[str]] = field(
default_factory=lambda: {name: [] for name in CATEGORIES if name != "logo"}
)
missing: list[str] = field(default_factory=list)
error: str | None = None
def R(category: str, rect: tuple[float, float, float, float], *pages: int) -> RectRule:
return RectRule(category, rect, tuple(pages) if pages else (0,))
def W(category: str, rect: tuple[float, float, float, float], *pages: int) -> WordRegion:
return WordRegion(category, rect, tuple(pages) if pages else (0,))
# Coordinates are PDF points in each source template's native page system.
# Non-logo rectangles remain as layout documentation and fallback references;
# text replacement itself targets exact glyph boxes so labels remain untouched.
PROFILES: dict[str, Profile] = {
"CuuLong.pdf": Profile(
terms={
"well_name": ("Su Tu Nau South 7P", "SNS-7P"),
"rig_name": ("PVD1", "PVD-1"),
"coordinates": ("10° 33' 11.87\" N", "108° 24' 3.88\" E"),
},
rectangles=(
R("well_name", (200, 37, 395, 55)), R("rig_name", (33, 75, 155, 95)),
R("coordinates", (160, 75, 375, 95)),
),
# Its legacy RC4 PDF has a dangling xref object that Document.scrub()
# rejects. Redaction + garbage=4 still permanently removes old objects.
scrub=False,
),
"HOANGLONG_JOC.pdf": Profile(
terms={"logo": ("HOANG LONG JOC",), "well_name": ("16-1-TGT-H5-36P",),
"rig_name": ("Thor-PVD/Borr Drilling",)},
rectangles=(R("well_name", (20, 48, 180, 69), 0), R("rig_name", (20, 58, 180, 78), 0),
R("well_name", (20, 32, 190, 45), 1), R("rig_name", (20, 44, 190, 57), 1)),
not_applicable=("coordinates",),
),
"HarbourEnergy.pdf": Profile(
terms={"well_name": ("12W-CS-S6PST",), "rig_name": ("PV Drilling VI",)},
rectangles=(R("well_name", (470, 60, 570, 102)), R("rig_name", (30, 185, 155, 205))),
not_applicable=("coordinates",),
),
"Hibiscus.pdf": Profile(
terms={"logo": ("Hibiscus Oil & Gas Malaysia Limited",), "well_name": ("BOC-30 (T1)",),
"rig_name": ("PVD III",)},
rectangles=(R("well_name", (29, 82, 210, 95)), R("rig_name", (375, 106, 560, 120))),
not_applicable=("coordinates",),
),
"Murphy.pdf": Profile(
terms={"well_name": ("LDH-1X Original Hole", "LDH-1X"), "rig_name": ("Hakuryu 11",),
"coordinates": ("10° 14' 51.846\" N", "108° 10' 30.66\" E")},
rectangles=(R("well_name", (23, 50, 205, 66)), R("well_name", (23, 73, 163, 92)),
R("rig_name", (160, 108, 297, 127)), R("coordinates", (426, 73, 561, 92))),
),
"PVEP_POC-2.pdf": Profile(
terms={"well_name": ("DH-27P",), "rig_name": ("SD Perseverance (SDP)",),
"coordinates": ("8°29'59.9330\"N", "108°40'55.6362\"E")},
rectangles=(R("well_name", (36, 42, 170, 52)), R("rig_name", (36, 81, 168, 91)),
R("coordinates", (36, 111, 170, 128))),
),
"PVEP_POC.pdf": Profile(
terms={"well_name": ("05.1a-DH-19P",), "rig_name": ("WEST TUCANA",)},
rectangles=(R("well_name", (83, 40, 225, 50)), R("rig_name", (83, 82, 265, 94)),
R("coordinates", (83, 117, 265, 136))),
not_applicable=("coordinates",),
),
"PetronasCarigali.pdf": Profile(
terms={"well_name": ("HAM RONG-1X",), "rig_name": ("DEEP DRILLER-5 (DD-5)",)},
rectangles=(R("well_name", (55, 108, 260, 122)), R("rig_name", (55, 138, 260, 153))),
not_applicable=("coordinates",),
),
"Sonatrack.pdf": Profile(
terms={"well_name": ("BRS-38",), "rig_name": ("TP-222",),
"coordinates": ("32°35'57,4133\"N", "6°38'13,40\"E")},
rectangles=(R("well_name", (130, 185, 460, 214)), R("rig_name", (130, 223, 464, 251)),
R("coordinates", (462, 223, 716, 264))),
),
"THANGLONG_JOC.pdf": Profile(
terms={"well_name": ("Hai Su Trang / 15-2/01-HST-6P", "HST-6P"),
"rig_name": ("Velesto Drilling / Naga 3", "Naga 3")},
rectangles=(R("well_name", (77, 50, 260, 60), 0, 2), R("rig_name", (77, 59, 240, 68), 0, 2)),
not_applicable=("coordinates",),
),
"VIETSOPETRO_2.pdf": Profile(
terms={"logo": ("VIETSOPETRO",), "well_name": ("KTN- P2",), "rig_name": ("Tam Dao-05",)},
rectangles=(R("logo", (165, 23, 300, 37)), R("well_name", (33, 36, 192, 50)),
R("rig_name", (190, 36, 355, 50))),
not_applicable=("coordinates",),
),
"AMAL.pdf": Profile(
terms={"well_name": ("AMAL-18 STA",), "rig_name": ("ADM-6",)},
rectangles=(R("rig_name", (21, 152, 170, 162)), R("well_name", (21, 162, 180, 173))),
word_regions=(W("coordinates", (430, 525, 510, 627)),),
),
"AmourEnergy.pdf": Profile(
terms={"logo": ("ARMOUR ENERGY LTD", "ARMOUR ENERGY"), "well_name": ("Myrtle Basin 1",),
"rig_name": ("Nitro 1", "Nitro # 7", "Nitro Rig 7")},
rectangles=(R("well_name", (90, 87, 240, 100)), R("rig_name", (98, 111, 240, 124))),
not_applicable=("coordinates",),
),
"Chevron.pdf": Profile(
terms={"well_name": ("Bibiyana -19",), "rig_name": ("WDI 801",)},
rectangles=(R("well_name", (23, 76, 205, 92)), R("rig_name", (100, 94, 205, 109))),
not_applicable=("coordinates",),
),
"GPC.pdf": Profile(
terms={"well_name": ("NWO-3",), "rig_name": ("ADMARINE-88",),
"coordinates": ("28º 56.4077'", "32° 51.0596ʹ")},
rectangles=(R("well_name", (290, 27, 395, 40)), R("rig_name", (176, 45, 255, 62)),
R("coordinates", (404, 45, 510, 55))),
),
"HOKCHI.pdf": Profile(
terms={"logo": ("HOKCHI ENERGY S.A. de C.V.",), "well_name": ("HOKCHI-6DEL",),
"rig_name": ("HUNTER",)},
rectangles=(R("well_name", (28, 77, 205, 90)), R("rig_name", (28, 89, 205, 103))),
not_applicable=("coordinates",),
),
"Khalda.pdf": Profile(
terms={"well_name": ("HERUNEFER W-13",), "rig_name": ("EDC 58",)},
rectangles=(R("logo", (20, 20, 110, 59)), R("well_name", (23, 58, 210, 75)),
R("rig_name", (458, 72, 570, 94))),
not_applicable=("coordinates",),
),
"NISOC.pdf": Profile(
terms={"well_name": ("RR-026",), "rig_name": ("S201",)},
rectangles=(R("well_name", (18, 88, 112, 108)), R("rig_name", (110, 106, 205, 117))),
not_applicable=("coordinates",),
),
"PETROMINERALES.pdf": Profile(
terms={"logo": ("PETROMINERALES PERU S.A.",),
"well_name": ("LCOL02XD", "LA COLPA-2XD"), "rig_name": ("PTX/5825",)},
rectangles=(R("well_name", (35, 72, 175, 85)), R("well_name", (192, 86, 330, 99)),
R("rig_name", (328, 100, 505, 113))),
not_applicable=("coordinates",),
),
"POGC.pdf": Profile(
terms={"well_name": ("SPD19B-06",), "rig_name": ("SAHAR-1",),
"coordinates": ("26° 39' 46.3\" N", "52° 5' 19.4\" E")},
rectangles=(R("well_name", (235, 45, 365, 70)), R("rig_name", (25, 94, 120, 113)),
R("coordinates", (393, 77, 580, 96))),
),
"SONATRACH.pdf": Profile(
terms={"logo": ("SONATRACH",), "well_name": ("ATK-29",), "rig_name": ("TP 180",)},
rectangles=(R("well_name", (9, 78, 130, 101), 0), R("rig_name", (142, 102, 235, 125), 0),
R("well_name", (9, 54, 130, 76), 1, 2), R("rig_name", (142, 78, 235, 101), 1, 2)),
not_applicable=("coordinates",),
),
"SPD.pdf": Profile(
terms={"well_name": ("SPD19B-06",), "rig_name": ("SAHAR-1",),
"coordinates": ("26° 39' 46.3\" N", "52° 5' 19.4\" E")},
rectangles=(R("well_name", (235, 45, 365, 70)), R("rig_name", (25, 94, 120, 113)),
R("coordinates", (393, 77, 580, 96))),
),
"WellView.pdf": Profile(
terms={"logo": ("WellView",), "well_name": ("Sample 11 - Full Data",),
"rig_name": ("NABORS, 432", "NABORS")},
rectangles=(R("logo", (27, 24, 145, 51)), R("well_name", (27, 51, 205, 66)),
R("rig_name", (451, 221, 588, 262))),
not_applicable=("coordinates",),
),
}
def _default_input() -> Path:
for path in DEFAULT_INPUTS:
if path.is_dir():
return path
raise FileNotFoundError("DDR_Templates or DDR templates directory was not found")
def _pdfs(inputs: Iterable[Path]) -> list[Path]:
found: list[Path] = []
for path in inputs:
if path.is_file() and path.suffix.lower() == ".pdf":
found.append(path)
elif path.is_dir():
found.extend(p for p in path.rglob("*") if p.suffix.lower() == ".pdf")
else:
raise FileNotFoundError(f"not a PDF file or directory: {path}")
return sorted(set(found), key=lambda p: str(p).lower())
def _logo_images(page: pymupdf.Page) -> list[pymupdf.Rect]:
"""Find displayed raster logos in the top 22 percent of a page."""
result: list[pymupdf.Rect] = []
page_area = page.rect.get_area()
seen: set[tuple[float, float, float, float]] = set()
for image in page.get_images(full=True):
for rect in page.get_image_rects(image):
key = tuple(round(value, 2) for value in rect)
if key in seen:
continue
seen.add(key)
if (
rect.width >= 10
and rect.height >= 10
and rect.y1 <= page.rect.height * 0.22
and rect.get_area() / page_area <= 0.15
):
result.append(rect + (-1, -1, 1, 1))
return result
@dataclass
class TextCandidate:
category: str
rect: pymupdf.Rect
replacement: str
font_size: float
color: tuple[float, float, float]
baseline: float
def _seed(filename: str) -> int:
return int(hashlib.sha256(filename.encode("utf-8")).hexdigest()[:8], 16) % 90 + 10
def _fake_value(category: str, term: str, filename: str) -> str:
number = _seed(filename)
if category == "well_name":
return f"WELL-{number}"
if category == "rig_name":
return f"RIG-{number}"
upper = term.upper()
if "N" in upper or "S" in upper:
hemisphere = "S" if "S" in upper and "N" not in upper else "N"
return f"12° 34' 56.78\" {hemisphere}"
hemisphere = "W" if "W" in upper and "E" not in upper else "E"
return f"112° 34' 56.78\" {hemisphere}"
def _style(page: pymupdf.Page, rect: pymupdf.Rect) -> tuple[float, tuple[float, float, float], float]:
best: tuple[float, dict] | None = None
for block in page.get_text("dict")["blocks"]:
for line in block.get("lines", []):
for span in line.get("spans", []):
overlap = pymupdf.Rect(span["bbox"]) & rect
area = overlap.get_area() if not overlap.is_empty else 0.0
if area and (best is None or area > best[0]):
best = (area, span)
if best is None:
return max(5.0, rect.height * 0.72), (0.0, 0.0, 0.0), rect.y1 - 1
span = best[1]
return float(span["size"]), pymupdf.sRGB_to_pdf(span["color"]), float(span["origin"][1])
def _add_logo(candidates: list[pymupdf.Rect], rect: pymupdf.Rect, page: pymupdf.Page) -> None:
clipped = rect & page.rect
if clipped.is_empty or clipped.get_area() < 1:
return
for index, existing in enumerate(candidates):
overlap = existing & clipped
if not overlap.is_empty and overlap.get_area() > 0:
candidates[index] = existing | clipped
return
candidates.append(clipped)
def _add_text(candidates: list[TextCandidate], candidate: TextCandidate) -> None:
for existing in candidates:
overlap = existing.rect & candidate.rect
if not overlap.is_empty and overlap.get_area() >= min(
existing.rect.get_area(), candidate.rect.get_area()
) * 0.5:
return
candidates.append(candidate)
def _insert_replacement(page: pymupdf.Page, candidate: TextCandidate) -> None:
size = candidate.font_size
width = pymupdf.get_text_length(candidate.replacement, fontname="helv", fontsize=size)
if width > candidate.rect.width:
size = max(3.5, size * candidate.rect.width / width * 0.96)
page.insert_text(
(candidate.rect.x0, candidate.baseline), candidate.replacement,
fontname="helv", fontsize=size, color=candidate.color, overlay=True,
)
def redact_pdf(
source: Path, destination: Path, profile: Profile, logo_fill: tuple[float, float, float]
) -> FileAudit:
audit = FileAudit(str(source), str(destination), "ok")
try:
document = pymupdf.open(source)
audit.pages = len(document)
for page_index, page in enumerate(document):
logos: list[pymupdf.Rect] = []
text_candidates: list[TextCandidate] = []
for rect in _logo_images(page):
_add_logo(logos, rect, page)
for term in sorted(profile.terms.get("logo", ()), key=len, reverse=True):
for rect in page.search_for(term):
_add_logo(logos, rect + (-1, -1, 1, 1), page)
for rule in profile.rectangles:
if rule.category == "logo" and page_index in rule.pages:
_add_logo(logos, pymupdf.Rect(rule.rect), page)
for category in ("well_name", "rig_name", "coordinates"):
for term in sorted(profile.terms.get(category, ()), key=len, reverse=True):
for rect in page.search_for(term):
size, color, baseline = _style(page, rect)
replacement = _fake_value(category, term, source.name)
_add_text(text_candidates, TextCandidate(
category, rect + (-0.5, -0.5, 0.5, 0.5), replacement,
size, color, baseline,
))
for region in profile.word_regions:
if page_index not in region.pages:
continue
region_rect = pymupdf.Rect(region.rect)
words = [word for word in page.get_text("words", sort=True)
if region_rect.contains(pymupdf.Rect(word[:4]))]
row_numbers: dict[float, int] = {}
for word in words:
rect = pymupdf.Rect(word[:4])
row_key = round(rect.y0, 1)
if row_key not in row_numbers:
row_numbers[row_key] = len(row_numbers) + 1
column_base = 700000 if rect.x0 < region_rect.x0 + region_rect.width / 2 else 500000
value = column_base + _seed(source.name) * 10 + row_numbers[row_key] * 7.13
replacement = f"{value:.2f}"
size, color, baseline = _style(page, rect)
_add_text(text_candidates, TextCandidate(
region.category, rect + (-0.5, -0.5, 0.5, 0.5), replacement,
size, color, baseline,
))
for rect in logos:
page.add_redact_annot(rect, fill=logo_fill, cross_out=False)
if logos:
page.apply_redactions(
images=pymupdf.PDF_REDACT_IMAGE_PIXELS,
graphics=pymupdf.PDF_REDACT_LINE_ART_REMOVE_IF_COVERED,
text=pymupdf.PDF_REDACT_TEXT_REMOVE,
)
audit.redactions["logo"] += len(logos)
for candidate in text_candidates:
page.add_redact_annot(candidate.rect, fill=False, cross_out=False)
if text_candidates:
page.apply_redactions(
images=pymupdf.PDF_REDACT_IMAGE_NONE,
graphics=pymupdf.PDF_REDACT_LINE_ART_NONE,
text=pymupdf.PDF_REDACT_TEXT_REMOVE,
)
for candidate in text_candidates:
_insert_replacement(page, candidate)
audit.redactions[candidate.category] += 1
values = audit.synthetic_values[candidate.category]
if candidate.replacement not in values:
values.append(candidate.replacement)
if profile.scrub:
document.scrub(
attached_files=True, clean_pages=True, embedded_files=True, hidden_text=True,
javascript=True, metadata=True, redactions=True, redact_images=0,
remove_links=False, reset_fields=True, reset_responses=True, thumbnails=True,
xml_metadata=True,
)
else:
document.set_metadata({})
document.del_xml_metadata()
destination.parent.mkdir(parents=True, exist_ok=True)
document.save(destination, garbage=4, clean=True, deflate=True)
document.close()
expected = set(CATEGORIES) - set(profile.not_applicable)
audit.missing = sorted(category for category in expected if audit.redactions[category] == 0)
if audit.missing:
audit.status = "warning"
# Verify that original sensitive values are gone and replacements exist.
check = pymupdf.open(destination)
leaked: list[str] = []
for category, terms in profile.terms.items():
for term in terms:
if any(page.search_for(term) for page in check):
leaked.append(f"{category}:{term}")
missing_fakes: list[str] = []
for category, values in audit.synthetic_values.items():
for value in values:
if not any(page.search_for(value) for page in check):
missing_fakes.append(f"{category}:{value}")
check.close()
if leaked:
raise RuntimeError("post-redaction verification failed: " + ", ".join(leaked))
if missing_fakes:
raise RuntimeError("synthetic text verification failed: " + ", ".join(missing_fakes))
return audit
except Exception as exc: # one corrupt file should not hide the remaining audit
audit.status = "error"
audit.error = str(exc)
return audit
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("inputs", nargs="*", type=Path, help="PDF files/directories; defaults to DDR templates")
parser.add_argument("--output-dir", type=Path, default=Path("pseudonymized"))
parser.add_argument("--audit", type=Path, help="audit JSON path; defaults to OUTPUT_DIR/audit.json")
parser.add_argument(
"--logo-fill", "--fill", dest="logo_fill", choices=("black", "white"), default="white",
help="color used to hide logos (default: white)",
)
parser.add_argument("--strict", action="store_true", help="fail instead of skipping unprofiled/scanned PDFs")
return parser.parse_args(argv)
def main(argv: Sequence[str] | None = None) -> int:
args = parse_args(argv)
try:
inputs = args.inputs or [_default_input()]
sources = _pdfs(inputs)
except (FileNotFoundError, OSError) as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
root = inputs[0] if len(inputs) == 1 and inputs[0].is_dir() else None
logo_fill = (0.0, 0.0, 0.0) if args.logo_fill == "black" else (1.0, 1.0, 1.0)
audits: list[FileAudit] = []
for source in sources:
profile = PROFILES.get(source.name)
if profile is None:
audit = FileAudit(str(source), "", "error" if args.strict else "skipped")
audit.error = "no vector-template profile (scanned PDFs are intentionally excluded)"
audits.append(audit)
continue
relative = source.relative_to(root) if root and source.is_relative_to(root) else Path(source.name)
destination = args.output_dir / relative
audit = redact_pdf(source, destination, profile, logo_fill)
audits.append(audit)
counts = ", ".join(f"{key}={value}" for key, value in audit.redactions.items())
print(f"{audit.status:7} {source} -> {destination} ({counts})")
audit_path = args.audit or args.output_dir / "audit.json"
audit_path.parent.mkdir(parents=True, exist_ok=True)
audit_path.write_text(json.dumps([asdict(item) for item in audits], indent=2), encoding="utf-8")
errors = sum(item.status == "error" for item in audits)
warnings = sum(item.status == "warning" for item in audits)
skipped = sum(item.status == "skipped" for item in audits)
print(f"\nAudit: {audit_path} | files={len(audits)} errors={errors} warnings={warnings} skipped={skipped}")
return 1 if errors or (args.strict and skipped) else 0
if __name__ == "__main__":
raise SystemExit(main())