-
Notifications
You must be signed in to change notification settings - Fork 9
/
json_consistency.py
178 lines (151 loc) · 5.53 KB
/
json_consistency.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import datetime
import json
import logging
import sys
from pathlib import Path
from pydantic import BaseModel, NonNegativeInt
from pypdf import PdfReader
logger = logging.getLogger()
logger.level = logging.ERROR
class AnnotationCount(BaseModel):
Highlight: int | None = None
Ink: int | None = None
Link: int | None = None
Text: int | None = None
Widget: int | None = None
def items(self) -> list[tuple[str, int]]:
return [
("Highlight", self.Highlight if self.Highlight else 0),
("Link", self.Link if self.Link else 0),
("Ink", self.Ink if self.Ink else 0),
("Text", self.Text if self.Text else 0),
("Widget", self.Widget if self.Widget else 0),
]
def sum(self) -> int:
return sum(value for _, value in self.items())
class PdfEntry(BaseModel):
path: str
encrypted: bool
producer: str | None
pages: NonNegativeInt
images: NonNegativeInt | None
forms: NonNegativeInt
creation_date: datetime.datetime | None
annotations: AnnotationCount
class MainPdfFile(BaseModel):
data: list[PdfEntry]
def main() -> None:
"""Check the consistency of the JSON metadata file."""
with open("files.json") as f:
data = json.load(f)
main_pdf = MainPdfFile.model_validate(data)
registered_pdfs = []
seen_failure = False
for entry in main_pdf.data:
registered_pdfs.append(entry.path)
if not Path(entry.path).exists():
print(f"❌ ERROR: File not found: {entry.path}")
seen_failure = True
else:
print(f"✅ Found {entry.path}")
seen_failure = seen_failure or check_meta(entry)
# Are all files registered?
pdf_paths = Path().glob("**/*.pdf")
for pdf_path in pdf_paths:
if str(pdf_path) not in registered_pdfs:
print(f"❌ ERROR: File not registered: {pdf_path}")
seen_failure = True
if seen_failure:
sys.exit(1)
def pdf_to_datetime(date_str: str | None) -> datetime.datetime | None:
"""Convert a PDF datetime string to a datetime object."""
if date_str is None:
return None
if not date_str.startswith("D:"):
print(f"❌ ERROR: Invalid date: {date_str}")
date_str = date_str[2:]
if len(date_str) < 14:
print(f"❌ ERROR: Invalid date: {date_str}")
return datetime.datetime(
int(date_str[0:4]), # year
int(date_str[4:6]), # month
int(date_str[6:8]), # day
int(date_str[8:10]), # hour
int(date_str[10:12]), # minute
int(date_str[12:14]), # second
)
def get_annotation_counts(reader: PdfReader) -> dict[str, int]:
"""Get a dictionary with the annotation subtype counts."""
pdf_annotations = {}
for page in reader.pages:
if page.annotations:
for annot in page.annotations:
annot_obj = annot.get_object()
subtype = annot_obj["/Subtype"][1:]
if subtype not in pdf_annotations:
pdf_annotations[subtype] = 0
pdf_annotations[subtype] += 1
return pdf_annotations
def check_meta(entry: PdfEntry) -> bool:
"""Check if the given entry metadata matches the extracted metadata."""
seen_failure = False
try:
reader = PdfReader(entry.path)
if reader.is_encrypted:
return seen_failure
info = reader.metadata
except Exception:
return seen_failure
if info is None:
info = {}
if info.get("/Producer") != entry.producer:
seen_failure = True
print(
f"❌ ERROR: Producer mismatch: {entry.producer} vs {info.get('/Producer')}",
)
if len(reader.pages) != entry.pages:
seen_failure = True
print(
f"❌ ERROR: Page mismatch: {len(reader.pages)} vs {entry.pages}",
)
pdf_date = pdf_to_datetime(info.get("/CreationDate"))
pdf_date = None if pdf_date is None else pdf_date.isoformat()
entry_date = (
None if entry.creation_date is None else entry.creation_date.isoformat()[:19]
)
if pdf_date != entry_date:
seen_failure = True
print(f"❌ ERROR: Creation date mismatch: {entry_date} vs {pdf_date}")
# Check annotations
pdf_annotations = get_annotation_counts(reader)
pdf_annotations_sum = sum(pdf_annotations.values())
entry_annotation_sum = 0
if entry.annotations:
entry_annotation_sum = entry.annotations.sum()
if pdf_annotations_sum != entry_annotation_sum:
seen_failure = True
print(
f"❌ ERROR: Annotation count mismatch: {entry_annotation_sum} vs {pdf_annotations_sum}"
)
print(" Expected:")
seen_subtypes = []
for subtype, exp_count in sorted(entry.annotations.items()):
seen_subtypes.append(subtype)
if exp_count == pdf_annotations.get(subtype, 0):
continue
print(
f" - {subtype}: {exp_count} vs {pdf_annotations.get(subtype, 0)}"
)
todo_subtypes = []
for subtype, _ in sorted(pdf_annotations.items()):
if subtype not in seen_subtypes:
todo_subtypes.append(subtype)
if todo_subtypes:
print(" Found:")
for subtype, count in sorted(pdf_annotations.items()):
if subtype not in seen_subtypes:
todo_subtypes.append(subtype)
print(f" - {subtype}: {count}")
return seen_failure
if __name__ == "__main__":
main()