Files
Censor_data/visualize_synthetic_values.py
2026-09-17 01:55:47 +00:00

257 lines
9.0 KiB
Python

#!/usr/bin/env python3
"""Render pseudonymized PDF pages and box every searchable synthetic value."""
from __future__ import annotations
import argparse
import json
import shutil
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Sequence
import pymupdf
from PIL import Image, ImageDraw, ImageFont
CATEGORIES = {
"person_name": {"label": "PERSON", "color": (216, 27, 96)},
"company_title": {"label": "COMPANY", "color": (123, 31, 162)},
"well_name": {"label": "WELL", "color": (21, 101, 192)},
"rig_name": {"label": "RIG", "color": (245, 124, 0)},
"coordinates": {"label": "COORD", "color": (46, 125, 50)},
}
@dataclass(frozen=True)
class Match:
category: str
value: str
rect_points: list[float]
rect_pixels: list[int]
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--audit", type=Path, default=Path("pseudonymized_v2/audit.json"),
help="v2 audit JSON (default: pseudonymized_v2/audit.json)",
)
parser.add_argument(
"--pdf-root", type=Path, default=Path("pseudonymized_v2"),
help="root used to preserve private/public paths",
)
parser.add_argument(
"--output-dir", type=Path, default=Path("visualization"),
help="visualization directory (default: visualization)",
)
parser.add_argument("--dpi", type=int, default=144, help="render resolution")
parser.add_argument(
"--include-empty-pages", action="store_true",
help="also render pages on which no synthetic value was found",
)
parser.add_argument(
"--no-clean", action="store_true",
help="do not clear the output directory before rendering",
)
return parser.parse_args(argv)
def _font(size: int, bold: bool = False) -> ImageFont.ImageFont:
candidates = (
"DejaVuSans-Bold.ttf" if bold else "DejaVuSans.ttf",
"/System/Library/Fonts/Supplemental/Arial Bold.ttf" if bold
else "/System/Library/Fonts/Supplemental/Arial.ttf",
)
for candidate in candidates:
try:
return ImageFont.truetype(candidate, size)
except OSError:
pass
return ImageFont.load_default()
def _find_matches(
page: pymupdf.Page, synthetic_values: dict[str, list[str]], scale: float
) -> list[Match]:
matches: list[Match] = []
seen: set[tuple[str, int, int, int, int]] = set()
for category in CATEGORIES:
for value in synthetic_values.get(category, []):
for rect in page.search_for(value):
pixel_rect = [
round(rect.x0 * scale), round(rect.y0 * scale),
round(rect.x1 * scale), round(rect.y1 * scale),
]
key = (category, *pixel_rect)
if key in seen:
continue
seen.add(key)
matches.append(Match(
category=category,
value=value,
rect_points=[round(number, 3) for number in rect],
rect_pixels=pixel_rect,
))
return matches
def _draw_legend(
draw: ImageDraw.ImageDraw, width: int, header_height: int,
font: ImageFont.ImageFont,
) -> None:
draw.rectangle((0, 0, width, header_height), fill=(248, 249, 250))
draw.line((0, header_height - 1, width, header_height - 1), fill=(180, 180, 180), width=1)
x = 16
box_size = max(12, header_height // 4)
for spec in CATEGORIES.values():
y = (header_height - box_size) // 2
draw.rectangle((x, y, x + box_size, y + box_size), fill=spec["color"])
x += box_size + 7
draw.text((x, y - 1), spec["label"], fill=(30, 30, 30), font=font)
text_box = draw.textbbox((x, y), spec["label"], font=font)
x = text_box[2] + 22
def _draw_match(
draw: ImageDraw.ImageDraw, match: Match, header_height: int, line_width: int,
) -> None:
spec = CATEGORIES[match.category]
color = spec["color"]
x0, y0, x1, y1 = match.rect_pixels
y0 += header_height
y1 += header_height
draw.rectangle((x0, y0, x1, y1), outline=color, width=line_width)
def _render_page(
page: pymupdf.Page, matches: list[Match], destination: Path, dpi: int
) -> None:
pixmap = page.get_pixmap(dpi=dpi, colorspace=pymupdf.csRGB, alpha=False)
page_image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)
scale = dpi / 72
header_height = max(48, round(28 * scale))
canvas = Image.new("RGB", (page_image.width, page_image.height + header_height), "white")
canvas.paste(page_image, (0, header_height))
draw = ImageDraw.Draw(canvas)
legend_font = _font(max(11, round(7.5 * scale)), bold=True)
_draw_legend(draw, canvas.width, header_height, legend_font)
for match in matches:
_draw_match(draw, match, header_height, max(3, round(1.5 * scale)))
destination.parent.mkdir(parents=True, exist_ok=True)
canvas.save(destination, format="PNG", optimize=True)
def main(argv: Sequence[str] | None = None) -> int:
args = parse_args(argv)
if args.dpi < 72:
raise SystemExit("--dpi must be at least 72")
if not args.audit.is_file():
raise SystemExit(f"audit file not found: {args.audit}")
if args.output_dir.exists() and not args.no_clean:
shutil.rmtree(args.output_dir)
args.output_dir.mkdir(parents=True, exist_ok=True)
audits = json.loads(args.audit.read_text(encoding="utf-8"))
scale = args.dpi / 72
images: list[dict[str, object]] = []
category_counts = {category: 0 for category in CATEGORIES}
pages_examined = 0
pages_without_matches = 0
for audit in audits:
if audit.get("status") != "ok":
continue
pdf_path = Path(audit["output"])
if not pdf_path.is_file():
raise SystemExit(f"output PDF not found: {pdf_path}")
try:
relative_pdf = pdf_path.relative_to(args.pdf_root)
except ValueError:
relative_pdf = Path(pdf_path.name)
document = pymupdf.open(pdf_path)
for page_index, page in enumerate(document):
pages_examined += 1
matches = _find_matches(page, audit["synthetic_values"], scale)
if not matches:
pages_without_matches += 1
if not args.include_empty_pages:
continue
image_path = (
args.output_dir / relative_pdf.parent / relative_pdf.stem
/ f"page_{page_index + 1:03d}.png"
)
_render_page(page, matches, image_path, args.dpi)
for match in matches:
category_counts[match.category] += 1
images.append({
"image": str(image_path),
"pdf": str(pdf_path),
"page": page_index + 1,
"width_points": round(page.rect.width, 3),
"height_points": round(page.rect.height, 3),
"matches": [asdict(match) for match in matches],
})
document.close()
manifest = {
"audit": str(args.audit),
"pdf_root": str(args.pdf_root),
"dpi": args.dpi,
"pages_examined": pages_examined,
"pages_rendered": len(images),
"pages_without_matches": pages_without_matches,
"bounding_boxes": sum(category_counts.values()),
"category_counts": category_counts,
"images": images,
}
manifest_path = args.output_dir / "manifest.json"
manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
readme = f"""# Synthetic-value visualizations
This folder contains page images rendered from `{args.pdf_root}` at {args.dpi} DPI.
Only pages containing at least one searchable synthetic value are included.
Color legend:
- Pink: person name (`person_name`)
- Purple: company name in title (`company_title`)
- Blue: well name (`well_name`)
- Orange: rig name (`rig_name`)
- Green: coordinates (`coordinates`)
Summary:
- PDF pages examined: {pages_examined}
- Page images generated: {len(images)}
- Bounding boxes: {manifest['bounding_boxes']}
- Person-name boxes: {category_counts['person_name']}
- Company-title boxes: {category_counts['company_title']}
- Well-name boxes: {category_counts['well_name']}
- Rig-name boxes: {category_counts['rig_name']}
- Coordinate boxes: {category_counts['coordinates']}
`manifest.json` records each image, source PDF, one-based page number, synthetic value,
category, PDF-space rectangle in points, and image-space rectangle in pixels.
Recreate this folder from the project root with:
```bash
conda activate ai
python visualize_synthetic_values.py
```
"""
(args.output_dir / "README.md").write_text(readme, encoding="utf-8")
print(
f"Rendered {len(images)}/{pages_examined} pages with "
f"{manifest['bounding_boxes']} boxes into {args.output_dir}"
)
print("Category counts:", ", ".join(f"{k}={v}" for k, v in category_counts.items()))
print(f"Manifest: {manifest_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())