Skip to content

armgit / Aleph

Public Imported from GitHub
0

Give satellite imagery, terrain data, buildings, streetview photos to your LLM

Generate tif for satellite results

Belluxx9a180518810d
diff --git a/docs/cli.md b/docs/cli.md
index 5855d8b..9ac7b38 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -16,6 +16,10 @@ alephgeo satellite --place "Colosseum, Rome" --best-match --size 200 -o captures
`-o captures` saves each download in the `captures` dir. Otherwise the results folders are created in the current directory.
+Satellite captures produce `satellite.tif`, a lossless RGBA Cloud Optimized GeoTIFF (COG). Missing imagery is transparent. Large outputs automatically use BigTIFF.
+
+Each capture also includes `satellite.png` with identical full-resolution pixels and transparency.
+
## Use coordinates
Coordinates are `LAT LON`; distances are in meters.
diff --git a/resources/show.svg b/resources/show.svg
index 52907f7..a63affe 100644
--- a/resources/show.svg
+++ b/resources/show.svg
@@ -558,7 +558,7 @@
id="path329" /></g><text
id="g341"
class="ink"
- aria-label="satellite.png"
+ aria-label="satellite.tif"
data-font="mono"
data-font-size="21"
x="997"
@@ -566,7 +566,7 @@
font-family="'DejaVu Sans Mono', 'Courier New', monospace"
font-size="21px"
font-weight="400"
- xml:space="preserve">satellite.png</text><text
+ xml:space="preserve">satellite.tif</text><text
id="g363"
class="muted"
aria-label="Stitched image + raw tiles"
diff --git a/src/capture.py b/src/capture.py
index b9f83a6..2456f46 100644
--- a/src/capture.py
+++ b/src/capture.py
@@ -2,17 +2,15 @@
import json
import math
-import struct
import tempfile
import time
-import zlib
from datetime import datetime, timezone
from io import BytesIO
from pathlib import Path
from PIL import Image
-from . import streetview, terrain
+from . import satellite, streetview, terrain
from .common import (
MissingImagery,
atomic_path,
@@ -315,42 +313,6 @@ def capture_osm(stage, area, folder, client, progress):
raise failure
-def merge_satellite(stage, folder):
- """Write RGBA PNG scanlines with at most one tile row decoded at a time."""
- mosaic = stage["grid"]
- width, height = mosaic["width"], mosaic["height"]
- bottom = mosaic["top"] + height
- with atomic_path(folder / "satellite.png") as temporary, temporary.open("wb") as output:
- def chunk(kind, data):
- output.write(struct.pack(">I", len(data)))
- output.write(kind)
- output.write(data)
- output.write(struct.pack(">I", zlib.crc32(data, zlib.crc32(kind))))
-
- output.write(b"\x89PNG\r\n\x1a\n")
- chunk(b"IHDR", struct.pack(">2I5B", width, height, 8, 6, 0, 0, 0))
- compressor = zlib.compressobj()
- with Image.new("RGBA", (width, min(256, height))) as strip:
- for row in range(mosaic["rows"]):
- tile_top = (mosaic["y0"] + row) * 256
- top = max(mosaic["top"], tile_top)
- strip_height = min(bottom, tile_top + 256) - top
- strip.paste((0, 0, 0, 0), (0, 0, width, strip.height))
- # Saved patches are a row-major prefix, including transparent gaps.
- first = row * mosaic["columns"]
- for photo in stage["results"][first:first + mosaic["columns"]]:
- with open_image((folder / photo["filename"]).read_bytes(), (256, 256)) as patch:
- strip.paste(patch, (photo["x"] * 256 - mosaic["left"], tile_top - top))
- for y in range(strip_height):
- with strip.crop((0, y, width, y + 1)) as scanline:
- # Filter 0 keeps encoding simple and requires no previous row.
- data = compressor.compress(b"\0" + scanline.tobytes())
- if data:
- chunk(b"IDAT", data)
- chunk(b"IDAT", compressor.flush())
- chunk(b"IEND", b"")
-
-
def export(run, folder, progress, *, rebuild=True):
"""Also works offline, on partial runs, or after a failed final export."""
# Commit capture progress before merging, which can fail or be interrupted.
@@ -364,8 +326,7 @@ def export(run, folder, progress, *, rebuild=True):
folder / "satellite/patches.geojson",
collection(feature("Polygon", [tile_ring(p)], p) for p in stage["results"]),
)
- progress("Merging satellite image")
- merge_satellite(stage, folder)
+ satellite.merge(stage, folder, progress)
elif stage["mode"] == "osm":
terrain_results = [item for item in stage["results"] if "x" in item]
count = stage["grid"]["rows"] * stage["grid"]["columns"]
@@ -383,10 +344,13 @@ def save_preview(run, folder):
b"Aleph capture\n\n"
b"streetview/photos/ contains photos; streetview/ holds GeoJSON and plan.svg.\n"
b"satellite/patches/ contains patches; satellite/ holds GeoJSON and plan.svg.\n"
- b"Open satellite.png for the merged image and map.osm for native map data.\n"
+ b"Open satellite.tif for satellite imagery and map.osm for native map data.\n"
b"Photo headings are clockwise from north; left/right follow OSM node order.\n"
b"GeoJSON files record paths, photo locations, or satellite patch footprints.\n"
- b"Satellite images are north-up Web Mercator, cropped to enclosing pixels.\n"
+ b"satellite.tif is a lossless RGBA Cloud Optimized GeoTIFF in EPSG:3857.\n"
+ b"It is north-up, cropped to enclosing pixels, with internal overviews.\n"
+ b"satellite.png contains the same full-resolution pixels for easy viewing.\n"
+ b"Transparent pixels mark missing imagery or unfinished downloads.\n"
b"terrain.tif is Float32 meters in EPSG:3857, without resampling.\n"
b"Keep terrain/tiles/ for resume and offline export.\n"
b"Filenames in the manifest and GeoJSON are relative to this run folder.\n"
diff --git a/src/dashboard.py b/src/dashboard.py
index 365f3bc..a68d269 100644
--- a/src/dashboard.py
+++ b/src/dashboard.py
@@ -130,7 +130,7 @@ class Catalog:
def file(self, identity, name):
folder, run, _ = self.get(identity)
- allowed = {"map.osm", "terrain.tif", "satellite.png", "manifest.json", "README.txt",
+ allowed = {"map.osm", "terrain.tif", "satellite.tif", "satellite.png", "manifest.json", "README.txt",
"streetview/photos.geojson", "streetview/paths.geojson", "streetview/plan.svg",
"satellite/patches.geojson", "satellite/plan.svg"}
allowed.update(item["filename"] for stage in run["stages"] for item in stage["results"]
diff --git a/src/quick.py b/src/quick.py
index 0b89f45..5a90c6a 100644
--- a/src/quick.py
+++ b/src/quick.py
@@ -156,7 +156,8 @@ def satellite(client, output, progress, *, at=None, place=None, match=None, best
north, west = coordinate(g["left"], g["top"], zoom)
south, east = coordinate(g["left"] + g["width"], g["top"] + g["height"], zoom)
result = dict(command="satellite", status="complete", folder=str(folder),
- path=str(folder / "satellite.png"), manifest=str(folder / "manifest.json"),
+ path=str(folder / "satellite.tif"), manifest=str(folder / "manifest.json"),
+ png_path=str(folder / "satellite.png"),
requested_bounds=list(area), bounds=[south, west, north, east],
width=g["width"], height=g["height"], zoom=zoom, crs="EPSG:3857",
source="Google satellite", imagery_date=None, place=selected_place)
diff --git a/src/satellite.py b/src/satellite.py
new file mode 100644
index 0000000..4f99efa
--- /dev/null
+++ b/src/satellite.py
@@ -0,0 +1,233 @@
+"""Lossless RGBA Cloud Optimized GeoTIFF and PNG exports using Pillow and the stdlib.
+
+Directories precede all pixels; tiled overviews precede full-resolution data.
+Compressed blocks are spooled to disk, bounding COG decoding to small windows.
+The PNG reuses those blocks, decoding one tile row at a time.
+No GDAL or libtiff encoder is required.
+"""
+
+import math
+import struct
+import tempfile
+import zlib
+from array import array
+
+from PIL import Image
+
+from .common import atomic_path, contained
+from .geo import MERCATOR_RADIUS
+
+BLOCK = 256
+TIFF_LIMIT = 2**32
+
+
+def region(box, read_tile):
+ """Assemble a small pixel window from 256-pixel tiles, including alpha."""
+ left, top, right, bottom = box
+ image = Image.new("RGBA", (right - left, bottom - top))
+ try:
+ for y in range(top // BLOCK, (bottom - 1) // BLOCK + 1):
+ for x in range(left // BLOCK, (right - 1) // BLOCK + 1):
+ with read_tile(x, y) as tile:
+ image.paste(tile, (x * BLOCK - left, y * BLOCK - top))
+ return image
+ except BaseException:
+ image.close()
+ raise
+
+
+class Level:
+ def __init__(self, width, height):
+ self.width, self.height = width, height
+ self.columns = math.ceil(width / BLOCK)
+ self.rows = math.ceil(height / BLOCK)
+ self.offsets, self.sizes = array("Q"), array("I")
+
+ def read(self, stream, x, y):
+ i = y * self.columns + x
+ stream.seek(self.offsets[i])
+ raw = zlib.decompress(stream.read(self.sizes[i]))
+ return Image.frombytes("RGBA", (BLOCK, BLOCK), raw)
+
+ def write(self, stream, image):
+ with Image.new("RGBA", (BLOCK, BLOCK)) as tile:
+ tile.paste(image, (0, 0))
+ data = zlib.compress(tile.tobytes())
+ stream.seek(0, 2)
+ self.offsets.append(stream.tell())
+ self.sizes.append(len(data))
+ stream.write(data)
+
+
+def header(levels, grid, *, big=False):
+ """Encode just the TIFF directories and GeoKeys, with final block offsets.
+
+ Classic TIFF uses 32-bit offsets; BigTIFF uses 64-bit offsets. Pixel data
+ follows this header in smallest-to-largest level order, row-major per level.
+ """
+ offset_format, count_format = ("Q", "Q") if big else ("I", "H")
+ inline = 8 if big else 4
+ directories = []
+ scale = 2 * math.pi * MERCATOR_RADIUS / (BLOCK * 2**grid["zoom"])
+ half = math.pi * MERCATOR_RADIUS
+ for i, level in enumerate(levels):
+ # (TIFF type, values). ExtraSamples=2 means unassociated alpha.
+ tags = {
+ 254: (4, [int(i != 0)]), 256: (4, [level.width]), 257: (4, [level.height]),
+ 258: (3, [8, 8, 8, 8]), 259: (3, [8]), 262: (3, [2]),
+ 277: (3, [4]), 284: (3, [1]), 322: (4, [BLOCK]), 323: (4, [BLOCK]),
+ 324: (16 if big else 4, [0] * len(level.sizes)),
+ 325: (4, level.sizes), 338: (3, [2]),
+ }
+ if i == 0:
+ tags.update({
+ 33550: (12, [scale, scale, 0]),
+ 33922: (12, [0, 0, 0, grid["left"] * scale - half,
+ half - grid["top"] * scale, 0]),
+ 34735: (3, [1, 1, 0, 3, 1024, 0, 1, 1, 1025, 0, 1, 1, 3072, 0, 1, 3857]),
+ })
+ directories.append(tags)
+
+ data = bytearray(struct.pack("<2sHHHQ", b"II", 43, 8, 0, 16) if big
+ else struct.pack("<2sHI", b"II", 42, 8))
+ locations = []
+ for tags in directories:
+ data.extend(b"\0" * (-len(data) % 8))
+ locations.append(len(data))
+ data.extend(b"\0" * ((8 if big else 2) + len(tags) * (20 if big else 12) + inline))
+ deferred = []
+ offset_fields = []
+ for i, tags in enumerate(directories):
+ cursor = locations[i]
+ struct.pack_into("<" + count_format, data, cursor, len(tags))
+ cursor += 8 if big else 2
+ for code, (kind, values) in sorted(tags.items()):
+ struct.pack_into("<HH" + offset_format, data, cursor, code, kind, len(values))
+ field = cursor + (12 if big else 8)
+ raw = struct.pack("<" + {3: "H", 4: "I", 12: "d", 16: "Q"}[kind] * len(values), *values)
+ if len(raw) <= inline:
+ data[field:field + len(raw)] = raw
+ if code == 324:
+ offset_fields.append((i, field))
+ else:
+ deferred.append((code in (324, 325), i, code, field, raw))
+ cursor += 20 if big else 12
+ struct.pack_into("<" + offset_format, data, cursor,
+ locations[i + 1] if i + 1 < len(locations) else 0)
+ # Keep metadata before potentially large tile offset/count arrays.
+ for _, i, code, field, raw in sorted(deferred, key=lambda item: item[0]):
+ data.extend(b"\0" * (-len(data) % 8))
+ struct.pack_into("<" + offset_format, data, field, len(data))
+ if code == 324:
+ offset_fields.append((i, len(data)))
+ data.extend(raw)
+ data.extend(b"\0" * (-len(data) % 8))
+ starts, cursor = {}, len(data)
+ for i in reversed(range(len(levels))):
+ starts[i] = cursor
+ cursor += sum(levels[i].sizes)
+ if not big and cursor >= TIFF_LIMIT:
+ return header(levels, grid, big=True)
+ for i, field in offset_fields:
+ cursor = starts[i]
+ for size in levels[i].sizes:
+ struct.pack_into("<" + offset_format, data, field, cursor)
+ cursor += size
+ field += inline
+ return data
+
+
+def write_png(path, level, spool, progress):
+ """Stream the full-resolution pixels as PNG, decoding one tile row at a time."""
+ with path.open("wb") as output:
+ def chunk(kind, data):
+ output.write(struct.pack(">I", len(data)))
+ output.write(kind)
+ output.write(data)
+ output.write(struct.pack(">I", zlib.crc32(data, zlib.crc32(kind))))
+
+ output.write(b"\x89PNG\r\n\x1a\n")
+ chunk(b"IHDR", struct.pack(">2I5B", level.width, level.height, 8, 6, 0, 0, 0))
+ compressor = zlib.compressobj()
+ progress("Building satellite.png", 0, level.rows)
+ for row, top in enumerate(range(0, level.height, BLOCK), 1):
+ with region((0, top, level.width, min(top + BLOCK, level.height)),
+ lambda x, y: level.read(spool, x, y)) as strip:
+ for y in range(strip.height):
+ with strip.crop((0, y, level.width, y + 1)) as scanline:
+ data = compressor.compress(b"\0" + scanline.tobytes())
+ if data:
+ chunk(b"IDAT", data)
+ progress("Building satellite.png", row, level.rows)
+ chunk(b"IDAT", compressor.flush())
+ chunk(b"IEND", b"")
+
+
+def merge(stage, folder, progress):
+ """Write satellite.tif and satellite.png, retaining transparent gaps."""
+ grid = stage["grid"]
+ levels = [Level(grid["width"], grid["height"])]
+ while max(levels[-1].width, levels[-1].height) > BLOCK:
+ previous = levels[-1]
+ levels.append(Level((previous.width + 1) // 2, (previous.height + 1) // 2))
+ count = sum(level.columns * level.rows for level in levels)
+ done = 0
+ progress("Building satellite.tif", done, count)
+
+ def source(x, y):
+ index = (y - grid["y0"]) * grid["columns"] + x - grid["x0"]
+ if index >= len(stage["results"]):
+ return Image.new("RGBA", (BLOCK, BLOCK))
+ tile = stage["results"][index]
+ if (tile["x"], tile["y"], tile["zoom"]) != (x, y, grid["zoom"]):
+ raise ValueError("Invalid saved satellite tile order.")
+ with Image.open(contained(folder, tile["filename"])) as image:
+ if image.format not in ("JPEG", "PNG") or image.size != (BLOCK, BLOCK):
+ raise ValueError("Expected a 256 × 256 satellite JPEG or PNG.")
+ return image.convert("RGBA")
+
+ with (
+ atomic_path(folder / "satellite.tif") as temporary,
+ atomic_path(folder / "satellite.png") as png_temporary,
+ tempfile.TemporaryFile(dir=folder) as spool,
+ ):
+ for i, level in enumerate(levels):
+ for y in range(0, level.height, BLOCK):
+ for x in range(0, level.width, BLOCK):
+ width, height = min(BLOCK, level.width - x), min(BLOCK, level.height - y)
+ if i == 0:
+ left, top = grid["left"] + x, grid["top"] + y
+ with region((left, top, left + width, top + height), source) as image:
+ level.write(spool, image)
+ else:
+ previous = levels[i - 1]
+ # Fractional windows preserve the extent for odd dimensions.
+ sx, sy = previous.width / level.width, previous.height / level.height
+ box = (x * sx, y * sy, (x + width) * sx, (y + height) * sy)
+ window = (math.floor(box[0]), math.floor(box[1]),
+ math.ceil(box[2]), math.ceil(box[3]))
+ local = tuple(v - window[j % 2] for j, v in enumerate(box))
+ with (
+ region(window, lambda tx, ty: previous.read(spool, tx, ty)) as image,
+ image.resize((width, height), Image.Resampling.BOX, box=local) as smaller,
+ ):
+ level.write(spool, smaller)
+ done += 1
+ progress("Building satellite.tif", done, count)
+ with temporary.open("wb") as output:
+ output.write(header(levels, grid))
+ total_bytes = sum(sum(level.sizes) for level in levels)
+ copied = 0
+ progress("Saving satellite.tif", copied, total_bytes, "bytes")
+ for level in reversed(levels):
+ spool.seek(level.offsets[0])
+ remaining = sum(level.sizes)
+ while remaining:
+ data = spool.read(min(1024 * 1024, remaining))
+ if not data:
+ raise OSError("Truncated satellite export spool.")
+ output.write(data)
+ remaining -= len(data)
+ copied += len(data)
+ progress("Saving satellite.tif", copied, total_bytes, "bytes")
+ write_png(png_temporary, levels[0], spool, progress)
diff --git a/tests/test_capture.py b/tests/test_capture.py
index 434cc9b..25a5ab4 100644
--- a/tests/test_capture.py
+++ b/tests/test_capture.py
@@ -122,14 +122,12 @@ class CaptureRecoveryTests(unittest.TestCase):
colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0)]
self.client.get.side_effect = [image_bytes((256, 256), color) for color in colors]
previous = image_bytes((1, 1), "black")
- (self.folder / "satellite.png").write_bytes(previous)
- compressor = Mock()
- compressor.compress.side_effect = OSError("export disk full")
- with patch("src.capture.zlib.compressobj", return_value=compressor):
+ (self.folder / "satellite.tif").write_bytes(previous)
+ with patch("src.satellite.zlib.compress", side_effect=OSError("export disk full")):
with self.assertRaisesRegex(OSError, "export disk full"):
capture.download(run, self.folder, self.client, self.progress)
- self.assertEqual((self.folder / "satellite.png").read_bytes(), previous)
- self.assertFalse(list(self.folder.glob(".satellite.png-*")))
+ self.assertEqual((self.folder / "satellite.tif").read_bytes(), previous)
+ self.assertFalse(list(self.folder.glob(".satellite.tif-*")))
saved = capture.load(self.folder)
self.assertEqual(saved["state"], "failed")
self.assertFalse(saved["exports_saved"])
@@ -137,15 +135,23 @@ class CaptureRecoveryTests(unittest.TestCase):
self.client.get.reset_mock()
self.client.get.side_effect = AssertionError("Saved tiles must not be downloaded again")
+ (self.folder / "satellite.png").write_bytes(previous)
+ with patch("src.satellite.zlib.compressobj", side_effect=OSError("PNG disk full")):
+ with self.assertRaisesRegex(OSError, "PNG disk full"):
+ capture.download(saved, self.folder, self.client, self.progress)
+ for extension in ("tif", "png"):
+ self.assertEqual((self.folder / f"satellite.{extension}").read_bytes(), previous)
+ self.assertFalse(list(self.folder.glob(f".satellite.{extension}-*")))
+ self.assertFalse(capture.load(self.folder)["exports_saved"])
capture.download(saved, self.folder, self.client, self.progress)
self.client.get.assert_not_called()
self.assertEqual(capture.load(self.folder)["state"], "complete")
- with Image.open(self.folder / "satellite.png") as mosaic:
+ with Image.open(self.folder / "satellite.tif") as mosaic:
self.assertEqual(mosaic.size, (256, 256))
self.assertEqual([mosaic.getpixel(point) for point in ((0, 0), (255, 0), (0, 255), (255, 255))],
[(*color, 255) for color in colors])
- def test_satellite_strips_match_mosaic_for_empty_partial_and_complete_captures(self):
+ def test_satellite_cog_matches_mosaic_for_empty_partial_and_complete_captures(self):
north, west = geo.coordinate(384, 384, 3)
south, east = geo.coordinate(896, 984, 3)
run = capture.plan(self.client, [south, west, north, east],
@@ -169,9 +175,14 @@ class CaptureRecoveryTests(unittest.TestCase):
with patch.object(Image, "new", wraps=Image.new) as allocate:
capture.export(run, self.folder, self.progress)
self.assertTrue(allocate.called)
- self.assertTrue(all(call.args[1][1] <= 256 for call in allocate.call_args_list))
+ self.assertTrue(all(max(call.args[1]) <= 513 for call in allocate.call_args_list))
+ with Image.open(self.folder / "satellite.tif") as actual:
+ self.assertEqual(actual.format, "TIFF")
+ self.assertEqual(actual.size, expected.size)
+ self.assertEqual(actual.mode, "RGBA")
+ self.assertEqual(actual.tobytes(), expected.tobytes())
with Image.open(self.folder / "satellite.png") as actual:
- actual.verify() # Includes PNG chunk CRCs.
+ actual.verify()
with Image.open(self.folder / "satellite.png") as actual:
self.assertEqual(actual.size, expected.size)
self.assertEqual(actual.mode, "RGBA")
@@ -192,8 +203,8 @@ class CaptureRecoveryTests(unittest.TestCase):
self.assertTrue(missing.fp.closed)
saved = capture.load(self.folder)
self.assertEqual(saved["state"], "complete")
- original = (self.folder / "satellite.png").read_bytes()
- with Image.open(self.folder / "satellite.png") as mosaic:
+ original = (self.folder / "satellite.tif").read_bytes()
+ with Image.open(self.folder / "satellite.tif") as mosaic:
self.assertEqual(mosaic.size, (256, 256))
self.assertEqual(mosaic.getpixel((0, 0)), (255, 0, 0, 255))
self.assertEqual(mosaic.crop((128, 0, 256, 128)).getchannel("A").getextrema(), (0, 0))
@@ -202,7 +213,7 @@ class CaptureRecoveryTests(unittest.TestCase):
self.client.get.reset_mock()
capture.download(saved, self.folder, self.client, self.progress)
self.client.get.assert_not_called()
- self.assertEqual((self.folder / "satellite.png").read_bytes(), original)
+ self.assertEqual((self.folder / "satellite.tif").read_bytes(), original)
def test_osm_failure_still_saves_terrain_and_resume_fetches_only_map(self):
run = capture.plan(self.client, [1, 1, 2, 2],
diff --git a/tests/test_cli.py b/tests/test_cli.py
index b04f6a8..f2ef8de 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -56,4 +56,5 @@ class CaptureCommandTests(unittest.TestCase):
with patch.object(Client, "get", side_effect=AssertionError("Export must stay offline")):
exported = invoke("export", folder)
self.assertEqual(exported["folder"], folder)
+ self.assertTrue((Path(folder) / "satellite.tif").is_file())
self.assertTrue((Path(folder) / "satellite.png").is_file())
diff --git a/tests/test_queries.py b/tests/test_queries.py
index 34c0ae6..b86b775 100644
--- a/tests/test_queries.py
+++ b/tests/test_queries.py
@@ -98,7 +98,10 @@ class QueryTests(unittest.TestCase):
self.assertEqual(status, 0, result)
self.assertGreater(result["width"] * result["height"], 16_000_000)
self.assertGreater(self.get.call_count, 128)
+ self.assertEqual(Path(result["path"]).name, "satellite.tif")
self.assertTrue(Path(result["path"]).is_file())
+ self.assertEqual(Path(result["png_path"]).name, "satellite.png")
+ self.assertTrue(Path(result["png_path"]).is_file())
def test_single_streetview_uses_actual_camera_and_look_at_without_osm(self):
def response(address, **kwargs):
diff --git a/tests/test_satellite.py b/tests/test_satellite.py
new file mode 100644
index 0000000..2037f83
--- /dev/null
+++ b/tests/test_satellite.py
@@ -0,0 +1,108 @@
+"""Check COG layout and pixels with Pillow's independent TIFF reader."""
+
+import math
+import struct
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from PIL import Image
+
+from src import geo, satellite
+
+
+class SatelliteTests(unittest.TestCase):
+ def test_cog_layout_georeferencing_and_overviews_in_classic_and_bigtiff(self):
+ # Odd dimensions and a crop across source tiles expose overview seams,
+ # padded-edge darkening, and incorrect georeferencing to whole tile edges.
+ north, west = geo.coordinate(383, 391, 4)
+ south, east = geo.coordinate(1408, 1160, 4)
+ grid = geo.grid((south, west, north, east), 4)
+ for big in (False, True):
+ with self.subTest(big=big), tempfile.TemporaryDirectory() as directory:
+ folder = Path(directory)
+ stage = dict(grid=grid, results=[])
+ expected = self.enterContext(Image.new("RGBA", (1025, 769)))
+ for i, tile in enumerate(geo.tiles(grid)):
+ name = f"{i}.png"
+ # Transparent red must not bleed into the blue overview.
+ color = (255, 0, 0, 0) if i % 3 == 0 else (0, 80 + i * 5, 200, 255)
+ with Image.new("RGBA", (256, 256), color) as image:
+ image.save(folder / name)
+ expected.paste(image, (tile["x"] * 256 - grid["left"],
+ tile["y"] * 256 - grid["top"]))
+ stage["results"].append(dict(tile, filename=name))
+ with patch.object(satellite, "TIFF_LIMIT", 0 if big else 2**32):
+ satellite.merge(stage, folder, Mock())
+ path = folder / "satellite.tif"
+ data = path.read_bytes()
+ self.assertEqual(struct.unpack_from("<H", data, 2)[0], 43 if big else 42)
+ ifds, offsets, ends, metadata_ends = [], [], [], []
+ with Image.open(path) as image:
+ self.assertEqual(image.n_frames, 4)
+ for frame, size in enumerate(((1025, 769), (513, 385), (257, 193), (129, 97))):
+ image.seek(frame)
+ tags = image.tag_v2
+ self.assertEqual(image.size, size)
+ self.assertEqual(image.mode, "RGBA")
+ self.assertEqual(tags[254], int(frame != 0))
+ self.assertEqual((tags[322], tags[323]), (256, 256))
+ self.assertEqual(tags[259], 8) # Deflate, lossless.
+ self.assertEqual(tags[338], (2,)) # Unassociated alpha.
+ if frame == 0:
+ scale = 2 * math.pi * geo.MERCATOR_RADIUS / 4096
+ self.assertEqual(tags[33550], (scale, scale, 0))
+ self.assertEqual(tags[33922], (0, 0, 0, 383 * scale - math.pi * geo.MERCATOR_RADIUS,
+ math.pi * geo.MERCATOR_RADIUS - 391 * scale, 0))
+ self.assertEqual(tags[34735], (1, 1, 0, 3, 1024, 0, 1, 1,
+ 1025, 0, 1, 1, 3072, 0, 1, 3857))
+ else:
+ self.assertNotIn(33550, tags) # Overviews inherit the full image extent.
+ smaller = expected.resize(size, Image.Resampling.BOX)
+ expected.close()
+ expected = self.enterContext(smaller)
+ self.assertEqual(image.tobytes(), expected.tobytes())
+ tile_offsets, tile_sizes = tags[324], tags[325]
+ self.assertEqual(len(tile_offsets), math.ceil(size[0] / 256) * math.ceil(size[1] / 256))
+ self.assertTrue(all(b == a + count for a, b, count in
+ zip(tile_offsets, tile_offsets[1:], tile_sizes)))
+ offsets.append(tile_offsets[0])
+ ends.append(tile_offsets[-1] + tile_sizes[-1])
+ # Inspect byte positions independently of the writer. All IFDs
+ # and out-of-line tag values must precede the first tile.
+ position = struct.unpack_from("<Q" if big else "<I", data, 8 if big else 4)[0]
+ while position:
+ ifds.append(position)
+ self.assertEqual(position % (8 if big else 2), 0)
+ count = struct.unpack_from("<Q" if big else "<H", data, position)[0]
+ cursor = position + (8 if big else 2)
+ for _ in range(count):
+ _, kind, length, value = struct.unpack_from("<HHQQ" if big else "<HHII", data, cursor)
+ size = {3: 2, 4: 4, 12: 8, 16: 8}[kind] * length
+ if size > (8 if big else 4):
+ metadata_ends.append(value + size)
+ cursor += 20 if big else 12
+ metadata_ends.append(cursor + (8 if big else 4))
+ position = struct.unpack_from("<Q" if big else "<I", data, cursor)[0]
+ self.assertEqual(len(ifds), 4)
+ self.assertEqual(ifds, sorted(ifds))
+ self.assertLessEqual(max(metadata_ends), min(offsets))
+ self.assertEqual(offsets, sorted(offsets, reverse=True))
+ self.assertEqual(ends[1:], offsets[:-1])
+ self.assertEqual(ends[0], len(data))
+
+ def test_bigtiff_offsets_cross_four_gib_without_allocating_pixel_data(self):
+ full, overview = satellite.Level(768, 512), satellite.Level(256, 171)
+ full.sizes.extend([2**30] * 6)
+ overview.sizes.append(100)
+ data = satellite.header([full, overview], dict(left=0, top=0, zoom=1))
+ self.assertEqual(data[:4], b"II+\0")
+ # IFD 0: read LONG8 tile offsets directly from its directory.
+ count = struct.unpack_from("<Q", data, 16)[0]
+ entries = [struct.unpack_from("<HHQQ", data, 24 + i * 20) for i in range(count)]
+ _, kind, count, pointer = next(entry for entry in entries if entry[0] == 324)
+ self.assertEqual((kind, count), (16, 6))
+ offsets = struct.unpack_from("<6Q", data, pointer)
+ self.assertEqual(offsets[0], len(data) + 100)
+ self.assertGreater(offsets[-1], 2**32)