lynkeus 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lynkeus/__init__.py ADDED
@@ -0,0 +1,880 @@
1
+ """lynkeus: summarize the differences between two PDF files.
2
+
3
+ Named after Lynkeus, the Argonaut whose sight was so sharp that he could
4
+ see through walls and under the earth.
5
+
6
+ Stages, from cheapest to most expensive:
7
+ 1. hashes - raw sha1 and sha256, then a normalized hash that ignores metadata,
8
+ plus a list of the metadata fields that differ
9
+ 2. text - per-page text (pdftotext), pages aligned by similarity,
10
+ word-level diff per page
11
+ 3. visual - pages rendered (pdftoppm) and compared pixel-wise
12
+ (ImageMagick compare)
13
+
14
+ Exit status: 0 = same content, 1 = content differs, 2 = error.
15
+ Requires: poppler-utils (pdftotext, pdftoppm, pdfinfo), qpdf, ImageMagick.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import concurrent.futures as cf
22
+ import difflib
23
+ import hashlib
24
+ import html
25
+ import os
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import sys
30
+ import tempfile
31
+ import unicodedata
32
+ from collections import Counter
33
+ from dataclasses import dataclass, field
34
+ from pathlib import Path
35
+
36
+ # --------------------------------------------------------------------------
37
+ # helpers
38
+
39
+
40
+ def run(cmd: list[str], ok=(0,)) -> subprocess.CompletedProcess:
41
+ p = subprocess.run(cmd, capture_output=True)
42
+ if p.returncode not in ok:
43
+ raise RuntimeError(f"{cmd[0]} failed ({p.returncode}): "
44
+ f"{p.stderr.decode(errors='replace').strip()}")
45
+ return p
46
+
47
+
48
+ def need(*tools: str) -> None:
49
+ missing = [t for t in tools if shutil.which(t) is None]
50
+ if missing:
51
+ print(f"lynkeus: missing required tools: {', '.join(missing)}", file=sys.stderr)
52
+ sys.exit(2)
53
+
54
+
55
+ def sha256(data: bytes) -> str:
56
+ return hashlib.sha256(data).hexdigest()
57
+
58
+
59
+ def file_hashes(path: Path) -> tuple[str, str]:
60
+ """(sha1, sha256) of a file, read in chunks."""
61
+ h1, h256 = hashlib.sha1(), hashlib.sha256()
62
+ with path.open("rb") as f:
63
+ for chunk in iter(lambda: f.read(1 << 20), b""):
64
+ h1.update(chunk)
65
+ h256.update(chunk)
66
+ return h1.hexdigest(), h256.hexdigest()
67
+
68
+
69
+ # --------------------------------------------------------------------------
70
+ # stage 1: hashes and metadata
71
+
72
+ VOLATILE = re.compile(
73
+ rb"^\s*/(CreationDate|ModDate|ID|Producer|Creator)\b.*$", re.M)
74
+ XMP = re.compile(rb"<\?xpacket begin.*?<\?xpacket end[^>]*>", re.S)
75
+
76
+
77
+ def normalized_hash(path: Path, tmp: Path) -> str:
78
+ """Hash of the uncompressed, deterministically-numbered PDF with the
79
+ volatile metadata (dates, IDs, producer, XMP packet) removed."""
80
+ out = tmp / (path.stem + ".qdf")
81
+ # qpdf exit code 3 = succeeded with warnings (damaged but readable)
82
+ run(["qpdf", "--qdf", "--object-streams=disable", "--compress-streams=n",
83
+ "--decode-level=generalized", "--deterministic-id",
84
+ "--no-original-object-ids",
85
+ str(path), str(out)], ok=(0, 3))
86
+ data = out.read_bytes()
87
+ data = XMP.sub(b"", data)
88
+ data = VOLATILE.sub(b"", data)
89
+ return sha256(data)
90
+
91
+
92
+ def pdfinfo(path: Path) -> dict[str, str]:
93
+ p = run(["pdfinfo", str(path)])
94
+ info = {}
95
+ for line in p.stdout.decode(errors="replace").splitlines():
96
+ k, sep, v = line.partition(":")
97
+ if sep:
98
+ info[k.strip()] = v.strip()
99
+ return info
100
+
101
+
102
+ # --------------------------------------------------------------------------
103
+ # stage 2: text
104
+
105
+
106
+ def page_texts(path: Path) -> list[str]:
107
+ p = run(["pdftotext", "-enc", "UTF-8", str(path), "-"])
108
+ pages = p.stdout.decode("utf-8", errors="replace").split("\f")
109
+ if pages and not pages[-1].strip():
110
+ pages.pop() # pdftotext ends with a trailing form feed
111
+ return pages
112
+
113
+
114
+ INVISIBLE = re.compile("[\ufe00-\ufe0f\u200b-\u200d\u2060\ufeff\u00ad]")
115
+
116
+
117
+ def words(text: str) -> list[str]:
118
+ """Normalized word list: NFKC (so ¹→1, fi→fi, 𝑥→x), invisible characters
119
+ and variation selectors dropped, hyphenation at line ends undone."""
120
+ text = INVISIBLE.sub("", unicodedata.normalize("NFKC", text))
121
+ text = re.sub(r"(\w)-\n(\w)", r"\1\2", text)
122
+ return text.split()
123
+
124
+
125
+ def similarity(a: list[str], b: list[str]) -> float:
126
+ if not a and not b:
127
+ return 1.0
128
+ return difflib.SequenceMatcher(None, a, b, autojunk=False).ratio()
129
+
130
+
131
+ def align_block(A, B, ia, ib, threshold=0.4):
132
+ """Needleman-Wunsch alignment of page lists A[ia..] and B[ib..].
133
+ Returns a list of (i or None, j or None)."""
134
+ n, m = len(A), len(B)
135
+ sim = [[similarity(A[i], B[j]) for j in range(m)] for i in range(n)]
136
+ gap = threshold / 2 # pairing below `threshold` scores worse than 2 gaps
137
+ score = [[0.0] * (m + 1) for _ in range(n + 1)]
138
+ for i in range(1, n + 1):
139
+ score[i][0] = -gap * i
140
+ for j in range(1, m + 1):
141
+ score[0][j] = -gap * j
142
+ for i in range(1, n + 1):
143
+ for j in range(1, m + 1):
144
+ score[i][j] = max(score[i - 1][j - 1] + sim[i - 1][j - 1] - threshold,
145
+ score[i - 1][j] - gap,
146
+ score[i][j - 1] - gap)
147
+ out, i, j = [], n, m
148
+ while i or j:
149
+ if i and j and score[i][j] == score[i - 1][j - 1] + sim[i - 1][j - 1] - threshold:
150
+ out.append((ia + i - 1, ib + j - 1)); i -= 1; j -= 1
151
+ elif i and score[i][j] == score[i - 1][j] - gap:
152
+ out.append((ia + i - 1, None)); i -= 1
153
+ else:
154
+ out.append((None, ib + j - 1)); j -= 1
155
+ return out[::-1]
156
+
157
+
158
+ def align_pages(wa: list[list[str]], wb: list[list[str]]):
159
+ """Pair pages of A and B: exact matches first, then similarity-based
160
+ alignment inside the remaining blocks."""
161
+ keys_a = [" ".join(w) for w in wa]
162
+ keys_b = [" ".join(w) for w in wb]
163
+ sm = difflib.SequenceMatcher(None, keys_a, keys_b, autojunk=False)
164
+ pairs = []
165
+ for op, a0, a1, b0, b1 in sm.get_opcodes():
166
+ if op == "equal":
167
+ pairs += list(zip(range(a0, a1), range(b0, b1)))
168
+ else:
169
+ pairs += align_block(wa[a0:a1], wb[b0:b1], a0, b0)
170
+ return pairs
171
+
172
+
173
+ def word_diff(a: list[str], b: list[str], ctx=6, max_hunks=5):
174
+ sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
175
+ added = removed = 0
176
+ hunks = []
177
+ for op, a0, a1, b0, b1 in sm.get_opcodes():
178
+ if op == "equal":
179
+ continue
180
+ removed += a1 - a0
181
+ added += b1 - b0
182
+ hunks.append((a[max(0, a0 - ctx):a0], a[a0:a1], b[b0:b1], a[a1:a1 + ctx]))
183
+ return added, removed, hunks[:max_hunks], len(hunks)
184
+
185
+
186
+ # --------------------------------------------------------------------------
187
+ # stage 3: visual
188
+
189
+
190
+ def render(path: Path, outdir: Path, dpi: int) -> list[Path]:
191
+ outdir.mkdir(parents=True, exist_ok=True)
192
+ run(["pdftoppm", "-r", str(dpi), "-png", str(path), str(outdir / "p")],
193
+ ok=(0, 99))
194
+ # pdftoppm zero-pads to the width of the page count: sort numerically
195
+ files = sorted(outdir.glob("p-*.png"),
196
+ key=lambda p: int(p.stem.split("-")[-1]))
197
+ return files
198
+
199
+
200
+ def render_page(path: Path, index: int, dpi: int, out: Path) -> Path:
201
+ """Render one page (0-based index) to out (a .png path)."""
202
+ n = str(index + 1)
203
+ run(["pdftoppm", "-r", str(dpi), "-png", "-singlefile", "-f", n, "-l", n,
204
+ str(path), str(out.with_suffix(""))], ok=(0, 99))
205
+ return out
206
+
207
+
208
+ def diff_overlay(a: Path, b: Path, out: Path, fuzz: float, radius=6,
209
+ color="#ff2d55") -> bool:
210
+ """Write a transparent PNG marking the changed areas between two
211
+ same-size images: changed pixels dilated into blobs, light fill plus a
212
+ stronger outline. Returns False when nothing changed."""
213
+ mask = out.with_name(out.stem + "-mask.png")
214
+ p = subprocess.run(["magick", "compare", "-metric", "AE", "-fuzz", f"{fuzz}%",
215
+ "-highlight-color", "white", "-lowlight-color", "black",
216
+ "-compose", "src", str(a), str(b), str(mask)],
217
+ capture_output=True)
218
+ if p.returncode not in (0, 1) or float(p.stderr.split()[0]) == 0:
219
+ mask.unlink(missing_ok=True)
220
+ return False
221
+ # alpha = 25% inside the blobs + 65% on their outline
222
+ run(["magick", str(mask), "-colorspace", "gray",
223
+ "-morphology", "Dilate", f"Disk:{radius}", "-threshold", "50%",
224
+ "(", "+clone", "-morphology", "EdgeIn", "Disk:1.5", "-evaluate", "multiply", "0.65", ")",
225
+ "(", "-clone", "0", "-evaluate", "multiply", "0.25", ")",
226
+ "-delete", "0", "-compose", "plus", "-composite", str(mask)])
227
+ run(["magick", str(mask), "(", "+clone", "-fill", color, "-colorize", "100", ")",
228
+ "+swap", "-alpha", "off", "-compose", "copyalpha", "-composite",
229
+ "-define", "png:compression-level=9", f"PNG32:{out}"])
230
+ mask.unlink()
231
+ return True
232
+
233
+
234
+ def quantize(path: Path, colors: int) -> None:
235
+ """Shrink a report PNG in place with a reduced palette (text stays sharp,
236
+ files get ~3x smaller)."""
237
+ run(["magick", str(path), "-dither", "None", "-colors", str(colors),
238
+ "-define", "png:compression-level=9", f"PNG8:{path}"])
239
+
240
+
241
+ def compare_images(a: Path, b: Path, out: Path, fuzz: float):
242
+ """Return the number of differing pixels and the total pixel count,
243
+ or None when the images differ in size."""
244
+ cmd = ["magick", "compare", "-metric", "AE", "-fuzz", f"{fuzz}%",
245
+ str(a), str(b), str(out)]
246
+ p = subprocess.run(cmd, capture_output=True)
247
+ err = p.stderr.decode(errors="replace").strip()
248
+ if p.returncode not in (0, 1):
249
+ if "image widths or heights differ" in err:
250
+ return None
251
+ raise RuntimeError(f"compare failed: {err}")
252
+ # IM7 prints e.g. "1234" or "1234 (0.0123)"
253
+ diff = float(err.split()[0])
254
+ size = run(["magick", "identify", "-format", "%w %h", str(a)]).stdout.split()
255
+ total = int(size[0]) * int(size[1])
256
+ return int(diff), total
257
+
258
+
259
+ # --------------------------------------------------------------------------
260
+ # report model
261
+
262
+
263
+ @dataclass
264
+ class PagePair:
265
+ a: int | None # 0-based page index in A
266
+ b: int | None
267
+ text_sim: float = 1.0
268
+ added: int = 0
269
+ removed: int = 0
270
+ reordered: bool = False # same words, different order
271
+ hunks: list = field(default_factory=list)
272
+ n_hunks: int = 0
273
+ vis_pixels: int | None = None # differing pixels
274
+ vis_frac: float | None = None
275
+ vis_size_mismatch: bool = False
276
+ vis_raw_frac: float | None = None # before applying --min-pixels
277
+ diff_png: Path | None = None # compare output, kept for every pair
278
+
279
+ @property
280
+ def text_changed(self):
281
+ return self.added or self.removed
282
+
283
+ @property
284
+ def visual_changed(self):
285
+ return self.vis_size_mismatch or bool(self.vis_frac)
286
+
287
+ def label(self):
288
+ a = "-" if self.a is None else str(self.a + 1)
289
+ b = "-" if self.b is None else str(self.b + 1)
290
+ return f"{a}→{b}" if a != b else a
291
+
292
+ def kind(self):
293
+ if self.a is None:
294
+ return "added"
295
+ if self.b is None:
296
+ return "removed"
297
+ if self.text_changed:
298
+ return "text"
299
+ if self.reordered:
300
+ return "reordered"
301
+ if self.visual_changed:
302
+ return "visual-only"
303
+ return "same"
304
+
305
+
306
+ # --------------------------------------------------------------------------
307
+ # main
308
+
309
+
310
+ def main(argv=None) -> int:
311
+ ap = argparse.ArgumentParser(prog="lynkeus", description=__doc__.split("\n\n")[0],
312
+ formatter_class=argparse.RawDescriptionHelpFormatter)
313
+ ap.add_argument("a", type=Path)
314
+ ap.add_argument("b", type=Path)
315
+ ap.add_argument("-o", "--out", type=Path,
316
+ help="write diff images and report.html to this directory")
317
+ ap.add_argument("--dpi", type=int, default=60, help="render resolution (default 60)")
318
+ ap.add_argument("--fuzz", type=float, default=10,
319
+ help="per-pixel colour tolerance in %% (default 10)")
320
+ ap.add_argument("--min-pixels", type=int, default=4,
321
+ help="ignore pages where fewer pixels than this differ "
322
+ "(default 4, at the render resolution). A changed "
323
+ "page number touches 10-20 pixels at 60 dpi; "
324
+ "rendering noise 0-1")
325
+ ap.add_argument("--zoom-dpi", type=int, default=120,
326
+ help="resolution of the zoomable page images in the HTML "
327
+ "report (default 120)")
328
+ ap.add_argument("--colors", type=int, default=64,
329
+ help="palette size of the report images; 0 keeps full "
330
+ "colour (default 64)")
331
+ ap.add_argument("--no-visual", action="store_true", help="skip stage 3")
332
+ ap.add_argument("-v", "--verbose", action="store_true",
333
+ help="show word-level snippets for every changed page")
334
+ args = ap.parse_args(argv)
335
+
336
+ need("pdftotext", "pdftoppm", "pdfinfo", "qpdf",
337
+ *(() if args.no_visual else ("magick",)))
338
+ for p in (args.a, args.b):
339
+ if not p.is_file():
340
+ print(f"lynkeus: {p}: no such file", file=sys.stderr)
341
+ return 2
342
+
343
+ tmp = Path(tempfile.mkdtemp(prefix="lynkeus-"))
344
+ try:
345
+ return compare(args, tmp)
346
+ except RuntimeError as e:
347
+ print(f"lynkeus: {e}", file=sys.stderr)
348
+ return 2
349
+ finally:
350
+ shutil.rmtree(tmp, ignore_errors=True)
351
+
352
+
353
+ def compare(args, tmp: Path) -> int:
354
+ A, B = args.a, args.b
355
+ out = []
356
+ say = out.append
357
+
358
+ # ---- stage 1
359
+ (sha1_a, raw_a), (sha1_b, raw_b) = file_hashes(A), file_hashes(B)
360
+ say(f"== 1. hashes")
361
+ for tag, name, h1, h256 in (("A", A, sha1_a, raw_a), ("B", B, sha1_b, raw_b)):
362
+ say(f" {tag}: {name}")
363
+ say(f" sha1 {h1}")
364
+ say(f" sha256 {h256}")
365
+ sha1s = (sha1_a, sha1_b)
366
+
367
+ def finish_early(headline: str, body: str) -> int:
368
+ text = "\n".join(out)
369
+ print(text)
370
+ if args.out:
371
+ write_html(args, sha1s, headline, text, body, details_open=True)
372
+ print(f"\nreport: {args.out / 'report.html'}")
373
+ return 0
374
+
375
+ if raw_a == raw_b:
376
+ say("identical bytes")
377
+ return finish_early("Identical files: the bytes are the same.",
378
+ "<p class=verdict>Both files have the same SHA-1 and "
379
+ "SHA-256: no further comparison needed.</p>")
380
+ say("raw hashes differ")
381
+ norm_a, norm_b = normalized_hash(A, tmp), normalized_hash(B, tmp)
382
+ ia, ib = pdfinfo(A), pdfinfo(B)
383
+ meta = [k for k in sorted(set(ia) | set(ib))
384
+ if k not in ("File size",) and ia.get(k) != ib.get(k)]
385
+ for k in meta:
386
+ say(f" meta {k}: {ia.get(k, '∅')!r} → {ib.get(k, '∅')!r}")
387
+ say(f" file size: {A.stat().st_size:,} → {B.stat().st_size:,} bytes")
388
+ if norm_a == norm_b:
389
+ say("normalized hash identical: same content, only metadata differs")
390
+ rows = "".join(f"<tr><th>{html.escape(k)}</th><td>{html.escape(ia.get(k, '∅'))}</td>"
391
+ f"<td>{html.escape(ib.get(k, '∅'))}</td></tr>" for k in meta)
392
+ rows += (f"<tr><th>File size</th><td>{A.stat().st_size:,} bytes</td>"
393
+ f"<td>{B.stat().st_size:,} bytes</td></tr>")
394
+ return finish_early(
395
+ "Same content: only the metadata differs.",
396
+ "<p class=verdict>The files differ, but once dates, IDs, producer and "
397
+ "XMP metadata are removed they are the same, so the pages were not "
398
+ "compared further.</p>"
399
+ f"<table class=meta><tr><th></th><th>A</th><th>B</th></tr>{rows}</table>")
400
+ say("normalized hash differs: content changed")
401
+
402
+ # ---- stage 2
403
+ ta, tb = page_texts(A), page_texts(B)
404
+ wa, wb = [words(t) for t in ta], [words(t) for t in tb]
405
+ pairs = [PagePair(i, j) for i, j in align_pages(wa, wb)]
406
+ for p in pairs:
407
+ if p.a is not None and p.b is not None:
408
+ a, b = wa[p.a], wb[p.b]
409
+ if a != b and Counter(a) == Counter(b):
410
+ p.reordered = True
411
+ elif a != b:
412
+ p.text_sim = similarity(a, b)
413
+ p.added, p.removed, p.hunks, p.n_hunks = word_diff(a, b)
414
+
415
+ # ---- stage 3
416
+ imgs_a = imgs_b = None
417
+ if not args.no_visual:
418
+ with cf.ThreadPoolExecutor(2) as ex:
419
+ fa = ex.submit(render, A, tmp / "a", args.dpi)
420
+ fb = ex.submit(render, B, tmp / "b", args.dpi)
421
+ imgs_a, imgs_b = fa.result(), fb.result()
422
+ diffdir = tmp / "diff"
423
+ diffdir.mkdir()
424
+
425
+ def vis(p: PagePair):
426
+ if p.a is None or p.b is None:
427
+ return
428
+ d = diffdir / f"diff-{p.a + 1:03d}-{p.b + 1:03d}.png"
429
+ r = compare_images(imgs_a[p.a], imgs_b[p.b], d, args.fuzz)
430
+ if r is None:
431
+ p.vis_size_mismatch = True
432
+ return
433
+ p.vis_pixels, total = r
434
+ frac = p.vis_pixels / total
435
+ p.vis_raw_frac = frac
436
+ p.vis_frac = frac if p.vis_pixels >= args.min_pixels else 0.0
437
+ p.diff_png = d
438
+
439
+ with cf.ThreadPoolExecutor(os.cpu_count() or 4) as ex:
440
+ list(ex.map(vis, pairs))
441
+
442
+ # ---- summary
443
+ kinds = {}
444
+ for p in pairs:
445
+ kinds.setdefault(p.kind(), []).append(p)
446
+
447
+ say("")
448
+ say(f"== 2. text ({len(ta)} vs {len(tb)} pages)")
449
+ if not any(p.text_changed for p in pairs) and "added" not in kinds and "removed" not in kinds:
450
+ say("extracted text identical on every page")
451
+ for p in pairs:
452
+ if p.a is None:
453
+ say(f" page {p.label()}: ADDED “{snippet(wb[p.b])}”")
454
+ elif p.b is None:
455
+ say(f" page {p.label()}: REMOVED “{snippet(wa[p.a])}”")
456
+ elif p.text_changed:
457
+ say(f" page {p.label()}: +{p.added}/−{p.removed} words "
458
+ f"({p.n_hunks} change{'s' * (p.n_hunks != 1)}, similarity {p.text_sim:.0%})")
459
+ for h in p.hunks[: None if args.verbose else 2]:
460
+ say(" " + fmt_hunk(h))
461
+ if not args.verbose and p.n_hunks > 2:
462
+ say(f" … {p.n_hunks - 2} more (use -v)")
463
+
464
+ reo = kinds.get("reordered", [])
465
+ if reo:
466
+ say(f" same words in a different order (extraction order, usually math/tables): {pages(reo)}")
467
+
468
+ if not args.no_visual:
469
+ say("")
470
+ say(f"== 3. visual (dpi {args.dpi}, fuzz {args.fuzz:g}%, "
471
+ f"threshold {args.min_pixels} px)")
472
+ vo = kinds.get("visual-only", [])
473
+ tv = [p for p in kinds.get("text", []) + reo if p.visual_changed]
474
+ tnv = [p for p in kinds.get("text", []) if not p.visual_changed]
475
+ mism = [p for p in pairs if p.vis_size_mismatch]
476
+ if mism:
477
+ say(f" page size changed: {pages(mism)}")
478
+ say(f" visual-only changes (text identical): {pages(vo) or 'none'}")
479
+ for p in sorted(vo, key=lambda p: -(p.vis_frac or 0))[:10]:
480
+ if p.vis_frac:
481
+ say(f" page {p.label()}: {p.vis_frac:.2%} of pixels")
482
+ say(f" text + visual changes: {pages(tv) or 'none'}")
483
+ if tnv:
484
+ say(f" text changed, visual change below {args.min_pixels} px at "
485
+ f"{args.dpi} dpi: {pages(tnv)} (tiny glyphs such as page "
486
+ "numbers, or encoding / extraction differences)")
487
+
488
+ say("")
489
+ say("== summary")
490
+ n_same = len(kinds.get("same", []))
491
+ parts = [f"{len(pairs)} aligned pages", f"{n_same} unchanged"]
492
+ for k, name in (("text", "text changes"), ("reordered", "reordered text"),
493
+ ("visual-only", "visual-only"),
494
+ ("added", "added"), ("removed", "removed")):
495
+ if kinds.get(k):
496
+ parts.append(f"{len(kinds[k])} {name}")
497
+ say(", ".join(parts))
498
+ shifted = [p for p in pairs if p.a is not None and p.b is not None and p.a != p.b]
499
+ if shifted:
500
+ say(f"page numbering shifts from A p.{shifted[0].a + 1} → B p.{shifted[0].b + 1}")
501
+
502
+ text = "\n".join(out)
503
+ print(text)
504
+
505
+ if args.out:
506
+ write_report(args, pairs, ta, tb, text, imgs_a, imgs_b, args.min_pixels, sha1s)
507
+ print(f"\nreport: {args.out / 'report.html'}")
508
+
509
+ return 0 if n_same == len(pairs) else 1
510
+
511
+
512
+ def snippet(ws: list[str], n=10) -> str:
513
+ s = " ".join(ws[:n])
514
+ return s + (" …" if len(ws) > n else "")
515
+
516
+
517
+ def fmt_hunk(h) -> str:
518
+ pre, old, new, post = h
519
+ def cut(ws, n=12):
520
+ return " ".join(ws) if len(ws) <= n else " ".join(ws[:n]) + " …"
521
+ s = " ".join(pre[-4:])
522
+ if old:
523
+ s += f" [-{cut(old)}-]"
524
+ if new:
525
+ s += f" {{+{cut(new)}+}}"
526
+ s += " " + " ".join(post[:4])
527
+ return s.strip()
528
+
529
+
530
+ def pages(ps: list[PagePair]) -> str:
531
+ return ", ".join(p.label() for p in ps)
532
+
533
+
534
+ # --------------------------------------------------------------------------
535
+ # HTML report
536
+
537
+
538
+ def write_report(args, pairs, ta, tb, summary, imgs_a, imgs_b, min_pixels, sha1s):
539
+ out: Path = args.out
540
+ out.mkdir(parents=True, exist_ok=True)
541
+ imgdir = out / "img"
542
+ imgdir.mkdir(exist_ok=True)
543
+ zoom = {}
544
+ if imgs_a is not None and pairs:
545
+ zoom = render_zoom(args, pairs, imgdir / "zoom")
546
+ rows = []
547
+ for p in pairs:
548
+ k = p.kind()
549
+ body = ""
550
+ if p.a is not None and p.b is not None and p.text_changed:
551
+ body += "<ul class=hunks>" + "".join(
552
+ f"<li>{hunk_html(h)}</li>" for h in p.hunks) + "</ul>"
553
+ if p.n_hunks > len(p.hunks):
554
+ body += f"<p class=more>… {p.n_hunks - len(p.hunks)} more changes</p>"
555
+ elif k == "reordered":
556
+ body += "<p class=more>Same words, different extraction order.</p>"
557
+ elif k in ("added", "removed"):
558
+ t = tb[p.b] if p.a is None else ta[p.a]
559
+ body += f"<pre>{html.escape(t.strip()[:600])}</pre>"
560
+ imgs = page_images(p, imgs_a, imgs_b, imgdir, min_pixels)
561
+ z = zoom.get(id(p), {})
562
+ zattrs = "".join(f" data-z{key}='{html.escape(v)}'" for key, v in z.items())
563
+ rows.append(f"<section class='{k}' data-kind='{k}' data-label='page {html.escape(p.label())}'{zattrs}>"
564
+ f"<h2>page {html.escape(p.label())} "
565
+ f"<span class=tag>{KIND_LABEL.get(k, k)}</span></h2>{body}{imgs}</section>")
566
+ counts = {}
567
+ for p in pairs:
568
+ counts[p.kind()] = counts.get(p.kind(), 0) + 1
569
+ order = ["text", "reordered", "visual-only", "added", "removed", "same"]
570
+ # unchanged pages start hidden, unless nothing else changed
571
+ show_same = len(counts) == 1
572
+ chips = "".join(
573
+ f"<label class='chip {k}'><input type=checkbox value='{k}'"
574
+ f"{' checked' if k != 'same' or show_same else ''}> "
575
+ f"{KIND_LABEL.get(k, k)} <b>{counts[k]}</b></label>"
576
+ for k in order if counts.get(k))
577
+ filters = (f"<div id=filters>Show: {chips}"
578
+ f"<button data-set=all>all</button><button data-set=none>none</button>"
579
+ f"<span id=shown></span></div>") if chips else ""
580
+ headline = summary.rstrip().splitlines()[-1]
581
+ if headline.startswith("page numbering shifts"):
582
+ headline = summary.rstrip().splitlines()[-2] + " — " + headline
583
+ write_html(args, sha1s, headline, summary,
584
+ "".join(rows) or "<p>No pages.</p>", filters)
585
+ if args.colors:
586
+ files = [f for f in imgdir.rglob("*.png") if not f.name.startswith("ov-")]
587
+ with cf.ThreadPoolExecutor(os.cpu_count() or 4) as ex:
588
+ list(ex.map(lambda f: quantize(f, args.colors), files))
589
+
590
+
591
+ KIND_LABEL = {"same": "unchanged"}
592
+
593
+
594
+ def write_html(args, sha1s, headline: str, summary: str, body: str,
595
+ filters: str = "", details_open: bool = False) -> None:
596
+ """Write report.html: sticky header (files, sha1, filters), headline,
597
+ folded text report, then the body (page sections or a verdict)."""
598
+ out: Path = args.out
599
+ out.mkdir(parents=True, exist_ok=True)
600
+
601
+ def file_id(tag, path, sha1):
602
+ return (f"<span class=file><b>{tag}</b> {html.escape(str(path))} "
603
+ f"<code title='sha1 {sha1}'>sha1 {sha1[:10]}</code></span>")
604
+ header = (f"<header id=top><div class=files>{file_id('A', args.a, sha1s[0])}"
605
+ f"<span class=arrow>→</span>{file_id('B', args.b, sha1s[1])}</div>"
606
+ f"{filters}</header>")
607
+ doc = f"""<!DOCTYPE html>
608
+ <html><head><meta charset="utf-8"><title>lynkeus {html.escape(args.a.name)} vs {html.escape(args.b.name)}</title>
609
+ <style>
610
+ body{{font:14px/1.45 system-ui,sans-serif;max-width:1200px;margin:2em auto;padding:0 1em;color:#222}}
611
+ .headline{{font-size:15px;font-weight:600}} details summary{{cursor:pointer;color:#555}}
612
+ pre.summary{{background:#f6f6f6;padding:1em;overflow:auto;font-size:12px}}
613
+ section{{border-top:1px solid #ddd;padding:.5em 0}}
614
+ h2{{font-size:16px;margin:.4em 0}}
615
+ .tag{{font-size:11px;padding:1px 6px;border-radius:3px;background:#eee;vertical-align:middle}}
616
+ .text .tag{{background:#fde2b8}} .visual-only .tag{{background:#d6e6fb}}
617
+ .added .tag{{background:#cdeccd}} .reordered .tag{{background:#eadcf6}} .removed .tag{{background:#f6cfcf}}
618
+ del{{background:#fbd3d3;text-decoration:line-through}} ins{{background:#cdf0cd;text-decoration:none}}
619
+ .imgs{{display:flex;gap:8px}} figure{{margin:0;flex:1}} img{{width:100%;border:1px solid #ccc}}
620
+ figcaption{{font-size:11px;color:#666;text-align:center}}
621
+ .imgs figure{{max-width:33%}} .nodiff div{{border:1px dashed #ccc;color:#888;height:100%;display:flex;align-items:center;justify-content:center}}
622
+ #top{{position:sticky;top:0;background:#fff;padding:.6em 0;border-bottom:1px solid #ddd;z-index:1}}
623
+ .files{{display:flex;flex-wrap:wrap;gap:4px 12px;align-items:baseline;font-size:17px;font-weight:600}}
624
+ .file b{{color:#888;font-weight:600}} .arrow{{color:#888}}
625
+ .file code{{font-size:11px;font-weight:400;color:#666;background:#f3f3f3;padding:1px 5px;border-radius:3px}}
626
+ #filters{{margin-top:.5em;display:flex;flex-wrap:wrap;gap:6px;align-items:center}}
627
+ .chip{{padding:2px 8px;border-radius:12px;background:#eee;cursor:pointer;user-select:none}}
628
+ .chip.text{{background:#fde2b8}} .chip.visual-only{{background:#d6e6fb}} .chip.reordered{{background:#eadcf6}}
629
+ .chip.added{{background:#cdeccd}} .chip.removed{{background:#f6cfcf}}
630
+ .chip:has(input:not(:checked)){{opacity:.45}}
631
+ #filters button{{font:inherit;font-size:12px}} #shown{{color:#666;font-size:12px;margin-left:auto}}
632
+ section.hidden{{display:none}}
633
+ .same .tag,.chip.same{{background:#e4e4e4}} section.same h2{{color:#777}}
634
+ .verdict{{font-size:15px}} table.meta{{border-collapse:collapse;font-size:13px}}
635
+ table.meta th,table.meta td{{border:1px solid #ddd;padding:3px 10px;text-align:left}}
636
+ table.meta th{{background:#f6f6f6}}
637
+ section[data-za] .imgs img, section[data-zb] .imgs img{{cursor:zoom-in}}
638
+ #lb{{position:fixed;inset:0;background:#1d1f22;z-index:10;display:flex;flex-direction:column;color:#ddd}}
639
+ #lb[hidden]{{display:none}}
640
+ .lb-bar{{display:flex;align-items:center;gap:6px;padding:6px 10px;background:#2a2d31;flex-wrap:wrap}}
641
+ .lb-bar button{{font:inherit;font-size:13px;background:#3a3e44;color:#eee;border:1px solid #555;border-radius:4px;padding:2px 9px;cursor:pointer}}
642
+ .lb-bar button:hover{{background:#4a4f56}} .lb-bar button.on{{background:#5a6f8f;border-color:#7a93b8}}
643
+ .lb-bar button:disabled{{opacity:.35;cursor:default}}
644
+ #lb-title{{font-weight:600;margin-right:8px}} #lb-zoom{{min-width:4em;text-align:right;font-variant-numeric:tabular-nums}}
645
+ .lb-hint{{margin-left:auto;font-size:11px;color:#999}}
646
+ .lb-panes{{flex:1;display:flex;gap:4px;padding:4px;min-height:0}}
647
+ .pane{{flex:1;position:relative;overflow:hidden;background:#2b2e33;cursor:grab;touch-action:none}}
648
+ .pane.drag{{cursor:grabbing}} .pane[hidden]{{display:none}}
649
+ .pane img{{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;transform-origin:0 0;
650
+ border:0;user-select:none;-webkit-user-drag:none;pointer-events:none}}
651
+ .pane img.ov{{display:none}} #lb.marks .pane img.ov.has{{display:block}}
652
+ .pane .cap{{position:absolute;top:6px;left:8px;z-index:1;background:rgba(0,0,0,.6);padding:1px 8px;border-radius:3px;font-size:12px}}
653
+ .pane .missing{{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#888}}
654
+ </style></head><body>
655
+ {header}
656
+ <p class=headline>{html.escape(headline)}</p>
657
+ <details{' open' if details_open else ''}><summary>Full text report (hashes, metadata, text changes)</summary>
658
+ <pre class=summary>{html.escape(summary)}</pre></details>
659
+ {body}
660
+ <div id=lb hidden>
661
+ <div class=lb-bar>
662
+ <span id=lb-title></span>
663
+ <button id=lb-prev title="previous page (←)">‹ prev</button>
664
+ <button id=lb-next title="next page (→)">next ›</button>
665
+ <button id=lb-out title="zoom out (−)">−</button>
666
+ <span id=lb-zoom>100%</span>
667
+ <button id=lb-in title="zoom in (+)">+</button>
668
+ <button id=lb-fit title="fit (0)">fit</button>
669
+ <button id=lb-diff title="show the diff pane (d)">diff</button>
670
+ <button id=lb-ov class=on title="mark the changed areas on A and B (m)">marks</button>
671
+ <span class=lb-hint>wheel: zoom · drag: pan · double-click: zoom in/out · ←/→: page · d: diff · m: marks · Esc: close</span>
672
+ <button id=lb-close title="close (Esc)">✕</button>
673
+ </div>
674
+ <div class=lb-panes>
675
+ <div class=pane data-k=a><span class=cap>A</span><img alt=""><img class=ov alt=""></div>
676
+ <div class=pane data-k=d hidden><span class=cap>diff</span><img alt=""></div>
677
+ <div class=pane data-k=b><span class=cap>B</span><img alt=""><img class=ov alt=""></div>
678
+ </div>
679
+ </div>
680
+ <script>
681
+ const boxes = [...document.querySelectorAll('#filters input')];
682
+ const secs = [...document.querySelectorAll('section[data-kind]')];
683
+ function apply() {{
684
+ const on = new Set(boxes.filter(b => b.checked).map(b => b.value));
685
+ let n = 0;
686
+ for (const s of secs) {{ const v = on.has(s.dataset.kind); s.classList.toggle('hidden', !v); n += v; }}
687
+ const el = document.getElementById('shown'); if (el) el.textContent = n + ' / ' + secs.length + ' pages shown';
688
+ }}
689
+ boxes.forEach(b => b.addEventListener('change', apply));
690
+ document.querySelectorAll('#filters button').forEach(btn => btn.addEventListener('click', () => {{
691
+ boxes.forEach(b => b.checked = btn.dataset.set === 'all'); apply();
692
+ }}));
693
+ apply();
694
+
695
+ // ---- side-by-side viewer: one shared transform for all panes, so A, B
696
+ // and the diff stay aligned while zooming and panning
697
+ (() => {{
698
+ const lb = document.getElementById('lb');
699
+ const panes = [...lb.querySelectorAll('.pane')];
700
+ const $ = id => document.getElementById(id);
701
+ let cur = null, showDiff = false, t = {{s: 1, x: 0, y: 0}};
702
+ lb.classList.add('marks');
703
+
704
+ function render() {{
705
+ for (const img of lb.querySelectorAll('.pane img')) img.style.transform =
706
+ `translate(${{t.x}}px,${{t.y}}px) scale(${{t.s}})`;
707
+ $('lb-zoom').textContent = Math.round(t.s * 100) + '%';
708
+ }}
709
+ function zoomAt(px, py, s2) {{
710
+ s2 = Math.min(20, Math.max(1, s2));
711
+ t.x = px - (px - t.x) * (s2 / t.s);
712
+ t.y = py - (py - t.y) * (s2 / t.s);
713
+ t.s = s2;
714
+ if (t.s === 1) t.x = t.y = 0;
715
+ render();
716
+ }}
717
+ function center() {{
718
+ const r = panes.find(p => !p.hidden).getBoundingClientRect();
719
+ return [r.width / 2, r.height / 2];
720
+ }}
721
+ function fit() {{ t = {{s: 1, x: 0, y: 0}}; render(); }}
722
+ const visible = () => secs.filter(s => !s.classList.contains('hidden') && (s.dataset.za || s.dataset.zb));
723
+
724
+ function open(sec) {{
725
+ cur = sec;
726
+ const d = sec.dataset;
727
+ $('lb-title').textContent = d.label + ' — ' + d.kind;
728
+ const src = {{a: d.za, b: d.zb, d: d.zd}};
729
+ const cap = {{a: d.zcapa, b: d.zcapb, d: d.zcapd}};
730
+ for (const p of panes) {{
731
+ const k = p.dataset.k, img = p.querySelector('img'), ov = p.querySelector('img.ov');
732
+ if (ov) {{
733
+ ov.classList.toggle('has', !!d.zov);
734
+ if (d.zov) ov.src = d.zov; else ov.removeAttribute('src');
735
+ }}
736
+ p.hidden = k === 'd' ? !(showDiff && src.d) : !src[k];
737
+ if (src[k]) img.src = src[k]; else img.removeAttribute('src');
738
+ p.querySelector('.cap').textContent = cap[k] || '';
739
+ }}
740
+ $('lb-diff').disabled = !src.d;
741
+ $('lb-ov').disabled = !d.zov;
742
+ $('lb-diff').classList.toggle('on', showDiff && !!src.d);
743
+ const v = visible(), i = v.indexOf(sec);
744
+ $('lb-prev').disabled = i <= 0;
745
+ $('lb-next').disabled = i < 0 || i >= v.length - 1;
746
+ lb.hidden = false;
747
+ document.body.style.overflow = 'hidden';
748
+ render();
749
+ }}
750
+ function close() {{
751
+ lb.hidden = true; document.body.style.overflow = '';
752
+ if (cur) cur.scrollIntoView({{block: 'nearest'}});
753
+ }}
754
+ function step(n) {{
755
+ const v = visible(), i = v.indexOf(cur) + n;
756
+ if (i >= 0 && i < v.length) open(v[i]); // keep the zoom: compare the same spot
757
+ }}
758
+
759
+ document.addEventListener('click', e => {{
760
+ const img = e.target.closest('section .imgs img');
761
+ if (!img) return;
762
+ const sec = img.closest('section');
763
+ if (sec.dataset.za || sec.dataset.zb) {{ fit(); open(sec); }}
764
+ }});
765
+ for (const p of panes) {{
766
+ p.addEventListener('wheel', e => {{
767
+ e.preventDefault();
768
+ const r = p.getBoundingClientRect();
769
+ zoomAt(e.clientX - r.left, e.clientY - r.top, t.s * Math.exp(-e.deltaY * 0.0015));
770
+ }}, {{passive: false}});
771
+ p.addEventListener('dblclick', e => {{
772
+ const r = p.getBoundingClientRect();
773
+ if (t.s > 1) fit(); else zoomAt(e.clientX - r.left, e.clientY - r.top, 3);
774
+ }});
775
+ p.addEventListener('pointerdown', e => {{
776
+ p.setPointerCapture(e.pointerId); p.classList.add('drag');
777
+ let lx = e.clientX, ly = e.clientY;
778
+ const move = ev => {{ t.x += ev.clientX - lx; t.y += ev.clientY - ly; lx = ev.clientX; ly = ev.clientY; render(); }};
779
+ const up = () => {{ p.classList.remove('drag'); p.removeEventListener('pointermove', move); p.removeEventListener('pointerup', up); }};
780
+ p.addEventListener('pointermove', move); p.addEventListener('pointerup', up);
781
+ }});
782
+ }}
783
+ $('lb-close').onclick = close;
784
+ $('lb-prev').onclick = () => step(-1);
785
+ $('lb-next').onclick = () => step(1);
786
+ $('lb-in').onclick = () => zoomAt(...center(), t.s * 1.5);
787
+ $('lb-out').onclick = () => zoomAt(...center(), t.s / 1.5);
788
+ $('lb-fit').onclick = fit;
789
+ $('lb-diff').onclick = () => {{ showDiff = !showDiff; open(cur); }};
790
+ const toggleMarks = () => $('lb-ov').classList.toggle('on', lb.classList.toggle('marks'));
791
+ $('lb-ov').onclick = toggleMarks;
792
+ document.addEventListener('keydown', e => {{
793
+ if (lb.hidden) return;
794
+ const k = e.key;
795
+ if (k === 'Escape') close();
796
+ else if (k === 'ArrowLeft') step(-1);
797
+ else if (k === 'ArrowRight') step(1);
798
+ else if (k === '+' || k === '=') zoomAt(...center(), t.s * 1.5);
799
+ else if (k === '-') zoomAt(...center(), t.s / 1.5);
800
+ else if (k === '0') fit();
801
+ else if (k === 'd' && cur.dataset.zd) {{ showDiff = !showDiff; open(cur); }}
802
+ else if (k === 'm') toggleMarks();
803
+ else return;
804
+ e.preventDefault();
805
+ }});
806
+ }})();
807
+ </script>
808
+ </body></html>"""
809
+ (out / "report.html").write_text(doc, encoding="utf-8")
810
+
811
+
812
+ def render_zoom(args, listed, zdir: Path) -> dict:
813
+ """Render the listed pages at --zoom-dpi (plus a diff at that resolution)
814
+ for the viewer. Returns {id(pair): {"a": relpath, "b": ..., "d": ...}}."""
815
+ zdir.mkdir(parents=True, exist_ok=True)
816
+
817
+ def job(p: PagePair):
818
+ r = {}
819
+ if p.a is not None:
820
+ render_page(args.a, p.a, args.zoom_dpi, zdir / f"a-{p.a + 1:03d}.png")
821
+ r["a"] = f"img/zoom/a-{p.a + 1:03d}.png"
822
+ r["capa"] = f"A: {args.a.name} p.{p.a + 1}"
823
+ if p.b is not None:
824
+ render_page(args.b, p.b, args.zoom_dpi, zdir / f"b-{p.b + 1:03d}.png")
825
+ r["b"] = f"img/zoom/b-{p.b + 1:03d}.png"
826
+ r["capb"] = f"B: {args.b.name} p.{p.b + 1}"
827
+ if "a" in r and "b" in r and not p.vis_size_mismatch:
828
+ d = zdir / f"diff-{p.a + 1:03d}-{p.b + 1:03d}.png"
829
+ if compare_images(zdir / f"a-{p.a + 1:03d}.png",
830
+ zdir / f"b-{p.b + 1:03d}.png", d, args.fuzz):
831
+ r["d"] = f"img/zoom/{d.name}"
832
+ r["capd"] = "diff (red: changed pixels)"
833
+ ov = zdir / f"ov-{p.a + 1:03d}-{p.b + 1:03d}.png"
834
+ if diff_overlay(zdir / f"a-{p.a + 1:03d}.png",
835
+ zdir / f"b-{p.b + 1:03d}.png", ov, args.fuzz):
836
+ r["ov"] = f"img/zoom/{ov.name}"
837
+ return id(p), r
838
+
839
+ with cf.ThreadPoolExecutor(os.cpu_count() or 4) as ex:
840
+ return dict(ex.map(job, listed))
841
+
842
+
843
+ def page_images(p: PagePair, imgs_a, imgs_b, imgdir: Path, min_pixels) -> str:
844
+ """A / diff / B figures for a page pair; only one figure for an added or
845
+ removed page. Empty when the visual stage was skipped."""
846
+ if imgs_a is None:
847
+ return ""
848
+
849
+ def fig(src: Path, name: str, caption: str) -> str:
850
+ shutil.copy(src, imgdir / name)
851
+ return (f"<figure><img loading=lazy src='img/{name}'>"
852
+ f"<figcaption>{html.escape(caption)}</figcaption></figure>")
853
+
854
+ figs = []
855
+ if p.a is not None:
856
+ figs.append(fig(imgs_a[p.a], f"a-{p.a + 1:03d}.png", f"A p.{p.a + 1}"))
857
+ if p.a is not None and p.b is not None:
858
+ if p.vis_size_mismatch:
859
+ figs.append("<figure class=nodiff><div>page size differs</div></figure>")
860
+ elif p.diff_png and p.diff_png.exists():
861
+ frac = p.vis_raw_frac or 0.0
862
+ cap = f"diff {frac:.2%}"
863
+ if not p.vis_frac:
864
+ cap += f" ({p.vis_pixels} px, below the {min_pixels} px threshold: no visible change)"
865
+ figs.append(fig(p.diff_png, p.diff_png.name, cap))
866
+ if p.b is not None:
867
+ figs.append(fig(imgs_b[p.b], f"b-{p.b + 1:03d}.png", f"B p.{p.b + 1}"))
868
+ return f"<div class=imgs>{''.join(figs)}</div>"
869
+
870
+
871
+ def hunk_html(h) -> str:
872
+ pre, old, new, post = h
873
+ e = lambda ws: html.escape(" ".join(ws))
874
+ s = e(pre[-6:])
875
+ if old:
876
+ s += f" <del>{e(old)}</del>"
877
+ if new:
878
+ s += f" <ins>{e(new)}</ins>"
879
+ return s + " " + e(post[:6])
880
+
lynkeus/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Run lynkeus with `python -m lynkeus`."""
2
+
3
+ import sys
4
+
5
+ from lynkeus import main
6
+
7
+ sys.exit(main())
@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.4
2
+ Name: lynkeus
3
+ Version: 0.1.1
4
+ Summary: Summarize the differences between two PDF files: hashes, then text, then pixels
5
+ Keywords: pdf,diff,compare,visual diff,report
6
+ Author: Pierre Wilke
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: End Users/Desktop
12
+ Classifier: Operating System :: POSIX
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Text Processing
15
+ Classifier: Topic :: Utilities
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+
19
+ # lynkeus
20
+
21
+ Summarize the differences between two PDF files: are they the same, did only
22
+ the metadata change, which pages changed their text, and which changed only
23
+ visually.
24
+
25
+ ```console
26
+ $ lynkeus latex-article/base.pdf stamp/filled.pdf -o report/
27
+ == 1. hashes
28
+ A: latex-article/base.pdf
29
+ sha1 3cbca933ea700e39010c46ee4fe065adf31e5e03
30
+ sha256 0c5a8905f55047648f10893beefc8ae05388a50f492307904db922f017141975
31
+ B: stamp/filled.pdf
32
+ sha1 0b7c83be87bd32ade4936c9820b1bd53e9d257bc
33
+ sha256 518e9db4ffba1acf97aaf9e02f97f4ed29c71184fea79d008090d66b9221cfd2
34
+ raw hashes differ
35
+ file size: 116,618 → 125,415 bytes
36
+ normalized hash differs: content changed
37
+
38
+ == 2. text (5 vs 5 pages)
39
+ page 1: +3/−0 words (2 changes, similarity 97%)
40
+ thing. Participant form Name: {+Jane Doe+} Date: □ I agree
41
+ Participant form Name: Date: {+04/12/2026+} □ I agree to
42
+
43
+ == 3. visual (dpi 60, fuzz 10%, threshold 4 px)
44
+ visual-only changes (text identical): 5
45
+ page 5: 0.08% of pixels
46
+ text + visual changes: 1
47
+
48
+ == summary
49
+ 5 aligned pages, 3 unchanged, 1 text changes, 1 visual-only
50
+
51
+ report: report/report.html
52
+ ```
53
+
54
+ Here a form was filled in on page 1 (a name and a date: text changes) and a
55
+ signature image pasted on page 5 (no text: a visual-only change). Both PDFs
56
+ come from the [examples](#examples-and-tests) (`make`, then look in `build/`).
57
+
58
+ ## The name
59
+
60
+ Lynkeus (Λυγκεύς, Lynceus in Latin) was the Argonaut with the sharpest eyes in
61
+ Greek myth. He could see through tree trunks, walls and rock, and spot things
62
+ from very far away. Pindar tells how, from the top of Mount Taygetus, he
63
+ spotted Castor hiding inside a hollow oak. His name became a byword for
64
+ sharp sight ("lynx-eyed"), and Goethe made him the tower watchman of
65
+ *Faust II*, "born to see, appointed to watch".
66
+
67
+ That's the job here: look through the surface of two PDFs (bytes, metadata,
68
+ text) and spot even the smallest visual change: a ticked box, a signature,
69
+ a page number that moved.
70
+
71
+ ## How it works
72
+
73
+ The checks run from cheapest to most expensive, and stop as soon as the
74
+ answer is known:
75
+
76
+ 1. **Hashes.** SHA-1 and SHA-256 of both files. If they differ, a
77
+ *normalized* hash is computed: the file is rewritten by qpdf in a fixed
78
+ form, and dates, IDs, producer and XMP metadata are removed. Equal
79
+ normalized hashes mean "same content, only metadata differs", and the
80
+ metadata fields that changed are listed.
81
+ 2. **Text.** The text of each page is extracted (`pdftotext`) and normalized
82
+ (Unicode NFKC, invisible characters and line-end hyphenation removed).
83
+ Pages are matched by similarity, so an inserted or deleted page is
84
+ reported as such instead of shifting every later page. Changed pages get
85
+ a word count and word-level snippets. Pages with the same words in a
86
+ different order (common with math and tables) are reported separately.
87
+ 3. **Visual.** Matched pages are rendered (`pdftoppm`) and compared pixel by
88
+ pixel (ImageMagick `compare`, with a colour tolerance). A page counts as
89
+ visually changed when at least `--min-pixels` pixels differ. Pages whose
90
+ text is identical but whose pixels differ are listed as **visual-only**:
91
+ usually a figure, a font or layout change, or something pasted on top.
92
+
93
+ ## Installation
94
+
95
+ lynkeus is a Python package with a `lynkeus` command. Once it is published on
96
+ PyPI:
97
+
98
+ ```
99
+ uv tool install lynkeus # or: pipx install lynkeus
100
+ ```
101
+
102
+ From a checkout of this repository:
103
+
104
+ ```
105
+ uv tool install . # installs the `lynkeus` command
106
+ uv run lynkeus A.pdf B.pdf # or run it in place, without installing
107
+ ```
108
+
109
+ It also needs a few programs that pip and uv can't install: see
110
+ [Dependencies](#dependencies).
111
+
112
+ ## Dependencies
113
+
114
+ ### Python
115
+
116
+ Python 3.10 or newer. lynkeus uses only the standard library: the
117
+ `dependencies` list in `pyproject.toml` is empty.
118
+
119
+ ### Programs lynkeus runs
120
+
121
+ | Program | Package (Debian/Ubuntu) | Used for | Tested with |
122
+ |---|---|---|---|
123
+ | `pdftotext`, `pdftoppm`, `pdfinfo` | `poppler-utils` | text extraction, page rendering, metadata | 25.03 |
124
+ | `qpdf` | `qpdf` | normalized hash (stage 1) | 12.2 |
125
+ | `magick` | `imagemagick` (version 7) | pixel comparison, change marks and image compression in the report | 7.1.2 |
126
+
127
+ ```
128
+ sudo apt install poppler-utils qpdf imagemagick
129
+ ```
130
+
131
+ ImageMagick 7 is needed: lynkeus calls the `magick` command, which
132
+ ImageMagick 6 doesn't provide. With `--no-visual` and without `-o`,
133
+ ImageMagick isn't used at all.
134
+
135
+ ### Additionally, for the examples and tests
136
+
137
+ | Program | Package (Debian/Ubuntu) | Used for |
138
+ |---|---|---|
139
+ | `make`, `bash`, `awk`, `sed`, `grep` | `make`, base system | the test suite |
140
+ | `uv` | [docs.astral.sh/uv](https://docs.astral.sh/uv/) | runs lynkeus from the checkout |
141
+ | `pdflatex` with beamer | `texlive-latex-base`, `texlive-latex-recommended`, `cm-super` | LaTeX examples |
142
+ | `typst` 0.13 or newer (tested with 0.15.1) | [typst.app](https://github.com/typst/typst) (e.g. `cargo install typst-cli`) | Typst examples and the stamp overlays |
143
+
144
+ ```
145
+ sudo apt install make texlive-latex-base texlive-latex-recommended cm-super
146
+ ```
147
+
148
+ The Typst slides use the public [polylux](https://typst.app/universe/package/polylux)
149
+ package, which Typst downloads on the first build. The Typst examples use only
150
+ Typst's built-in fonts, so they need no font installed.
151
+
152
+ ## Usage
153
+
154
+ ```
155
+ lynkeus A.pdf B.pdf [options]
156
+ ```
157
+
158
+ `python -m lynkeus` works too.
159
+
160
+ | Option | Default | Meaning |
161
+ |---|---|---|
162
+ | `-o DIR`, `--out DIR` | | write an HTML report (`DIR/report.html`) with page images |
163
+ | `--dpi N` | 60 | render resolution for the visual comparison |
164
+ | `--fuzz P` | 10 | per-pixel colour tolerance, in % |
165
+ | `--min-pixels N` | 4 | a page counts as visually changed from N differing pixels |
166
+ | `--zoom-dpi N` | 120 | resolution of the zoomable images in the report |
167
+ | `--colors N` | 64 | palette size of the report images (`0` keeps full colour) |
168
+ | `--no-visual` | | skip stage 3 (faster, text only) |
169
+ | `-v`, `--verbose` | | show every word-level change, not only the first two per page |
170
+
171
+ **Exit status**, as with `diff`: `0` when the content is the same (identical
172
+ bytes, or only the metadata differs), `1` when it differs, `2` on error.
173
+
174
+ ### The HTML report
175
+
176
+ With `-o`, lynkeus writes `report.html` and its images to the given folder:
177
+
178
+ - a header that stays visible while scrolling, with both file names and
179
+ their SHA-1;
180
+ - filters by kind of change: text, reordered, visual-only, added, removed,
181
+ and unchanged (off by default);
182
+ - for each page, the old page, a diff image and the new page side by side,
183
+ with the changed words highlighted;
184
+ - click any image to open a full-screen viewer: both versions side by side,
185
+ zoom (mouse wheel, `+`/`−`, double-click) and pan (drag) kept in sync,
186
+ red marks over the changed areas (`m`), an optional diff pane (`d`), and
187
+ `←`/`→` to move between pages.
188
+
189
+ When the comparison stops at stage 1, the report shows the verdict and, for
190
+ metadata-only changes, a table of the fields that differ.
191
+
192
+ ## Examples and tests
193
+
194
+ `examples/` contains test documents that each change one thing at a time:
195
+
196
+ - `latex-article/`, `latex-beamer/`: LaTeX article and beamer slides
197
+ - `typst-document/`, `typst-slides/`: a plain Typst document, and slides made
198
+ with [polylux](https://typst.app/universe/package/polylux)
199
+ - `stamp/`: a signature, and a filled-in form, pasted onto an existing PDF
200
+ with a transparent Typst overlay and `qpdf --overlay`
201
+
202
+ Each document is a single source with variants chosen at build time: `base`,
203
+ `meta` (same content, different timestamp), `text`, `addpage`, `rmpage`,
204
+ `addimg` and `chgimg`.
205
+
206
+ ```
207
+ make # build every example PDF into build/
208
+ make -j8 test # build, then run the checks in examples/tests.tsv
209
+ make retest # run every check again
210
+ make clean # remove build/
211
+ ```
212
+
213
+ Each line of `examples/tests.tsv` names two PDFs, the expected exit code, and
214
+ strings lynkeus's output must (or, with a `!` prefix, must not) contain.
215
+ `make test` writes an HTML report for every check and an index at
216
+ `build/reports/index.html`, with each check's status and verdict.
217
+
218
+ The checks run lynkeus from the checkout with `uv run lynkeus`. To test
219
+ another command instead, for example an installed one, set `LYNKEUS`:
220
+ `make test LYNKEUS=lynkeus`.
221
+
222
+ ## Known limitations
223
+
224
+ - **Page numbers.** After a page is added or removed, every page whose number
225
+ or page total changed shows a small text change (`+1/−1 words`).
226
+ - **Very small glyphs.** At the default 60 dpi, a change in a tiny footer
227
+ (for example a page total going from "1/6" to "1/7") can touch fewer
228
+ pixels than the threshold. The text stage still reports it.
229
+ - **Text extraction.** If the PDF producer changes how it encodes text,
230
+ the text stage can report changes that aren't visible, for example an
231
+ emoji drawn as an image instead of a glyph, or math extracted in a
232
+ different order. Check the visual stage for those pages.
@@ -0,0 +1,7 @@
1
+ lynkeus/__init__.py,sha256=HfWS0_jYFEO49hWtzam5I78Glwd85A5ONVzJKrkjSC8,37735
2
+ lynkeus/__main__.py,sha256=3lpt9sto1q-e3N74Jvgl_U0HnLxWwcWjb08weS5-tf8,100
3
+ lynkeus-0.1.1.dist-info/licenses/LICENSE,sha256=9jHrKgdL2oYHlgqR8O63-lWabIErbLJIdkQXKIQlsPw,1069
4
+ lynkeus-0.1.1.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
5
+ lynkeus-0.1.1.dist-info/entry_points.txt,sha256=xIlfZU9SOZhF7s4cA6GAPQI9hVP9NjRWeZIjCbfFcYk,42
6
+ lynkeus-0.1.1.dist-info/METADATA,sha256=ySFEEokoO3k4VpUvYwB_spww2BucmWXepDRAOic9iBk,9503
7
+ lynkeus-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.12
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ lynkeus = lynkeus:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pierre Wilke
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.