A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Tools: pypdf 6 for the digitise tools (Fixes #1251) (#1259)
Eyal Golan69d99b9586d6
diff --git a/tools/armistice_digitise.py b/tools/armistice_digitise.pyindex 6be645e97..a835ded00 100644--- a/tools/armistice_digitise.py+++ b/tools/armistice_digitise.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = ["numpy==2.5.3", "scipy==1.17.1", "pillow==12.3.0", "shapely==2.2.0", "rasterio==1.5.2", "pyproj==3.8.0",-# "scikit-image==0.26.0", "pypdf==5.4.0"]+# "scikit-image==0.26.0", "pypdf==6.21.1"]# ///"""Digitises the 1949 armistice lines that the primary sources allow, as true lines (not hex-snapped), intocontent/map/armistice_lines_1949.geojson. Owner rulings (2026-10-11): the lines come from the four General Armistice@@ -197,6 +197,27 @@ def check(path: Path, src: dict) -> None:raise SystemExit(f"{path}: sha256 {got}, expected {src['sha256']} ({src['url']})")+def jpeg_as_pypdf5(jpeg: bytes):+ """A JPEG stream decoded as pypdf 5.x decoded a /DCTDecode image (#1251): decoded by Pillow, saved again as a JPEG with+ Pillow's defaults, and that copy decoded. pypdf 6.3 and later return the first decode, which moves pixels on the ISA+ and khan_yunis scans; the committed lines were digitised on these pixels, so the tools keep them."""+ from PIL import Image+ buf = io.BytesIO()+ Image.open(io.BytesIO(jpeg), formats=("JPEG",)).save(buf, format="JPEG")+ return Image.open(io.BytesIO(buf.getvalue()), formats=("JPEG",))+++def pdf_page_image(pdf: Path, page: int):+ """The largest image on a PDF page (0-based) as a Pillow image; a /DCTDecode image goes through jpeg_as_pypdf5, the+ others (CCITT, JPX: the same pixels on pypdf 5.4.0 and 6.21.1) through pypdf."""+ from pypdf import PdfReader+ im = max(PdfReader(pdf).pages[page].images, key=lambda im: im.image.size[0] * im.image.size[1])+ xobj = im.indirect_reference.get_object()+ if xobj.get("/Filter") == "/DCTDecode":+ return jpeg_as_pypdf5(xobj.get_data())+ return im.image++def grid_fit(img_v: np.ndarray, img_h: np.ndarray, sheet: dict, px_per_km, thr: float, along: int, detrend: bool,tols=(0.15, 0.08, 0.05, 0.05)) -> dict:"""Fits E and N (km) as affine functions of scan pixels from the map's drawn 1-km grid lines: in bands across each@@ -294,12 +315,10 @@ def syria_line(pdf: Path, log) -> tuple[list, dict]:"""The Armistice Demarcation Line: the colour scan's green line, registered on the Annex I points and traced betweenthem; returns [(E, N)] vertices (Palestine-grid km) and diagnostics."""from PIL import Image- from pypdf import PdfReaderfrom scipy import ndimage as ndifrom skimage.graph import route_through_arrayImage.MAX_IMAGE_PIXELS = None- page = PdfReader(pdf).pages[13]- img = max(page.images, key=lambda im: im.image.size[0] * im.image.size[1]).image.convert("RGB")+ img = pdf_page_image(pdf, 13).convert("RGB")rgb = np.asarray(img).astype(np.int16)gray = rgb.mean(axis=2).astype(np.float32)r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]@@ -563,15 +582,13 @@ MV_GAPS = ("The signed map draws the demarcation line only in pieces: on sheet 1def egypt_1950(sheet1: Path, sheet2: Path, log) -> dict:"""The demarcation line as drawn on the two signed sheets of S/1471, traced between waypoints."""from PIL import Image- from pypdf import PdfReaderfrom scipy import ndimage as ndifrom shapely.geometry import LineStringImage.MAX_IMAGE_PIXELS = Noned1 = ~np.asarray(Image.open(sheet1).convert("1"))f1 = grid_fit(d1.astype(np.float32), d1.astype(np.float32),{"y": (470, 9900), "x": (390, 4300), "anchor": ((772, 2000, 101.0), (2000, 850, 123.0))}, 390.0, 0.3, 150, True)- page = PdfReader(sheet2).pages[0]- g2 = np.asarray(max(page.images, key=lambda im: im.image.size[0] * im.image.size[1]).image.convert("L")).astype(np.float32)+ g2 = np.asarray(pdf_page_image(sheet2, 0).convert("L")).astype(np.float32)f2 = grid_fit(ndi.uniform_filter1d(g2, 25, axis=1) - g2, ndi.uniform_filter1d(g2, 25, axis=0) - g2,{"y": (470, 6700), "x": (210, 3100), "anchor": ((193, 2000, 80.0), (1500, 452, 90.0))}, (295.0, 295.0), 6.0, 120, False)d2 = g2 < 110diff --git a/tools/control_digitise.py b/tools/control_digitise.pyindex a308080e0..182e95789 100644--- a/tools/control_digitise.py+++ b/tools/control_digitise.py@@ -1,7 +1,7 @@# /// script# requires-python = ">=3.11"# dependencies = ["numpy==2.5.3", "scipy==1.17.1", "pillow==12.3.0", "shapely==2.2.0", "pyproj==3.8.0",-# "scikit-image==0.26.0", "pypdf==5.4.0"]+# "scikit-image==0.26.0", "pypdf==6.21.1"]# ///"""Digitises who held which areas of Mandatory Palestine in 1948-49, by date, as true polygons, intocontent/map/control_1948_49.geojson (status draft; owner-verify). Owner rulings of 2026-10-14: the map colours areas by@@ -420,10 +420,8 @@ FACT_SOURCES = [ISA_MAP, RES181, S1025, CIA_MAP]def load_scan(pdf: Path) -> np.ndarray:from PIL import Image- from pypdf import PdfReaderad.check(pdf, ISA_MAP)- page = PdfReader(pdf).pages[1]- img = max(page.images, key=lambda im: im.image.size[0] * im.image.size[1]).image.convert("RGB")+ img = ad.pdf_page_image(pdf, 1).convert("RGB")a = np.asarray(img).astype(np.int16)if a.shape[:2] != (4078, 2368):raise SystemExit(f"{pdf}: the map image is {a.shape[1]} x {a.shape[0]} px, expected 2368 x 4078")@@ -557,10 +555,8 @@ def trace_all(a: np.ndarray, log) -> dict:def load_cia(pdf: Path) -> np.ndarray:"""The 18 May 1948 map (page 2) as an ink mask (True: dark)."""- from pypdf import PdfReaderad.check(pdf, CIA_MAP)- page = PdfReader(pdf).pages[1]- img = max(page.images, key=lambda im: im.image.size[0] * im.image.size[1]).image.convert("L")+ img = ad.pdf_page_image(pdf, 1).convert("L")a = np.asarray(img) < 128if a.shape != (2108, 1594):raise SystemExit(f"{pdf}: the map image is {a.shape[1]} x {a.shape[0]} px, expected 1594 x 2108")diff --git a/tools/tests/test_armistice.py b/tools/tests/test_armistice.pyindex 398ef002d..958f3e013 100644--- a/tools/tests/test_armistice.py+++ b/tools/tests/test_armistice.py@@ -372,3 +372,47 @@ def test_no_stale_statements_about_the_1950_line():assert "Art. V (the signed map decides)" not in ad.MV_TEXT["cite"] and "used only as a named cross-check" not in ad.S1471["cite"]urls = [s["url"] for s in SOURCE["statecraft"]["sources"]]assert len(urls) == len(set(urls)), "each source listed once"+++# --- the PDF image decode (#1251) -------------------------------------------------------------------------------------++def _jpeg(mode: str) -> bytes:+ import io+ from PIL import Image+ rng = np.random.default_rng(1251)+ shape = (64, 96, 3) if mode == "RGB" else (64, 96)+ buf = io.BytesIO()+ Image.fromarray(rng.integers(0, 256, shape, dtype=np.uint8), mode).save(buf, format="JPEG", quality=95)+ return buf.getvalue()++[email protected]("mode", ["RGB", "L"])+def test_a_pdf_jpeg_decodes_as_pypdf_5_did(mode):+ """pypdf 5.x re-saved a /DCTDecode image as a JPEG with Pillow's defaults and decoded that copy; the committed lines+ were digitised on those pixels (R0005czg.pdf page 2: a9321f3f..., khan_yunis.pdf: 8a3187fa...), so the tools keep it."""+ import io+ from PIL import Image+ raw = _jpeg(mode)+ once = Image.open(io.BytesIO(raw))+ buf = io.BytesIO()+ once.save(buf, format="JPEG")+ twice = np.asarray(Image.open(io.BytesIO(buf.getvalue())))+ got = ad.jpeg_as_pypdf5(raw)+ assert got.mode == mode+ assert np.array_equal(np.asarray(got), twice)+ assert not np.array_equal(np.asarray(got), np.asarray(once)), "a single decode is pypdf 6.3+'s, not the tools'"+++def test_pdf_page_image_takes_the_raw_jpeg_stream(tmp_path):+ """The largest image of the page, its /DCTDecode stream decoded by jpeg_as_pypdf5 whatever pypdf's own decode is."""+ import io+ pytest.importorskip("pypdf")+ from PIL import Image+ raw = _jpeg("RGB")+ small = Image.new("RGB", (8, 8), (255, 0, 0))+ pdf = tmp_path / "scan.pdf"+ Image.open(io.BytesIO(raw)).save(pdf, format="PDF", save_all=True, append_images=[small])+ from pypdf import PdfReader+ xobj = PdfReader(pdf).pages[0].images[0].indirect_reference.get_object()+ assert xobj["/Filter"] == "/DCTDecode"+ assert np.array_equal(np.asarray(ad.pdf_page_image(pdf, 0)), np.asarray(ad.jpeg_as_pypdf5(xobj.get_data())))