74 lines
2.9 KiB
Python
74 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Report fonts actually used by extracted PDF text spans and embedded resources.
|
|
|
|
This is an audit, not a visual fidelity gate. Equal font names do not prove
|
|
equal metrics, glyph outlines, encoding, shaping or paragraph layout.
|
|
Uses stdlib and Poppler. XML font sizes are rounded to integer bp at zoom 1;
|
|
they are diagnostic labels, not precise TeX-size measurements.
|
|
"""
|
|
import argparse
|
|
from collections import Counter
|
|
import json
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import xml.etree.ElementTree as ET
|
|
|
|
|
|
def font_name(name):
|
|
return re.sub(r"^[A-Z]{6}\+", "", name)
|
|
|
|
|
|
def inspect(path):
|
|
resource_list = subprocess.check_output(["pdffonts", str(path)], text=True)
|
|
resources = {font_name(re.split(r"\s{2,}", row)[0])
|
|
for row in resource_list.splitlines()[2:] if row.strip()}
|
|
xml = subprocess.check_output(["pdftohtml", "-xml", "-hidden", "-fontfullname",
|
|
"-i", "-stdout", "-zoom", "1", str(path)])
|
|
document = ET.fromstring(xml)
|
|
usage = Counter()
|
|
fonts = {}
|
|
for page in document.findall("page"):
|
|
fonts.update({spec["id"]: (font_name(spec["family"]), int(spec["size"]))
|
|
for spec in (node.attrib for node in page.findall("fontspec"))})
|
|
for span in page.findall("text"):
|
|
usage[fonts[span.attrib["font"]]] += len("".join(span.itertext()))
|
|
return {
|
|
"path": str(path.resolve()),
|
|
"pages": len(document.findall("page")),
|
|
"resource_font_names": sorted(resources),
|
|
"used_font_names": sorted({name for name, size in usage}),
|
|
"span_characters_by_font_and_rounded_size_bp": [
|
|
{"font": name, "rounded_size_bp": size, "characters": count}
|
|
for (name, size), count in sorted(usage.items())
|
|
],
|
|
}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--reference", type=Path, required=True)
|
|
parser.add_argument("--candidate", type=Path, required=True)
|
|
parser.add_argument("--json", type=Path, required=True)
|
|
args = parser.parse_args()
|
|
reference = inspect(args.reference)
|
|
candidate = inspect(args.candidate)
|
|
expected = set(reference["used_font_names"])
|
|
actual = set(candidate["used_font_names"])
|
|
report = {
|
|
"audit_completed": True,
|
|
"font_identity_sets_equal": expected == actual,
|
|
"reference_only_used_fonts": sorted(expected - actual),
|
|
"candidate_only_used_fonts": sorted(actual - expected),
|
|
"reference": reference,
|
|
"candidate": candidate,
|
|
"scope": "PDF text-span font identity/size audit; not rendering or full-format acceptance",
|
|
}
|
|
args.json.write_text(json.dumps(report, indent=2) + "\n")
|
|
print(json.dumps({key: value for key, value in report.items()
|
|
if key not in ("reference", "candidate")}, indent=2))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|