upload version 2

This commit is contained in:
2026-09-17 01:55:47 +00:00
parent 258c34e211
commit d8498b8361
4 changed files with 897 additions and 0 deletions

392
censor_pdfs_v2.py Normal file
View File

@@ -0,0 +1,392 @@
#!/usr/bin/env python3
"""Pseudonymize DDR PDFs, including personal names (version 2).
Version 2 extends ``censor_pdfs.py``. It still hides logos and replaces well
names, rig names, and coordinates, then permanently removes known personal names
and inserts deterministic synthetic names in the same positions.
No LLM, network service, or external API is used at runtime.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
import tempfile
from dataclasses import asdict, dataclass, field, replace
from pathlib import Path
from typing import Iterable, Sequence
import pymupdf
import censor_pdfs as v1
PERSON_TERMS: dict[str, tuple[str, ...]] = {
"CuuLong.pdf": ("Micheal Ting", "Nguyen Hong Hiep"),
"HOANGLONG_JOC.pdf": (
"Yong Kong Hai", "Mike Budrow", "Bui Xuan Them", "Tran Nam",
"L.H. Phuong", "Chu The Phong", "Kevin Jamie Howlett",
),
"HarbourEnergy.pdf": (
"Ray Third", "Pham The Thuc", "Nham Xuan Bich", "Phu / Ho",
"William James", "Le Tran Hau",
),
"Hibiscus.pdf": ("Anne / Afzan", "Muzily / Hakimi", "Nor Hazlindah"),
"Murphy.pdf": ("Trung Pham", "Andy Patrickis", "Lindsay McCracken", "Jason Hewit"),
"PVEP_POC-2.pdf": (
"Dave Spink / NH Hiep / LT Thinh", "VH Sang / CV Dinh", "NM Cuong",
"NDN Tri / RV Viet / DS Ha",
),
"PVEP_POC.pdf": ("Steve Lees/L.H.Khoat", "Nguyen Duy Sam"),
"PetronasCarigali.pdf": ("Iskanta/Aswade/Azlan",),
"Sonatrack.pdf": ("H.Bouadou//K.Hadjab", "A. Chellali"),
"THANGLONG_JOC.pdf": (
"Mike Turgeon", "Pham The Thuc", "Mark Sword", "Kishore Kelamparabil",
"Tran Ba Hung",
),
"VIETSOPETRO_2.pdf": ("Nguyen Van Tien", "Nguyen Thanh Hieu"),
"AMAL.pdf": ("MOHAMED HASHEM", "MOHAMED SABER", "ISLAM BADR"),
"AmourEnergy.pdf": (
"Shane Bennett", "Shane Bennet", "Don Castles", "Jon Martin",
"Damian Paranihi", "Dexter", "Matthew Morgan",
),
"Chevron.pdf": (
"HASAN ARAFAT", "Shayne Atkins", "Stephen Joubert", "Mahbubur Rahman",
"Ismail Hossain", "Jay Darder",
),
"GPC.pdf": ("HANY MESALLAM", "MAHMOUD TAIMOUR"),
"HOKCHI.pdf": (
"OPORTO, RAUL", "McCASKIE, ROBIN", "TERRERA, DIEGO", "SMITH, WALLACE",
"LUAN, XIAO WEI", "JOEL DE LA FUENTE",
),
"Khalda.pdf": (
"Abdel kawy Zidan", "khaled abd El-naser", "Mohamed Maher Mostafa",
"Mohamed Mousa", "Ashraf Adel Shawky Helal", "mohamed mahmoud reda",
),
"NISOC.pdf": (
"Mehdi Farahani", "A.Bozorgi", "M.Rasouli/E.Mondanipour", "H.Bonyadi",
"A.Asghari", "M.Salmani", "R.Rezaee/M.Ameri",
),
"PETROMINERALES.pdf": (
"J. BARRERA / W. BAQUERO", "FERNANDO ROMERO / FELIX CUADROS",
),
"POGC.pdf": (
"Mohamad Reza Kazemi", "Sajad Nouri", "Behnam Fattahi", "Mohsen Karami",
"M.Alipour/S.Sadeghi",
),
"SONATRACH.pdf": (
"S.DOUADI / A.ROUAIGUIA", "S,BENSEMCHA+S,DOUADI", "F,BENGASMI",
"A,BELABBAS", "M,AMROUNE", "H,KARA", "A.SAOUD", "L.BENACHI",
"A,YOUSFI", "K,MESSAOUD", "H,SALEM", "N,ABBASSEN", "S,MIKAOUSSI",
"A,KIRECHE",
),
"SPD.pdf": (
"Mohamad Reza Kazemi", "Sajad Nouri", "Behnam Fattahi", "Mohsen Karami",
"M.Alipour/S.Sadeghi",
),
"WellView.pdf": ("Tom Black", "Jim Green", "David Brown", "Sam White"),
}
# Company names that are part of a document title/header are replaced with
# synthetic text. Raster logos are still hidden by the v1 stage. CuuLong's
# replacement is explicitly specified; the others are plausible fake names.
COMPANY_TITLE_TERMS: dict[str, tuple[tuple[str, str], ...]] = {
"CuuLong.pdf": (("CLJOC", "CLCORP"),),
"HOANGLONG_JOC.pdf": (("HOANG LONG JOC", "HORIZON JOC"),),
"Hibiscus.pdf": ((
"Hibiscus Oil & Gas Malaysia Limited",
"Bluewave Oil & Gas Malaysia Limited",
),),
"PetronasCarigali.pdf": ((
"PETRONAS CARIGALI SDN BHD",
"MERIDIAN ENERGY SDN BHD",
),),
"THANGLONG_JOC.pdf": (("TLJOC", "TLCORP"),),
"VIETSOPETRO_2.pdf": (("VIETSOVPETRO", "BLUESEA ENERGY"),),
"AmourEnergy.pdf": (("ARMOUR ENERGY LTD", "NORTHRIDGE ENERGY LTD"),),
"Chevron.pdf": (("Chevron Bangladesh", "Horizon Bangladesh"),),
"GPC.pdf": (("G.P.C", "R.P.C"),),
"HOKCHI.pdf": ((
"HOKCHI ENERGY S.A. de C.V.",
"NOVA ENERGY S.A. de C.V.",
),),
"PETROMINERALES.pdf": ((
"PETROMINERALES PERU S.A.",
"ANDES ENERGY PERU S.A.",
),),
"SONATRACH.pdf": (("SONATRACH", "SAHARA ENERGY"),),
}
FIRST_NAMES = (
"Alex", "Avery", "Cameron", "Casey", "Dylan", "Elliot", "Hayden", "Jamie",
"Jordan", "Morgan", "Parker", "Quinn", "Riley", "Robin", "Rowan", "Sam",
"Taylor",
)
LAST_NAMES = (
"Adams", "Baker", "Carter", "Davis", "Evans", "Foster", "Garcia", "Harris",
"Ito", "Khan", "Lewis", "Martin", "Nguyen", "Patel", "Reed", "Silva",
"Turner", "Walker", "Young",
)
ALIASES = {"Shane Bennet": "Shane Bennett"}
@dataclass
class V2Audit:
input: str
output: str
status: str
pages: int = 0
replacements: dict[str, int] = field(default_factory=dict)
synthetic_values: dict[str, list[str]] = field(default_factory=dict)
missing: list[str] = field(default_factory=list)
error: str | None = None
def _hash_int(value: str) -> int:
return int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:16], 16)
def _one_fake_name(key: str, index: int = 0) -> str:
value = _hash_int(f"{key}:{index}")
first = FIRST_NAMES[value % len(FIRST_NAMES)]
last = LAST_NAMES[(value // len(FIRST_NAMES)) % len(LAST_NAMES)]
return f"{first} {last}"
def fake_person_name(original: str) -> str:
"""Return a stable, human-looking replacement while preserving list shape."""
canonical = ALIASES.get(original, original)
parts = [part.strip() for part in re.split(r"/{1,2}|\+", canonical) if part.strip()]
if len(parts) > 1:
return " / ".join(_one_fake_name(canonical, index) for index in range(len(parts)))
comma_name = re.fullmatch(r"([A-Za-z.]+),\s*([A-Za-z. ]+)", canonical)
fake = _one_fake_name(canonical)
first, last = fake.split(" ", 1)
if comma_name:
if len(comma_name.group(1).replace(".", "")) == 1:
return f"{first[0]},{last.upper()}"
return f"{last.upper()}, {first.upper()}"
if re.match(r"^[A-Za-z]\.", canonical):
return f"{first[0]}. {last}"
if canonical.isupper():
return fake.upper()
return fake
def _profile_for_v2(original_filename: str) -> v1.Profile:
"""Keep title text for replacement while retaining raster-logo removal."""
profile = v1.PROFILES[original_filename]
if original_filename not in COMPANY_TITLE_TERMS:
return profile
terms = {category: tuple(values) for category, values in profile.terms.items()}
# These text entries represented company-name headers in v1. V2 replaces
# them instead of blanking them; image-based logos are still detected.
terms.pop("logo", None)
rectangles = tuple(rule for rule in profile.rectangles if rule.category != "logo")
not_applicable = tuple(dict.fromkeys((*profile.not_applicable, "logo")))
return replace(
profile, terms=terms, rectangles=rectangles,
not_applicable=not_applicable,
)
def _replace_configured_text(
source: Path,
destination: Path,
original_filename: str,
scrub: bool,
categories: tuple[str, ...] = ("person_name", "company_title"),
) -> tuple[dict[str, int], dict[str, list[str]]]:
replacements: dict[str, dict[str, str]] = {}
if "person_name" in categories:
replacements["person_name"] = {
term: fake_person_name(term) for term in PERSON_TERMS[original_filename]
}
if "company_title" in categories:
replacements["company_title"] = dict(
COMPANY_TITLE_TERMS.get(original_filename, ())
)
document = pymupdf.open(source)
replacement_counts = {category: 0 for category in categories}
inserted_values = {category: set() for category in categories}
for page in document:
candidates: list[v1.TextCandidate] = []
# Longer strings go first so an abbreviated name inside a full name does
# not create overlapping redaction annotations.
configured = [
(category, term, synthetic)
for category, mapping in replacements.items()
for term, synthetic in mapping.items()
]
for category, term, synthetic in sorted(configured, key=lambda item: len(item[1]), reverse=True):
for rect in page.search_for(term):
size, color, baseline = v1._style(page, rect)
v1._add_text(candidates, v1.TextCandidate(
category, rect + (-0.5, -0.5, 0.5, 0.5), synthetic,
size, color, baseline,
))
for candidate in candidates:
page.add_redact_annot(candidate.rect, fill=False, cross_out=False)
if 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 candidates:
v1._insert_replacement(page, candidate)
replacement_counts[candidate.category] += 1
inserted_values[candidate.category].add(candidate.replacement)
if 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()
check = pymupdf.open(destination)
leaked = [
term
for mapping in replacements.values()
for term in mapping
if any(page.search_for(term) for page in check)
]
inserted = {
category: sorted(values) for category, values in inserted_values.items()
}
missing_fakes = [
value
for values in inserted.values()
for value in values
if not any(page.search_for(value) for page in check)
]
check.close()
if leaked:
raise RuntimeError("sensitive text still searchable: " + ", ".join(leaked))
if missing_fakes:
raise RuntimeError("synthetic text not searchable: " + ", ".join(missing_fakes))
return replacement_counts, inserted
def _replace_people(
source: Path, destination: Path, original_filename: str, scrub: bool
) -> tuple[int, list[str]]:
"""Backward-compatible helper used by the focused person-name tests."""
counts, inserted = _replace_configured_text(
source, destination, original_filename, scrub, ("person_name",)
)
return counts["person_name"], inserted["person_name"]
def _build_audit(source: Path, destination: Path, stage1: v1.FileAudit) -> V2Audit:
profile = v1.PROFILES[source.name]
text_counts, inserted = _replace_configured_text(
Path(stage1.output), destination, source.name, profile.scrub
)
replacements = dict(stage1.redactions)
replacements.update(text_counts)
synthetic = {key: list(values) for key, values in stage1.synthetic_values.items()}
synthetic.update(inserted)
missing = list(stage1.missing)
if not text_counts["person_name"]:
missing.append("person_name")
if source.name in COMPANY_TITLE_TERMS and not text_counts["company_title"]:
missing.append("company_title")
return V2Audit(
input=str(source), output=str(destination),
status="warning" if missing else "ok", pages=stage1.pages,
replacements=replacements, synthetic_values=synthetic, missing=missing,
)
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_v2"))
parser.add_argument("--audit", type=Path, help="audit JSON path; defaults to OUTPUT_DIR/audit.json")
parser.add_argument(
"--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 [v1._default_input()]
sources = v1._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[V2Audit] = []
with tempfile.TemporaryDirectory(prefix="censor-pdf-v2-") as temporary:
stage_root = Path(temporary)
for source in sources:
profile = (
_profile_for_v2(source.name) if source.name in v1.PROFILES else None
)
people = PERSON_TERMS.get(source.name)
if profile is None or people is None:
status = "error" if args.strict else "skipped"
audits.append(V2Audit(
str(source), "", status,
error="no v2 vector-template profile (scanned PDFs are intentionally excluded)",
))
continue
relative = source.relative_to(root) if root and source.is_relative_to(root) else Path(source.name)
stage_path = stage_root / relative
destination = args.output_dir / relative
stage1 = v1.redact_pdf(source, stage_path, profile, logo_fill)
if stage1.status == "error":
audit = V2Audit(
str(source), str(destination), "error", pages=stage1.pages,
error="v1 stage failed: " + (stage1.error or "unknown error"),
)
else:
try:
audit = _build_audit(source, destination, stage1)
except Exception as exc:
audit = V2Audit(
str(source), str(destination), "error", pages=stage1.pages,
error=str(exc),
)
audits.append(audit)
counts = ", ".join(f"{key}={value}" for key, value in audit.replacements.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())