Files
2026-11-05 21:22:03 +00:00

41 lines
1.5 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""tools/manual/find_pages.py <pass.pdf> <toc.json> <pages.json>: sucht die Seitenzahl jeder Überschrift für das Inhaltsverzeichnis."""
import io
import json
import sys
import pymupdf
pdf, toc_file, out = sys.argv[1], sys.argv[2], sys.argv[3]
toc = json.load(io.open(toc_file, encoding='utf-8'))
doc = pymupdf.open(pdf)
heads = [] # (Seite, Text, Größe)
for pno in range(len(doc)):
for b in doc[pno].get_text('dict')['blocks']:
for l in b.get('lines', []):
txt = ''.join(s['text'] for s in l['spans']).strip()
size = max((s['size'] for s in l['spans']), default=0)
if size >= 12 and txt:
heads.append((pno + 1, txt, size))
pages = {}
cursor = 0
missing = []
for t in toc:
key = t['title'].strip()
found = None
for i in range(cursor, len(heads)):
p, txt, size = heads[i]
# Überschrift = "<Nr> <Titel>"; lange Titel brechen um, darum Anfang vergleichen
flat = txt.replace(' ', ' ')
if flat.endswith(key) or flat == t['num'] + ' ' + key or key.startswith(flat.split(' ', 1)[-1][:25]) and flat.startswith(t['num'] + ' '):
if flat.startswith(t['num'] + ' ') or flat.startswith(t['num']):
found = (i, p)
break
if found:
cursor = found[0] + 1
pages['k' + t['num'].replace('.', '_')] = found[1]
else:
missing.append(t['num'] + ' ' + key)
json.dump(pages, io.open(out, 'w', encoding='utf-8'))
print('gefunden: %d von %d; fehlend: %s' % (len(pages), len(toc), missing[:10]))