Skip to content

Python and npm bindings, and datasets in memory - #12

Merged
giswqs merged 2 commits into
mainfrom
bindings
Oct 14, 2026
Merged

giswqs merged 2 commits into
mainfrom
bindings

Conversation

@giswqs

@giswqs giswqs commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

Roadmap 0.5 bindings: a Python package (PyO3 + NumPy, python/) and an npm package (wasm-bindgen, js/), plus a small core addition, terrio::memory, to open datasets from bytes and write them to bytes.

Python (terrio on PyPI)

abi3 wheels for Python ≥ 3.10, built with maturin; the only runtime dependency is NumPy. Rust doc comments are Google-style Python docstrings.

import terrio

dem = terrio.open_raster("dem.tif")                 # or terrio.open(path) -> Raster | VectorDataset
dem.width, dem.height, dem.count, dem.dtype, dem.nodata, dem.crs, dem.transform, dem.bounds
a = dem.read(1)                                      # (rows, cols), native dtype; read() -> (bands, rows, cols)

cog = terrio.open_raster("https://.../USGS_1_n40w106.tif", lazy=True)   # headers only
tile = cog.read(window=(2000, 3000, 256, 200))       # range requests for the needed tiles
thumb = cog.read(1, overview=2)

r = terrio.Raster.from_array(a * 2, dem.transform, crs=dem.crs, nodata=dem.nodata)
r.write("x2.tif", compress="DEFLATE"); r.to_bytes("x2.tif")
terrio.open_bytes(open("dem.tif", "rb").read(), "dem.tif", lazy=True)

ds = terrio.open_vector("countries.gpkg", layers=None)
layer = ds["countries"]                              # ds.layers, ds[0], iteration
layer.name, layer.crs, layer.geometry_type, layer.fields, len(layer), layer.bounds
layer.to_geojson(); layer.to_wkb(); layer.columns(); layer.to_geopandas(); layer.to_crs("EPSG:3857")
terrio.write_vector(layer, "out.fgb"); terrio.write_vector(geojson_dict_or_geodataframe, "out.gpkg")

terrio.info("dem.tif", stats=True)                   # same dict as `terrio info --json`
terrio.convert("countries.shp", "europe.gpkg", where="CONTINENT = 'Europe'", select=["NAME"])
terrio.translate("landsat.tif", "sub.tif", srcwin=(10, 20, 100, 80), bands=[3, 1], ot="Float32")
terrio.warp("dem.tif", "dem_4326.tif", t_srs="EPSG:4326", resampling="bilinear")
terrio.mosaic(["a.tif", "b.tif"], "m.vrt")           # or in-memory Rasters -> Raster
terrio.rasterize("counties.gpkg", "pop.tif", attribute="POP", tr=(0.01, 0.01), ot="Int32")
terrio.polygonize("landcover.tif", "lc.gpkg", connectedness=8)
xs, ys = terrio.transform_points(lon, lat, "EPSG:4326", "EPSG:32611")

Operations take the CLI options as keyword arguments, accept paths or in-memory objects (Raster, Layer, VectorDataset, GeoJSON, anything with __geo_interface__), return the result and also write it when a destination is given. The GIL is released during I/O and processing.

Errors: terrio.TerrioError base; TerrioIOError(OSError), NotFoundError(FileNotFoundError), and InvalidArgumentError, CRSError, UnsupportedError, InvalidDataError (all ValueError).

npm (terrio, name available)

import init, { open, fromGeoJSON, rasterFromArray, transformPoints, describeCrs, drivers } from "terrio";
await init();
const dem = open(bytes, "dem.tif");          // GeoTIFFs are decoded window by window
dem.info(); dem.readBand(1, [0, 0, 256, 256]); // Float32Array, Uint8Array...
dem.toBytes("dem_cog.tif", { format: "COG", compress: "DEFLATE" });
open(geojsonBytes, "roads.geojson").toBytes("roads.fgb", { tSrs: "EPSG:3857", where: "lanes > 2" });
transformPoints([-122.4], [37.8], "EPSG:4326", "EPSG:32610");

Built with wasm-pack for web (the npm package, 1.1 MB packed) and nodejs (tests). Nothing is published.

Core changes (kept small)

  • New crates/terrio/src/memory.rs: open_bytes, open_raster_bytes, open_raster_lazy_bytes, open_vector_bytes, write_raster_bytes, write_vector_bytes. Native builds go through a temporary directory and the file drivers, so every format behaves exactly as from files (multi-file outputs such as shapefiles come back as a zip). WebAssembly builds use in-memory codecs: read GeoTIFF/COG, ASCII grid, GeoJSON, TopoJSON, FlatGeobuf, KML, KMZ, GML, GPX and zip archives of these; write GeoTIFF/COG (with the merged gtiff_write encoder, lossless compressions), ASCII grid and the same vector formats. The API is generic (bytes + file name), so the vector/raster drivers can add byte readers behind it later.
  • cog.rs: LazyRaster::from_tiff_bytes, LazyRaster::dataset(), impl From<RasterDataset> for LazyRaster, and an in-memory Source.
  • crs.rs: SpatialRef::to_crs_info, from_layer and apply_to_layer made public; dataset.rs: fix_layer is pub(crate); vfs.rs: MAIN_DATASET_EXTENSIONS available in wasm.
  • Workspace members python (terrio-py, publish = false, lib test = false since the extension links to Python only when loaded) and js (terrio-js). Both build and lint in the plain workspace.

CI

  • python (ubuntu/macos/windows): maturin-action wheel build, install, pytest; wheels uploaded as artifacts.
  • real data vs GDAL: builds the wheel in the GDAL environment and runs the Python suite with TERRIO_TEST_DATA, comparing arrays with osgeo.gdal.
  • wasm: builds the npm package (nodejs and web targets), runs node --test js/tests/, uploads the package.
  • New release.yml: wheels (manylinux x86_64/aarch64, musllinux, macOS x86_64/arm64, Windows) + sdist on v* tags, published with PyPI trusted publishing (needs a pypi environment and a trusted publisher on the PyPI project; not triggered).
  • pre-commit: ruff check and format for python/.

Test results (local)

  • cargo fmt, cargo clippy --workspace --all-targets -D warnings (also for wasm32-unknown-unknown on terrio and terrio-js), cargo test --workspace (with TERRIO_TEST_DATA): pass. uvx pre-commit run --all-files: pass.
  • pytest without data: 32 passed (synthetic: every dtype through from_array/read, windows, writes, bytes, vector formats, convert/translate/warp/mosaic/rasterize/polygonize, errors, geopandas round trip).
  • pytest with real data and GDAL 3.12 (TERRIO_TEST_REMOTE=1): 81 passed, 3 xfailed. Arrays are identical to gdal.Band.ReadAsArray (shape, dtype, values) for 23 rasters (GeoTIFF/COG, Landsat, SRTM, NLCD, ECOSTRESS, OPERA, USGS 3DEP, ASCII grid, HFA, ENVI, JP2, BIL, ERS, Surfer, RST, SAGA, NetCDF, Zarr v3); lazy random windows and every overview match GDAL on 11 GeoTIFFs; a remote USGS COG window and overview match GDAL's /vsicurl/; open_bytes matches; rasters written by terrio read identically in GDAL; translate matches gdal.Translate exactly; warp to EPSG:3857 has GDAL's size and geotransform and >99.9% identical pixels; rasterize matches gdal.Rasterize; vector feature counts, fields, extents and geometry areas/lengths match OGR for GeoPackage, GeoJSON, GeoParquet, zipped shapefile; transform_points matches osr to 1 mm.
  • Node (wasm, nodejs target): 16 passed; band min/max/mean match GDAL's statistics (.aux.xml) for srtm_sub, dem, cog, landsat and nlcd GeoTIFFs; GeoJSON/KML/GML/GPX real files read from bytes.

Known gaps

  • xfailed until the vector-drivers work lands: the format library's FlatGeobuf reader fails on GDAL-written countries.fgb/UScounties.fgb and overflows on large files in 32-bit wasm; its GeoJSON reader mis-decodes non-ASCII text (Côte d'Ivoire).
  • WebAssembly cannot yet read Shapefile, GeoParquet or GeoPackage from memory (native builds can): those drivers read from paths; once the new drivers expose byte readers, memory::codec can route to them.
  • Found while testing (core, not changed here): vectors written in EPSG:3857 are re-identified as EPSG:3395 on reading.
  • Not done: Arrow export of layers (to_arrow), .pyi type stubs, npm publishing workflow. The PyPI project already has a 0.0.1 placeholder, so the first real release needs a version bump.

Summary by CodeRabbit

  • New Features
    • Added Python and JavaScript/WebAssembly packages for working with raster and vector data, including reading, writing, conversion, coordinate transformations, and geospatial processing.
    • Added in-memory dataset support, including opening and exporting data as bytes and lazy reads for GeoTIFF files.
    • Python bindings support NumPy arrays and optional GeoPandas conversions.
    • Added automated builds and package releases for Python wheels and JavaScript artifacts.
  • Documentation
    • Added setup, usage, supported-format, and testing guides for the Python and JavaScript packages.

Python (python/, the terrio-py crate, published as terrio on PyPI):
PyO3 and NumPy, abi3 wheels for Python 3.10+. terrio.open, open_raster
(lazy window and overview reads of local and remote GeoTIFFs),
open_vector, open_bytes, info, list_layers, drivers; Raster with
read() into native-dtype arrays, from_array, write and to_bytes;
VectorDataset and Layer with to_geojson, to_wkb, columns, to_geopandas
and to_crs; convert, translate, warp, mosaic, rasterize, polygonize,
transform_points and write_vector/write_raster with the CLI options as
keyword arguments. Errors raise terrio.TerrioError subclasses that are
also OSError or ValueError. pytest suite with synthetic tests and
real-data tests comparing arrays with osgeo.gdal.

npm (js/, the terrio-js crate): wasm-bindgen bindings opening datasets
from bytes, reading bands as typed arrays, layers as GeoJSON, writing
to bytes, and transforming coordinates. Tested in Node.

terrio::memory opens datasets from bytes and writes them to bytes:
through a temporary directory and the file drivers in native builds,
with in-memory codecs (GeoTIFF/COG, ASCII grid, GeoJSON, FlatGeobuf,
KML, KMZ, GML, GPX, TopoJSON, zip archives) in WebAssembly.
LazyRaster reads GeoTIFFs held in memory and wraps rasters in memory.

CI builds and tests wheels on Linux, macOS and Windows, runs the Python
tests against GDAL on real data, and builds and tests the npm package.
A release workflow publishes wheels to PyPI with trusted publishing.
@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

opengeos is on CodeRabbit Free, which includes PR summaries. Ask your admin to upgrade for code reviews.

  • Ask an admin to upgrade

Open in CodeRabbit

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Free
  • Run ID: 81d8fe6a-dd81-479a-bef6-a10eea85cc22
📥 Commits

Reviewing files that changed from the base of the PR and between 2076927 and 2b8bf9e.

⛔ Files ignored due to path filters: 1
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing: 30
  • .github/workflows/ci.yml
  • .github/workflows/release.yml
  • .gitignore
  • .pre-commit-config.yaml
  • Cargo.toml
  • README.md
  • ROADMAP.md
  • crates/terrio/src/cog.rs
  • crates/terrio/src/crs.rs
  • crates/terrio/src/dataset.rs
  • crates/terrio/src/lib.rs
  • crates/terrio/src/memory.rs
  • crates/terrio/src/vfs.rs
  • js/Cargo.toml
  • js/README.md
  • js/src/lib.rs
  • js/tests/node.test.mjs
  • python/Cargo.toml
  • python/README.md
  • python/pyproject.toml
  • python/python/terrio/__init__.py
  • python/python/terrio/errors.py
  • python/src/lib.rs
  • python/src/ops.rs
  • python/src/raster.rs
  • python/src/terrio/__init__.py
  • python/src/vector.rs
  • python/tests/conftest.py
  • python/tests/test_real_data.py
  • python/tests/test_synthetic.py
💤 Files with no reviewable changes: 1
  • python/src/terrio/init.py

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

📝 Walkthrough

The PR adds byte-based dataset I/O to the Rust crate, Python and WebAssembly bindings, and CI and release workflows for the language packages. It also adds usage documentation and tests for the new APIs.

Changes: Byte-based dataset I/O

Layer / File(s) Summary
Memory-backed lazy raster sources
crates/terrio/src/cog.rs, crates/terrio/src/crs.rs, crates/terrio/src/dataset.rs, crates/terrio/src/vfs.rs, crates/terrio/src/lib.rs
LazyRaster can wrap TIFF bytes or an existing dataset. Its source reads and seeks through an in-memory cursor. The crate exposes the memory module and supporting CRS and dataset helpers.
Byte-based dataset opening
crates/terrio/src/memory.rs, README.md, ROADMAP.md
The memory API adds byte-based open functions. Native builds use temporary files, while WebAssembly uses in-memory codecs for supported raster and vector inputs.
Byte-based dataset writing and tests
crates/terrio/src/memory.rs, ROADMAP.md
Raster and vector byte writers select a driver from options or the filename extension. Native multi-file outputs are zipped. Tests cover raster and vector codec round trips and native outputs.

Python bindings

Layer / File(s) Summary
Python package and error interface
python/Cargo.toml, python/pyproject.toml, python/python/terrio/*, python/src/lib.rs, python/src/terrio/__init__.py, Cargo.toml, .gitignore, .pre-commit-config.yaml
The project adds a Maturin-built extension, package exports, and a Python exception hierarchy. The extension maps Terrio errors to Python exceptions.
Python raster and vector objects
python/src/raster.rs, python/src/vector.rs, python/README.md
The bindings add Raster, Layer, and VectorDataset interfaces for metadata, array and feature access, conversions, reprojection, and writing.
Python dataset operations
python/src/ops.rs, python/README.md, README.md
The bindings expose dataset opening and writing, conversion, rasterization, polygonization, coordinate transformation, translation, warping, and mosaicking.
Python tests and package workflows
python/tests/*, .github/workflows/ci.yml, .github/workflows/release.yml, python/README.md, README.md
Synthetic and real-data tests cover the Python APIs, with selected comparisons against GDAL and OGR. CI builds and tests wheels across Ubuntu, macOS, and Windows. The release workflow builds wheels and a source distribution, then publishes on version tags.

JavaScript WebAssembly bindings

Layer / File(s) Summary
WebAssembly dataset API
js/src/lib.rs
The exported API opens byte inputs, creates raster and vector datasets, reads metadata and raster bands, writes bytes, and provides coordinate and CRS utilities.
WebAssembly packaging and validation
js/Cargo.toml, js/README.md, js/tests/node.test.mjs, .github/workflows/ci.yml, README.md
The package documentation describes builds and supported in-memory formats. Node.js tests cover raster and vector round trips, errors, and optional real data. CI builds Node.js and web targets and checks the npm package.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller as JavaScript caller
  participant Dataset as WebAssembly Dataset
  participant LazyRaster
  Caller->>Dataset: open(TIFF bytes)
  Dataset->>LazyRaster: open TIFF bytes lazily
  Caller->>Dataset: readBand(band, window)
  Dataset->>LazyRaster: read selected band and window
  LazyRaster-->>Dataset: raster values
  Dataset-->>Caller: typed array
Loading
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

A rabbit checks the byte stream’s course,
Then hops through fields of data, source to source.
TIFF leaves open lazily in the breeze,
Raster bands return with woodland ease.
Wheels roll out; tests bloom in rows,
The rabbit nods, then homeward goes.

Comment @coderabbitai help to get the list of available commands.

@giswqs
giswqs merged commit 993aac3 into main Oct 14, 2026
9 checks passed
@giswqs
giswqs deleted the bindings branch October 14, 2026 14:34
giswqs added a commit that referenced this pull request Nov 10, 2026
- Skip a pull request only when gh says the number names none; stop
  with an error when gh is missing, unauthenticated or offline, so a
  failure does not print an empty draft.
- Check each item of a list on its own, so a first item that only
  references an issue ("Closes #12") is skipped.
- Stop with a message asking for --since or a full clone with tags when
  no v* tag precedes --until, or when git cannot list the range; say in
  the docs that the script needs full history and tags.
- Match the whole release title, "Release X.Y.Z", in the script and
  the workflow.
giswqs added a commit that referenced this pull request Nov 10, 2026
* ci: write the changelog in the release pull request only

Every feature pull request added its entry at the top of the changelog's
Unreleased section, so each merge left the other open pull requests in
conflict on the same lines.

Feature pull requests now leave CHANGELOG.md alone and open their
description with a changelog-style paragraph. The release pull request
drafts its section from those with scripts/draft_changelog.py, which
reads the pull requests merged since the latest tag. A Changelog
workflow fails a pull request that edits the file unless its title
starts with Release. AGENTS.md and docs/contributing.md document the
rule.

* Address review feedback

- Remove fenced code blocks before splitting a description into
  paragraphs, so a block with a blank line is not split into an entry.
- Skip only wholly bold paragraphs, keeping an opening like
  "**Breaking:** ...".
- Remove heading lines before splitting, so prose right below a
  heading is kept.
- Match release pull requests as "Release X.Y.Z" in the script and the
  workflow, not any title starting with "Release ".
- Name the workflow's job "Changelog", the check name the docs use.
- Warn and skip a number gh cannot read instead of aborting the draft.
- Default --since to the last tag before --until, not before HEAD.
- Document merging the drafted entries into the existing Unreleased
  ones at release.

* Address Claude review feedback

- Skip a pull request only when gh says the number names none; stop
  with an error when gh is missing, unauthenticated or offline, so a
  failure does not print an empty draft.
- Check each item of a list on its own, so a first item that only
  references an issue ("Closes #12") is skipped.
- Stop with a message asking for --since or a full clone with tags when
  no v* tag precedes --until, or when git cannot list the range; say in
  the docs that the script needs full history and tags.
- Match the whole release title, "Release X.Y.Z", in the script and
  the workflow.

* Address Claude review feedback

- Remove only ATX headings ("#" to "######" and a space), so a line
  such as "#123 fixes the crash" stays in the description.
- Split a paragraph at its list items wherever they start, so an intro
  line directly above a list is separated from the items, and skip a
  lead-in that ends with a colon.

* Address Claude review feedback

- Match release titles with [0-9] and fullmatch, exactly as the
  Changelog workflow's ^Release [0-9]+.[0-9]+.[0-9]+$ does.
- Reword the module docstring's range description, say that only
  numbers naming no pull request are skipped, and wrap it and the
  --since option to 100 columns.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant