Upload files to "/"
This commit is contained in:
155
BAO_CAO_KET_QUA.md
Normal file
155
BAO_CAO_KET_QUA.md
Normal file
@@ -0,0 +1,155 @@
|
||||
# Báo cáo kết quả ẩn logo và giả lập thông tin nhạy cảm trong PDF
|
||||
|
||||
## 1. Mục tiêu
|
||||
|
||||
Xử lý bộ tài liệu Daily Drilling Report trong thư mục `DDR templates` để phục vụ huấn luyện Document AI, với các yêu cầu:
|
||||
|
||||
- Ẩn logo doanh nghiệp.
|
||||
- Thay tên giếng bằng dữ liệu giả có hình thức tự nhiên.
|
||||
- Thay tên giàn khoan bằng dữ liệu giả có hình thức tự nhiên.
|
||||
- Thay tọa độ giếng bằng tọa độ giả hợp lệ về mặt định dạng.
|
||||
- Giữ nguyên nhãn trường, bảng biểu, đường kẻ, màu nền và phần nội dung không nhạy cảm.
|
||||
- Không ghi đè lên tài liệu gốc.
|
||||
- Có thể chạy hoàn toàn cục bộ, không cần gọi ChatGPT, GLM hoặc API bên ngoài.
|
||||
|
||||
Ngày tổng hợp báo cáo: **11/09/2026**.
|
||||
|
||||
## 2. Phạm vi dữ liệu
|
||||
|
||||
Bộ dữ liệu đầu vào có tổng cộng 24 tệp PDF:
|
||||
|
||||
- 23 tệp PDF dạng vector được xử lý.
|
||||
- 1 tệp PDF dạng scan là `VIETSOPETRO.pdf`, được chủ động bỏ qua.
|
||||
- Tổng số trang PDF vector đã xử lý: **161 trang**.
|
||||
- Phân bố: 11 tệp trong nhóm `private` và 12 tệp trong nhóm `public`.
|
||||
|
||||
## 3. Phương pháp xử lý
|
||||
|
||||
Chương trình chính là `censor_pdfs.py`, sử dụng PyMuPDF và các cấu hình riêng cho 23 mẫu tài liệu vector.
|
||||
|
||||
Quy trình gồm các bước:
|
||||
|
||||
1. Xác định mẫu tài liệu dựa trên tên tệp.
|
||||
2. Phát hiện logo ảnh raster nằm ở phần đầu trang và các logo dạng chữ/vector đã được cấu hình.
|
||||
3. Xóa vĩnh viễn đối tượng logo và thay vùng logo bằng nền trắng theo mặc định.
|
||||
4. Tìm các chuỗi tên giếng, tên giàn khoan và tọa độ tại mọi trang.
|
||||
5. Xóa glyph của giá trị gốc nhưng không xóa nhãn trường, đường kẻ hoặc nền bảng.
|
||||
6. Chèn dữ liệu giả vào đúng vị trí với cỡ chữ và màu chữ lấy từ nội dung gốc.
|
||||
7. Xóa nội dung ẩn, metadata, JavaScript, tệp đính kèm và dữ liệu XML khi cấu trúc PDF hỗ trợ.
|
||||
8. Lưu thành tệp PDF mới và kiểm tra lại để bảo đảm giá trị gốc không còn tìm kiếm được.
|
||||
|
||||
Các mã giả được tạo ổn định theo tên tệp, ví dụ:
|
||||
|
||||
- Tên giếng: `WELL-##`.
|
||||
- Tên giàn khoan: `RIG-##`.
|
||||
- Tọa độ: giữ dạng độ, phút, giây và hướng Bắc/Nam/Đông/Tây.
|
||||
- Bảng tọa độ khảo sát của AMAL: thay từng ô số riêng biệt bằng giá trị tọa độ giả.
|
||||
|
||||
Cùng một tệp đầu vào sẽ nhận cùng một bộ mã giả trong các lần chạy khác nhau. Điều này giúp dữ liệu nhất quán giữa nhiều trang của cùng tài liệu.
|
||||
|
||||
## 4. Kết quả tổng hợp
|
||||
|
||||
| Chỉ tiêu | Kết quả |
|
||||
|---|---:|
|
||||
| PDF vector xử lý thành công | 23 |
|
||||
| Tổng số trang đã xử lý | 161 |
|
||||
| Vị trí logo đã ẩn | 195 |
|
||||
| Vị trí tên giếng đã thay | 152 |
|
||||
| Vị trí tên giàn khoan đã thay | 114 |
|
||||
| Vị trí tọa độ đã thay | 38 |
|
||||
| Tệp lỗi | 0 |
|
||||
| Tệp cảnh báo | 0 |
|
||||
| PDF scan bỏ qua | 1 |
|
||||
| Tổng dung lượng đầu ra | 5.251.039 byte |
|
||||
|
||||
Số lượng trong bảng là số vị trí xử lý trên tất cả các trang, không phải số giá trị duy nhất.
|
||||
|
||||
## 5. Kết quả theo từng tệp
|
||||
|
||||
| Tệp | Trang | Logo | Tên giếng | Giàn khoan | Tọa độ | Trạng thái |
|
||||
|---|---:|---:|---:|---:|---:|---|
|
||||
| CuuLong.pdf | 2 | 2 | 4 | 8 | 2 | Đạt |
|
||||
| HarbourEnergy.pdf | 6 | 6 | 1 | 1 | 0 | Đạt |
|
||||
| Hibiscus.pdf | 4 | 4 | 4 | 1 | 0 | Đạt |
|
||||
| HOANGLONG_JOC.pdf | 2 | 2 | 2 | 2 | 0 | Đạt |
|
||||
| Murphy.pdf | 4 | 4 | 5 | 1 | 2 | Đạt |
|
||||
| PetronasCarigali.pdf | 3 | 3 | 3 | 1 | 0 | Đạt |
|
||||
| PVEP_POC-2.pdf | 2 | 2 | 2 | 1 | 2 | Đạt |
|
||||
| PVEP_POC.pdf | 2 | 2 | 2 | 1 | 0 | Đạt |
|
||||
| Sonatrack.pdf | 2 | 1 | 1 | 1 | 2 | Đạt |
|
||||
| THANGLONG_JOC.pdf | 3 | 2 | 2 | 4 | 0 | Đạt |
|
||||
| VIETSOPETRO.pdf | 0 | - | - | - | - | Bỏ qua (PDF scan) |
|
||||
| VIETSOPETRO_2.pdf | 2 | 1 | 2 | 2 | 0 | Đạt |
|
||||
| AMAL.pdf | 30 | 2 | 1 | 2 | 24 | Đạt |
|
||||
| AmourEnergy.pdf | 60 | 100 | 60 | 60 | 0 | Đạt |
|
||||
| Chevron.pdf | 4 | 4 | 4 | 4 | 0 | Đạt |
|
||||
| GPC.pdf | 1 | 1 | 1 | 1 | 2 | Đạt |
|
||||
| HOKCHI.pdf | 9 | 18 | 20 | 9 | 0 | Đạt |
|
||||
| Khalda.pdf | 3 | 1 | 3 | 1 | 0 | Đạt |
|
||||
| NISOC.pdf | 4 | 8 | 5 | 1 | 0 | Đạt |
|
||||
| PETROMINERALES.pdf | 6 | 12 | 18 | 6 | 0 | Đạt |
|
||||
| POGC.pdf | 4 | 8 | 4 | 1 | 2 | Đạt |
|
||||
| SONATRACH.pdf | 3 | 3 | 3 | 3 | 0 | Đạt |
|
||||
| SPD.pdf | 4 | 8 | 4 | 1 | 2 | Đạt |
|
||||
| WellView.pdf | 1 | 1 | 1 | 2 | 0 | Đạt |
|
||||
|
||||
Giá trị `0` ở cột tọa độ có nghĩa là mẫu tài liệu không có tọa độ giếng cần thay hoặc trường tọa độ đang để trống.
|
||||
|
||||
## 6. Kiểm thử và xác minh
|
||||
|
||||
Các bước xác minh đã thực hiện:
|
||||
|
||||
- Chạy 6 bài kiểm thử tự động: tất cả đều đạt.
|
||||
- Mở lại toàn bộ 23 PDF đầu ra bằng PyMuPDF.
|
||||
- Render thử toàn bộ 161 trang để kiểm tra tệp không hỏng.
|
||||
- Kiểm tra chuỗi: thông tin nhạy cảm gốc không còn tìm kiếm được trong PDF đầu ra.
|
||||
- Kiểm tra chuỗi: dữ liệu giả đã được chèn và có thể tìm kiếm được, phù hợp với nhu cầu OCR/Document AI.
|
||||
- Kiểm tra trực quan các mẫu đại diện, bao gồm tài liệu nhiều trang, tài liệu có bảng màu, tài liệu có logo raster/vector và bảng tọa độ khảo sát.
|
||||
|
||||
Kết quả cuối cùng: **23/23 tệp vector đạt yêu cầu, không có lỗi và không có cảnh báo**.
|
||||
|
||||
## 7. Tệp đầu ra
|
||||
|
||||
- PDF đã giả lập dữ liệu: `pseudonymized/private` và `pseudonymized/public`.
|
||||
- Báo cáo kiểm toán máy đọc được: `pseudonymized/audit.json`.
|
||||
- Chương trình xử lý: `censor_pdfs.py`.
|
||||
- Kiểm thử: `test_censor_pdfs.py`.
|
||||
- Khai báo thư viện: `requirements.txt`.
|
||||
|
||||
Thư mục `redacted` là kết quả của phiên bản xử lý cũ dùng hộp che cho toàn bộ trường nhạy cảm. Khi huấn luyện Document AI nên sử dụng thư mục `pseudonymized` vì phiên bản này giữ nguyên nhãn và thay giá trị bằng dữ liệu giả.
|
||||
|
||||
## 8. Cách tái lập kết quả
|
||||
|
||||
```bash
|
||||
cd /Users/tungedng2710/Work/censor_data
|
||||
conda activate ai
|
||||
pip install -r requirements.txt
|
||||
python censor_pdfs.py
|
||||
```
|
||||
|
||||
Mặc định, logo được che bằng nền trắng. Để sử dụng hộp màu đen:
|
||||
|
||||
```bash
|
||||
python censor_pdfs.py --logo-fill black
|
||||
```
|
||||
|
||||
Chạy kiểm thử:
|
||||
|
||||
```bash
|
||||
python -m unittest -v
|
||||
```
|
||||
|
||||
Quy trình trên không gọi ChatGPT, GLM hoặc dịch vụ mạng. Kết nối Internet chỉ có thể cần trong lần đầu cài thư viện bằng `pip` nếu môi trường `ai` chưa có PyMuPDF.
|
||||
|
||||
## 9. Lưu ý và giới hạn
|
||||
|
||||
- Chương trình hiện được cấu hình riêng cho 23 tên tệp và bố cục đã khảo sát. PDF mới có tên hoặc bố cục khác sẽ bị bỏ qua thay vì xử lý phỏng đoán.
|
||||
- `VIETSOPETRO.pdf` là PDF scan nên chưa được xử lý bởi quy trình vector này. Muốn xử lý cần thêm OCR và phát hiện vùng trên ảnh.
|
||||
- Một số tên giếng hoặc tên giàn khoan xuất hiện trong phần mô tả nghiệp vụ; chương trình thay tất cả lần xuất hiện đã biết để tránh rò rỉ.
|
||||
- Tệp nguồn trong `DDR templates` vẫn chứa dữ liệu thật và phải được bảo vệ.
|
||||
- Cấu hình trong mã nguồn chứa các mẫu so khớp rút ra từ tài liệu gốc. Không nên phát hành công khai `censor_pdfs.py` nếu chưa tách hoặc mã hóa phần cấu hình nhạy cảm.
|
||||
- Nên kiểm tra trực quan lại nếu bổ sung mẫu PDF mới hoặc thay đổi logic tạo dữ liệu giả.
|
||||
|
||||
## 10. Kết luận
|
||||
|
||||
Quy trình đã tạo thành công bộ PDF có bố cục gần như nguyên bản, logo được ẩn và các trường nhạy cảm được thay bằng dữ liệu giả có thể đọc/trích xuất. Bộ kết quả trong `pseudonymized` phù hợp hơn bản che đen để huấn luyện mô hình Document AI vì vẫn giữ được quan hệ giữa nhãn trường, vị trí và giá trị văn bản.
|
||||
510
censor_pdfs.py
Normal file
510
censor_pdfs.py
Normal file
@@ -0,0 +1,510 @@
|
||||
#!/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())
|
||||
315
classify_pdf.py
Normal file
315
classify_pdf.py
Normal file
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Classify PDFs as vector or scanned using Poppler command-line tools.
|
||||
|
||||
The classifier does not inspect producer metadata or filenames. It measures the
|
||||
physical coverage of embedded raster images and combines that with extractable
|
||||
text/font evidence. This also detects OCR'd scans: a page-sized image wins over
|
||||
an invisible OCR text layer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
|
||||
REQUIRED_TOOLS = ("pdfinfo", "pdfimages", "pdftotext", "pdffonts")
|
||||
DEFAULT_DIRECTORIES = (Path("DDR_Templates"), Path("DDR templates"))
|
||||
PAGE_SIZE_RE = re.compile(
|
||||
r"^Page\s+(\d+)\s+size:\s+([0-9.]+)\s+x\s+([0-9.]+)\s+pts", re.MULTILINE
|
||||
)
|
||||
PAGE_COUNT_RE = re.compile(r"^Pages:\s+(\d+)", re.MULTILINE)
|
||||
|
||||
|
||||
class ClassificationError(RuntimeError):
|
||||
"""Raised when a PDF cannot be inspected."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PageEvidence:
|
||||
page: int
|
||||
text_characters: int
|
||||
max_image_coverage: float
|
||||
classification: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PDFResult:
|
||||
path: str
|
||||
classification: str
|
||||
confidence: float
|
||||
pages: int
|
||||
scanned_pages: int
|
||||
vector_pages: int
|
||||
font_count: int
|
||||
text_characters: int
|
||||
max_image_coverage: float
|
||||
reason: str
|
||||
error: str | None = None
|
||||
|
||||
|
||||
def _run(command: Sequence[str], timeout: int = 60) -> str:
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
command,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
errors="replace",
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise ClassificationError(f"command timed out: {command[0]}") from exc
|
||||
except OSError as exc:
|
||||
raise ClassificationError(f"could not run {command[0]}: {exc}") from exc
|
||||
|
||||
if completed.returncode:
|
||||
detail = completed.stderr.strip() or "unknown error"
|
||||
raise ClassificationError(f"{command[0]} failed: {detail}")
|
||||
return completed.stdout
|
||||
|
||||
|
||||
def _page_geometry(pdf: Path) -> tuple[int, dict[int, float]]:
|
||||
output = _run(["pdfinfo", "-box", str(pdf)])
|
||||
count_match = PAGE_COUNT_RE.search(output)
|
||||
if not count_match:
|
||||
raise ClassificationError("pdfinfo did not report a page count")
|
||||
page_count = int(count_match.group(1))
|
||||
|
||||
# Some pdfinfo versions only print every page size when -f/-l is explicit.
|
||||
output = _run(["pdfinfo", "-f", "1", "-l", str(page_count), "-box", str(pdf)])
|
||||
areas = {
|
||||
int(page): float(width) * float(height)
|
||||
for page, width, height in PAGE_SIZE_RE.findall(output)
|
||||
}
|
||||
if len(areas) != page_count:
|
||||
# Fall back to the generic page size for PDFs whose pages are uniform.
|
||||
generic = re.search(
|
||||
r"^Page size:\s+([0-9.]+)\s+x\s+([0-9.]+)\s+pts", output, re.MULTILINE
|
||||
)
|
||||
if generic:
|
||||
area = float(generic.group(1)) * float(generic.group(2))
|
||||
areas = {page: area for page in range(1, page_count + 1)}
|
||||
if len(areas) != page_count:
|
||||
raise ClassificationError("pdfinfo did not report every page size")
|
||||
return page_count, areas
|
||||
|
||||
|
||||
def _image_coverage(pdf: Path, page_areas: dict[int, float]) -> dict[int, float]:
|
||||
"""Return the largest image's displayed-area ratio for each page.
|
||||
|
||||
pdfimages reports image dimensions and effective x/y DPI. Those values let
|
||||
us recover the image's displayed size in PDF points without parsing streams.
|
||||
"""
|
||||
output = _run(["pdfimages", "-list", str(pdf)])
|
||||
coverage = {page: 0.0 for page in page_areas}
|
||||
for line in output.splitlines()[2:]:
|
||||
columns = line.split()
|
||||
if len(columns) < 14 or columns[2] not in {"image", "mask", "smask"}:
|
||||
continue
|
||||
try:
|
||||
page = int(columns[0])
|
||||
width_px = int(columns[3])
|
||||
height_px = int(columns[4])
|
||||
x_dpi = float(columns[12])
|
||||
y_dpi = float(columns[13])
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
if page not in page_areas or x_dpi <= 0 or y_dpi <= 0:
|
||||
continue
|
||||
displayed_area = (width_px * 72.0 / x_dpi) * (height_px * 72.0 / y_dpi)
|
||||
ratio = min(displayed_area / page_areas[page], 1.0)
|
||||
coverage[page] = max(coverage[page], ratio)
|
||||
return coverage
|
||||
|
||||
|
||||
def _text_by_page(pdf: Path, page_count: int) -> list[int]:
|
||||
output = _run(["pdftotext", "-enc", "UTF-8", str(pdf), "-"])
|
||||
pages = output.split("\f")
|
||||
if pages and not pages[-1].strip():
|
||||
pages.pop()
|
||||
pages.extend([""] * max(0, page_count - len(pages)))
|
||||
return [sum(not char.isspace() for char in text) for text in pages[:page_count]]
|
||||
|
||||
|
||||
def _font_count(pdf: Path) -> int:
|
||||
output = _run(["pdffonts", str(pdf)])
|
||||
lines = output.splitlines()
|
||||
return sum(bool(line.strip()) for line in lines[2:])
|
||||
|
||||
|
||||
def _classify_pages(
|
||||
text_counts: Sequence[int], image_coverage: dict[int, float], font_count: int
|
||||
) -> list[PageEvidence]:
|
||||
evidence: list[PageEvidence] = []
|
||||
for page, text_count in enumerate(text_counts, start=1):
|
||||
coverage = image_coverage.get(page, 0.0)
|
||||
if coverage >= 0.72:
|
||||
page_class = "scanned"
|
||||
elif text_count >= 20:
|
||||
page_class = "vector"
|
||||
elif coverage >= 0.25 and text_count < 20:
|
||||
page_class = "scanned"
|
||||
elif font_count and text_count:
|
||||
page_class = "vector"
|
||||
else:
|
||||
page_class = "unknown"
|
||||
evidence.append(PageEvidence(page, text_count, coverage, page_class))
|
||||
return evidence
|
||||
|
||||
|
||||
def classify_pdf(pdf: str | Path) -> PDFResult:
|
||||
"""Classify one PDF and return its evidence summary."""
|
||||
path = Path(pdf)
|
||||
try:
|
||||
page_count, page_areas = _page_geometry(path)
|
||||
coverage = _image_coverage(path, page_areas)
|
||||
text_counts = _text_by_page(path, page_count)
|
||||
fonts = _font_count(path)
|
||||
page_evidence = _classify_pages(text_counts, coverage, fonts)
|
||||
scanned = sum(item.classification == "scanned" for item in page_evidence)
|
||||
vector = sum(item.classification == "vector" for item in page_evidence)
|
||||
informative = scanned + vector
|
||||
|
||||
if informative == 0:
|
||||
# Empty/blank PDFs have no scan evidence, so vector is the safer class.
|
||||
classification = "vector"
|
||||
confidence = 0.5
|
||||
reason = "no page-sized raster images or extractable text found"
|
||||
else:
|
||||
scan_ratio = scanned / informative
|
||||
classification = "scanned" if scan_ratio >= 0.5 else "vector"
|
||||
confidence = 0.5 + abs(scan_ratio - 0.5)
|
||||
if classification == "scanned":
|
||||
reason = f"{scanned}/{informative} informative pages are raster-dominant"
|
||||
else:
|
||||
reason = f"{vector}/{informative} informative pages contain native text/vector content"
|
||||
|
||||
return PDFResult(
|
||||
path=str(path),
|
||||
classification=classification,
|
||||
confidence=round(confidence, 3),
|
||||
pages=page_count,
|
||||
scanned_pages=scanned,
|
||||
vector_pages=vector,
|
||||
font_count=fonts,
|
||||
text_characters=sum(text_counts),
|
||||
max_image_coverage=round(max(coverage.values(), default=0.0), 3),
|
||||
reason=reason,
|
||||
)
|
||||
except ClassificationError as exc:
|
||||
return PDFResult(
|
||||
path=str(path), classification="error", confidence=0.0, pages=0,
|
||||
scanned_pages=0, vector_pages=0, font_count=0, text_characters=0,
|
||||
max_image_coverage=0.0, reason="classification failed", error=str(exc),
|
||||
)
|
||||
|
||||
|
||||
def _find_default_directory() -> Path:
|
||||
for directory in DEFAULT_DIRECTORIES:
|
||||
if directory.is_dir():
|
||||
return directory
|
||||
names = " or ".join(str(path) for path in DEFAULT_DIRECTORIES)
|
||||
raise ClassificationError(f"default input directory not found ({names})")
|
||||
|
||||
|
||||
def _pdf_paths(inputs: Iterable[str]) -> list[Path]:
|
||||
paths: list[Path] = []
|
||||
for raw_path in inputs:
|
||||
path = Path(raw_path)
|
||||
if path.is_file() and path.suffix.lower() == ".pdf":
|
||||
paths.append(path)
|
||||
elif path.is_dir():
|
||||
paths.extend(candidate for candidate in path.rglob("*") if candidate.suffix.lower() == ".pdf")
|
||||
else:
|
||||
raise ClassificationError(f"not a PDF file or directory: {path}")
|
||||
return sorted(set(paths), key=lambda item: str(item).lower())
|
||||
|
||||
|
||||
def _write_results(results: Sequence[PDFResult], output_format: str, stream: object) -> None:
|
||||
rows = [asdict(result) for result in results]
|
||||
if output_format == "json":
|
||||
json.dump(rows, stream, indent=2, ensure_ascii=False)
|
||||
stream.write("\n")
|
||||
elif output_format == "csv":
|
||||
writer = csv.DictWriter(stream, fieldnames=list(PDFResult.__dataclass_fields__))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
else:
|
||||
headers = ("CLASS", "CONF", "PAGES", "MAX IMAGE", "TEXT", "PATH")
|
||||
display_rows = [
|
||||
(
|
||||
result.classification,
|
||||
f"{result.confidence:.0%}",
|
||||
str(result.pages),
|
||||
f"{result.max_image_coverage:.0%}",
|
||||
str(result.text_characters),
|
||||
result.path,
|
||||
)
|
||||
for result in results
|
||||
]
|
||||
widths = [
|
||||
max(len(headers[index]), *(len(row[index]) for row in display_rows))
|
||||
for index in range(len(headers))
|
||||
] if display_rows else [len(header) for header in headers]
|
||||
stream.write(" ".join(value.ljust(width) for value, width in zip(headers, widths)) + "\n")
|
||||
stream.write(" ".join("-" * width for width in widths) + "\n")
|
||||
for row in display_rows:
|
||||
stream.write(" ".join(value.ljust(width) for value, width in zip(row, widths)) + "\n")
|
||||
|
||||
|
||||
def _check_tools() -> None:
|
||||
missing = [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None]
|
||||
if missing:
|
||||
raise ClassificationError(
|
||||
"missing Poppler tools: " + ", ".join(missing) + ". Install poppler first."
|
||||
)
|
||||
|
||||
|
||||
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"inputs", nargs="*", help="PDF file(s) or directories (default: DDR_Templates/DDR templates)"
|
||||
)
|
||||
parser.add_argument("--format", choices=("table", "json", "csv"), default="table")
|
||||
parser.add_argument("--output", type=Path, help="write results to this file instead of stdout")
|
||||
parser.add_argument("--workers", type=int, default=4, help="parallel PDF inspections (default: 4)")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
args = parse_args(argv)
|
||||
try:
|
||||
_check_tools()
|
||||
inputs = args.inputs or [str(_find_default_directory())]
|
||||
pdfs = _pdf_paths(inputs)
|
||||
if not pdfs:
|
||||
raise ClassificationError("no PDF files found")
|
||||
workers = max(1, min(args.workers, len(pdfs)))
|
||||
with ThreadPoolExecutor(max_workers=workers) as executor:
|
||||
results = list(executor.map(classify_pdf, pdfs))
|
||||
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with args.output.open("w", encoding="utf-8", newline="") as stream:
|
||||
_write_results(results, args.format, stream)
|
||||
else:
|
||||
_write_results(results, args.format, sys.stdout)
|
||||
return int(any(result.error for result in results))
|
||||
except ClassificationError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
1
requirements.txt
Normal file
1
requirements.txt
Normal file
@@ -0,0 +1 @@
|
||||
pymupdf>=1.28,<2
|
||||
39
test_censor_pdfs.py
Normal file
39
test_censor_pdfs.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import pymupdf
|
||||
|
||||
from censor_pdfs import Profile, RectRule, _logo_images, redact_pdf
|
||||
|
||||
|
||||
class CensorPDFTests(unittest.TestCase):
|
||||
def test_redaction_replaces_sensitive_text(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source = Path(directory) / "source.pdf"
|
||||
output = Path(directory) / "output.pdf"
|
||||
document = pymupdf.open()
|
||||
page = document.new_page()
|
||||
page.insert_text((72, 72), "Well Name: SECRET-WELL")
|
||||
page.insert_text((72, 100), "Keep this text")
|
||||
document.save(source)
|
||||
document.close()
|
||||
|
||||
profile = Profile(terms={"well_name": ("SECRET-WELL",)}, not_applicable=("logo", "rig_name", "coordinates"))
|
||||
audit = redact_pdf(source, output, profile, (0.0, 0.0, 0.0))
|
||||
self.assertEqual(audit.status, "ok")
|
||||
redacted = pymupdf.open(output)
|
||||
text = "".join(page.get_text() for page in redacted)
|
||||
redacted.close()
|
||||
self.assertNotIn("SECRET-WELL", text)
|
||||
self.assertIn("WELL-", text)
|
||||
self.assertIn("Keep this text", text)
|
||||
|
||||
def test_rectangle_rule_tracks_logo_region(self):
|
||||
rule = RectRule("rig_name", (10, 20, 100, 40), (0,))
|
||||
self.assertEqual(rule.category, "rig_name")
|
||||
self.assertEqual(rule.pages, (0,))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user