from urllib.parse import parse_qs, urlsplit
import numpy as np
from local_server import serve
from tiles import TILE, png
from dataloader_rs import HttpDataset, ImageCollator, PyDataloader
from dataloader_rs import transforms as T
WIDTH, HEIGHT = 2 * TILE + TILE // 2, 2 * TILE TOKEN = "Bearer example-token"
def tile_server(path: str, headers) -> tuple[int, bytes]:
if headers.get("Authorization") != TOKEN:
return 401, b"missing token"
url = urlsplit(path)
query = parse_qs(url.query)
if url.path != "/tile" or "x" not in query or "y" not in query:
return 404, b"not found"
x, y = int(query["x"][0]), int(query["y"][0])
width, height = min(TILE, WIDTH - x), min(TILE, HEIGHT - y)
if width <= 0 or height <= 0:
return 404, b"outside the image"
pixels = np.zeros((height, width, 3), dtype=np.uint8)
pixels[..., 0] = x // 3
pixels[..., 1] = y // 2
return 200, png(pixels)
def main() -> None:
coords = np.array([(x, y) for y in range(0, HEIGHT, TILE) for x in range(0, WIDTH, TILE)])
decode = T.Compose(
[
T.Decode(),
T.ToRgb(),
T.PadTo(TILE, TILE), T.ToFloat(),
T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
T.ToChw(),
]
)
with serve(tile_server) as base:
tiles = HttpDataset.from_template(
base + "/tile?x={x}&y={y}",
{"x": coords[:, 0], "y": coords[:, 1]},
headers={"Authorization": TOKEN},
)
loader = PyDataloader(
tiles,
batch_size=4,
num_workers=2,
item_concurrency=4, transform=decode,
collate_fn=ImageCollator(),
return_indices=True,
)
for images, indices in loader:
batch = np.asarray(images) tile_coords = coords[indices] print(batch.shape, batch.dtype, "at", [tuple(int(v) for v in c) for c in tile_coords])
if __name__ == "__main__":
main()