streetframe 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. streetframe-0.0.1/.gitignore +8 -0
  2. streetframe-0.0.1/PKG-INFO +51 -0
  3. streetframe-0.0.1/README.pypi.md +30 -0
  4. streetframe-0.0.1/pyproject.toml +33 -0
  5. streetframe-0.0.1/src/streetframe/__init__.py +10 -0
  6. streetframe-0.0.1/src/streetframe/bridge/__init__.py +0 -0
  7. streetframe-0.0.1/src/streetframe/bridge/projectsidewalk.py +86 -0
  8. streetframe-0.0.1/src/streetframe/core/__init__.py +4 -0
  9. streetframe-0.0.1/src/streetframe/core/collection.py +210 -0
  10. streetframe-0.0.1/src/streetframe/core/conventions.py +76 -0
  11. streetframe-0.0.1/src/streetframe/core/schema.py +80 -0
  12. streetframe-0.0.1/src/streetframe/coverage.py +125 -0
  13. streetframe-0.0.1/src/streetframe/geometry/__init__.py +5 -0
  14. streetframe-0.0.1/src/streetframe/geometry/align.py +73 -0
  15. streetframe-0.0.1/src/streetframe/geometry/camera.py +302 -0
  16. streetframe-0.0.1/src/streetframe/geometry/cyclic.py +74 -0
  17. streetframe-0.0.1/src/streetframe/geometry/equirect.py +132 -0
  18. streetframe-0.0.1/src/streetframe/geometry/ground.py +73 -0
  19. streetframe-0.0.1/src/streetframe/geometry/register.py +260 -0
  20. streetframe-0.0.1/src/streetframe/geometry/resample.py +83 -0
  21. streetframe-0.0.1/src/streetframe/geometry/rotation.py +99 -0
  22. streetframe-0.0.1/src/streetframe/inspect/__init__.py +7 -0
  23. streetframe-0.0.1/src/streetframe/inspect/checks.py +143 -0
  24. streetframe-0.0.1/src/streetframe/inspect/corrections.py +50 -0
  25. streetframe-0.0.1/src/streetframe/inspect/html.py +199 -0
  26. streetframe-0.0.1/src/streetframe/inspect/overlay.py +67 -0
  27. streetframe-0.0.1/src/streetframe/inspect/plot.py +93 -0
  28. streetframe-0.0.1/src/streetframe/models.py +121 -0
  29. streetframe-0.0.1/src/streetframe/rank.py +55 -0
  30. streetframe-0.0.1/src/streetframe/reconstruct/__init__.py +5 -0
  31. streetframe-0.0.1/src/streetframe/reconstruct/colmap.py +280 -0
  32. streetframe-0.0.1/src/streetframe/results.py +114 -0
  33. streetframe-0.0.1/src/streetframe/sources/__init__.py +7 -0
  34. streetframe-0.0.1/src/streetframe/sources/base.py +42 -0
  35. streetframe-0.0.1/src/streetframe/sources/http.py +39 -0
  36. streetframe-0.0.1/src/streetframe/sources/local.py +253 -0
  37. streetframe-0.0.1/src/streetframe/sources/mapillary.py +157 -0
  38. streetframe-0.0.1/src/streetframe/sources/panoramax.py +159 -0
  39. streetframe-0.0.1/src/streetframe/sources/projectsidewalk.py +102 -0
  40. streetframe-0.0.1/src/streetframe/store.py +151 -0
  41. streetframe-0.0.1/src/streetframe/transfer.py +82 -0
  42. streetframe-0.0.1/tests/conftest.py +48 -0
  43. streetframe-0.0.1/tests/data/panoramax_search.json +911 -0
  44. streetframe-0.0.1/tests/data/projectsidewalk_labels.json +272 -0
  45. streetframe-0.0.1/tests/data/projectsidewalk_streets.json +177 -0
  46. streetframe-0.0.1/tests/test_agrees_with_rampnet.py +107 -0
  47. streetframe-0.0.1/tests/test_camera.py +111 -0
  48. streetframe-0.0.1/tests/test_core.py +66 -0
  49. streetframe-0.0.1/tests/test_geometry.py +95 -0
  50. streetframe-0.0.1/tests/test_local_and_checks.py +187 -0
  51. streetframe-0.0.1/tests/test_models_bridge_more.py +257 -0
  52. streetframe-0.0.1/tests/test_providers_and_results.py +202 -0
  53. streetframe-0.0.1/tests/test_reconstruct_resample.py +133 -0
  54. streetframe-0.0.1/tests/test_register_align.py +90 -0
@@ -0,0 +1,8 @@
1
+ .DS_Store
2
+ __pycache__/
3
+ *.egg-info/
4
+ .venv/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ demo_output/
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.5
2
+ Name: streetframe
3
+ Version: 0.0.1
4
+ Summary: Provider-neutral street-level imagery as GeoDataFrames (prototype; schema provisional)
5
+ Requires-Python: >=3.10
6
+ Requires-Dist: geopandas>=1.0
7
+ Requires-Dist: numpy>=1.24
8
+ Requires-Dist: pandas>=2.0
9
+ Requires-Dist: pyarrow>=14
10
+ Requires-Dist: pyproj>=3.5
11
+ Requires-Dist: shapely>=2.0
12
+ Provides-Extra: dev
13
+ Requires-Dist: matplotlib>=3.7; extra == 'dev'
14
+ Requires-Dist: pillow>=10; extra == 'dev'
15
+ Requires-Dist: pytest>=8; extra == 'dev'
16
+ Provides-Extra: images
17
+ Requires-Dist: pillow>=10; extra == 'images'
18
+ Provides-Extra: plot
19
+ Requires-Dist: matplotlib>=3.7; extra == 'plot'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # StreetFrame
23
+
24
+ A prototype of a provider-neutral Python library for street-level imagery, part of OSCUR. A street-level image is a frame with a position, an orientation, a time, a source and a license, and a collection of frames is a GeoDataFrame.
25
+
26
+ This is an early prototype: the frame record is provisional and there is no license yet.
27
+
28
+ ## Install
29
+
30
+ ```
31
+ pip install streetframe # add [images] or [plot] for Pillow or matplotlib
32
+ ```
33
+
34
+ The source repository has a demo that takes a few blocks of Seattle: open panoramas from Panoramax, Project Sidewalk's labels for the same streets, pose checks, coverage per street, and the labels (made on Google Street View) projected into the open panoramas.
35
+
36
+ ## What is here
37
+
38
+ | Module | What it does |
39
+ | --- | --- |
40
+ | `core` | The frame record, conventions, `FrameCollection`, GeoParquet |
41
+ | `sources` | A local folder, Panoramax, Mapillary (not yet run against the live service), and Project Sidewalk's labels and streets |
42
+ | `geometry` | Camera models, panoramas and views, ground geolocation, seam handling, pose from control points, alignment, resampling |
43
+ | `inspect` | Pose checks, a map with heading wedges, a frame with streets drawn from its pose, the inspector as one HTML file, heading corrections |
44
+ | `models`, `bridge` | A first model interface with one model that needs no deep learning; request bodies for Project Sidewalk's AI endpoint (built, never sent) |
45
+ | `results`, `transfer` | Observations with provenance; projecting them into other frames |
46
+ | `rank`, `coverage`, `store` | Choosing a frame for a place; coverage per street or cell and indicators per frame; a dataset folder with a manifest |
47
+ | `reconstruct` | Reading and writing COLMAP text models, georeferencing, poses written back to frames |
48
+
49
+ The core depends on numpy, pandas, geopandas, shapely, pyproj and pyarrow. Pillow and matplotlib are optional. Nothing depends on OpenCV, COLMAP or PyTorch.
50
+
51
+ Parts of the geometry, the frame ranking and the label handling are reimplemented from RampNet and Project Sidewalk (University of Washington); each module says where its method came from.
@@ -0,0 +1,30 @@
1
+ # StreetFrame
2
+
3
+ A prototype of a provider-neutral Python library for street-level imagery, part of OSCUR. A street-level image is a frame with a position, an orientation, a time, a source and a license, and a collection of frames is a GeoDataFrame.
4
+
5
+ This is an early prototype: the frame record is provisional and there is no license yet.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ pip install streetframe # add [images] or [plot] for Pillow or matplotlib
11
+ ```
12
+
13
+ The source repository has a demo that takes a few blocks of Seattle: open panoramas from Panoramax, Project Sidewalk's labels for the same streets, pose checks, coverage per street, and the labels (made on Google Street View) projected into the open panoramas.
14
+
15
+ ## What is here
16
+
17
+ | Module | What it does |
18
+ | --- | --- |
19
+ | `core` | The frame record, conventions, `FrameCollection`, GeoParquet |
20
+ | `sources` | A local folder, Panoramax, Mapillary (not yet run against the live service), and Project Sidewalk's labels and streets |
21
+ | `geometry` | Camera models, panoramas and views, ground geolocation, seam handling, pose from control points, alignment, resampling |
22
+ | `inspect` | Pose checks, a map with heading wedges, a frame with streets drawn from its pose, the inspector as one HTML file, heading corrections |
23
+ | `models`, `bridge` | A first model interface with one model that needs no deep learning; request bodies for Project Sidewalk's AI endpoint (built, never sent) |
24
+ | `results`, `transfer` | Observations with provenance; projecting them into other frames |
25
+ | `rank`, `coverage`, `store` | Choosing a frame for a place; coverage per street or cell and indicators per frame; a dataset folder with a manifest |
26
+ | `reconstruct` | Reading and writing COLMAP text models, georeferencing, poses written back to frames |
27
+
28
+ The core depends on numpy, pandas, geopandas, shapely, pyproj and pyarrow. Pillow and matplotlib are optional. Nothing depends on OpenCV, COLMAP or PyTorch.
29
+
30
+ Parts of the geometry, the frame ranking and the label handling are reimplemented from RampNet and Project Sidewalk (University of Washington); each module says where its method came from.
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "streetframe"
7
+ version = "0.0.1"
8
+ description = "Provider-neutral street-level imagery as GeoDataFrames (prototype; schema provisional)"
9
+ readme = "README.pypi.md"
10
+ requires-python = ">=3.10"
11
+ # License undecided (DESIGN.md section 15); no license is granted yet.
12
+ dependencies = [
13
+ "numpy>=1.24",
14
+ "pandas>=2.0",
15
+ "geopandas>=1.0",
16
+ "shapely>=2.0",
17
+ "pyproj>=3.5",
18
+ "pyarrow>=14",
19
+ ]
20
+
21
+ [project.optional-dependencies]
22
+ images = ["pillow>=10"]
23
+ plot = ["matplotlib>=3.7"]
24
+ dev = ["pytest>=8", "pillow>=10", "matplotlib>=3.7"]
25
+
26
+ [tool.hatch.build.targets.wheel]
27
+ packages = ["src/streetframe"]
28
+
29
+ [tool.hatch.build.targets.sdist]
30
+ include = ["src/streetframe", "tests", "README.pypi.md", "pyproject.toml"]
31
+
32
+ [tool.pytest.ini_options]
33
+ testpaths = ["tests"]
@@ -0,0 +1,10 @@
1
+ """StreetFrame: provider-neutral street-level imagery as GeoDataFrames.
2
+
3
+ PROTOTYPE. The frame record is provisional (see DESIGN.md and PLAN.md).
4
+ """
5
+ from .core import SCHEMA_VERSION, FrameCollection, SchemaError, make_frame_id
6
+ from .sources import LocalSource, SourceError
7
+
8
+ __version__ = "0.0.1"
9
+ __all__ = ["FrameCollection", "SchemaError", "make_frame_id", "SCHEMA_VERSION",
10
+ "LocalSource", "SourceError", "__version__"]
File without changes
@@ -0,0 +1,86 @@
1
+ """Model detections in the form Project Sidewalk's AI endpoint accepts
2
+ (``POST /ai/submitLabelsOnPano``; DESIGN.md section 14).
3
+
4
+ This module only builds the request body. It does not send anything:
5
+ submitting writes labels into a live deployment and needs its maintainers'
6
+ agreement and credentials.
7
+
8
+ The shape was read from ``AiLabelsSubmission`` and ``PanoSubmission`` in
9
+ Project Sidewalk's ``app/formats/json/ExploreFormats.scala`` (snake-case
10
+ JSON) on 6 December 2026 and is to be confirmed with the maintainers.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from typing import Any
16
+
17
+ import pandas as pd
18
+
19
+ from ..core.collection import FrameCollection
20
+ from ..results import Observations
21
+
22
+ #: Project Sidewalk's names for imagery sources that this library also knows.
23
+ PANO_SOURCES = {"gsv": "gsv", "mapillary": "mapillary", "panoramax": "panoramax", "infra3d": "infra3d"}
24
+
25
+
26
+ class PayloadError(ValueError):
27
+ pass
28
+
29
+
30
+ def submission_payloads(observations: Observations, frames: FrameCollection, *, api_version: str,
31
+ overwrite: bool = False) -> list[dict[str, Any]]:
32
+ """One request body per (panorama, label type) for a model's detections.
33
+
34
+ The observations must come from a model (``producer_kind == "model"``),
35
+ carry ``x_norm``, ``y_norm`` and ``confidence``, and their provenance must
36
+ name the model (``producer``) and its training date
37
+ (``model_training_date``). Every frame must be an equirectangular
38
+ panorama from a source Project Sidewalk knows, with size, position and heading.
39
+ """
40
+ prov = observations.provenance
41
+ if not prov.get("model_training_date"):
42
+ raise PayloadError("provenance needs model_training_date")
43
+ o = observations.gdf
44
+ if (o["producer_kind"] != "model").any():
45
+ raise PayloadError("only model detections are submitted through this endpoint")
46
+ for col in ("x_norm", "y_norm", "confidence"):
47
+ if o[col].isna().any():
48
+ raise PayloadError(f"every detection needs {col}")
49
+ by_id = frames.gdf.set_index("frame_id")
50
+ missing = sorted(set(o["frame_id"]) - set(by_id.index))
51
+ if missing:
52
+ raise PayloadError(f"frames not in the collection: {missing[:3]}")
53
+ out = []
54
+ for (frame_id, label), grp in o.groupby(["frame_id", "label"], sort=True):
55
+ f = by_id.loc[frame_id]
56
+ if f["source"] not in PANO_SOURCES:
57
+ raise PayloadError(f"{frame_id}: Project Sidewalk has no imagery source {f['source']!r}")
58
+ if f["projection"] != "equirectangular":
59
+ raise PayloadError(f"{frame_id}: only panoramas can be submitted")
60
+ need = {k: f[k] for k in ("width_px", "height_px", "heading_deg")}
61
+ if any(pd.isna(v) for v in need.values()):
62
+ raise PayloadError(f"{frame_id}: needs width, height and heading")
63
+ w, h = int(f["width_px"]), int(f["height_px"])
64
+ meta = None if pd.isna(f["source_metadata"]) else json.loads(f["source_metadata"])
65
+ out.append({
66
+ "label_type": label, "model_id": f"{prov['producer']}@{prov['producer_version']}",
67
+ "model_training_date": prov["model_training_date"], "api_version": api_version,
68
+ "overwrite": overwrite,
69
+ "pano": {
70
+ "pano_id": f["native_id"], "source": PANO_SOURCES[f["source"]],
71
+ "capture_date": "" if pd.isna(f["captured_at"]) else f["captured_at"].strftime("%Y-%m"),
72
+ "width": w, "height": h, "tile_width": None, "tile_height": None,
73
+ "lat": float(f.geometry.y), "lng": float(f.geometry.x),
74
+ "camera_heading": float(f["heading_deg"]),
75
+ "camera_pitch": None if pd.isna(f["pitch_deg"]) else float(f["pitch_deg"]),
76
+ "camera_roll": None if pd.isna(f["roll_deg"]) else float(f["roll_deg"]),
77
+ "links": [], "history": [], "address": None,
78
+ "copyright": None if pd.isna(f["copyright"]) else f["copyright"],
79
+ "license": None if pd.isna(f["license"]) else f["license"],
80
+ "source_metadata": meta if isinstance(meta, dict) else None,
81
+ },
82
+ "labels": [{"pano_x": int(round(x * w)) % w, "pano_y": min(int(round(y * h)), h - 1),
83
+ "confidence": float(c)}
84
+ for x, y, c in zip(grp["x_norm"], grp["y_norm"], grp["confidence"])],
85
+ })
86
+ return out
@@ -0,0 +1,4 @@
1
+ from .collection import FrameCollection, SchemaError, make_frame_id, validate
2
+ from .schema import SCHEMA_VERSION
3
+
4
+ __all__ = ["FrameCollection", "SchemaError", "make_frame_id", "validate", "SCHEMA_VERSION"]
@@ -0,0 +1,210 @@
1
+ """FrameCollection: a validated GeoDataFrame of frames (DESIGN.md section 6.3)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from typing import Any, Iterable, Mapping
8
+
9
+ import geopandas as gpd
10
+ import numpy as np
11
+ import pandas as pd
12
+ from shapely.geometry import Point
13
+
14
+ from . import schema
15
+ from .conventions import CRS
16
+
17
+
18
+ class SchemaError(ValueError):
19
+ """A table of frames does not follow the frame record."""
20
+
21
+
22
+ def make_frame_id(source: str, native_id: str) -> str:
23
+ """The library-wide identifier of a frame.
24
+
25
+ >>> make_frame_id("mapillary", "123")
26
+ 'mapillary:123'
27
+ """
28
+ if ":" in source:
29
+ raise ValueError(f"source name may not contain ':': {source!r}")
30
+ return f"{source}:{native_id}"
31
+
32
+
33
+ def _to_utc(values: pd.Series) -> pd.Series:
34
+ """Timestamps in UTC. Providers mix formats (with and without fractions of a second)."""
35
+ if pd.api.types.is_datetime64_any_dtype(values):
36
+ return pd.to_datetime(values, utc=True)
37
+ return pd.to_datetime(values, utc=True, format="mixed")
38
+
39
+
40
+ def _json_text(v):
41
+ if isinstance(v, str):
42
+ return v
43
+ if v is None or v is pd.NA or (isinstance(v, float) and v != v):
44
+ return pd.NA
45
+ return json.dumps(v, sort_keys=True, default=str)
46
+
47
+
48
+ def _coerce(gdf: gpd.GeoDataFrame) -> gpd.GeoDataFrame:
49
+ """Add missing optional columns and give every column its schema type."""
50
+ out = gdf.copy()
51
+ for f in schema.FIELDS:
52
+ if f.name == "geometry":
53
+ continue
54
+ if f.name not in out.columns:
55
+ out[f.name] = pd.NA
56
+ if f.kind == "timestamp":
57
+ out[f.name] = _to_utc(out[f.name])
58
+ elif f.kind == "json":
59
+ out[f.name] = out[f.name].map(_json_text).astype("string")
60
+ else:
61
+ out[f.name] = out[f.name].astype(schema.PANDAS_DTYPES[f.kind])
62
+ extra = [c for c in out.columns if c not in schema.FIELD_NAMES]
63
+ cols = [n for n in schema.FIELD_NAMES if n != "geometry"] + extra + ["geometry"]
64
+ return out[cols]
65
+
66
+
67
+ def validate(gdf: gpd.GeoDataFrame) -> None:
68
+ """Raise :class:`SchemaError` listing every way ``gdf`` breaks the record."""
69
+ problems: list[str] = []
70
+ missing = [n for n in schema.REQUIRED if n not in gdf.columns]
71
+ if missing:
72
+ raise SchemaError(f"missing required columns: {missing}")
73
+ if gdf.crs is None or gdf.crs.to_string() != CRS:
74
+ problems.append(f"crs must be {CRS}, got {gdf.crs}")
75
+ for name in schema.REQUIRED:
76
+ if name != "geometry" and gdf[name].isna().any():
77
+ problems.append(f"{name}: {int(gdf[name].isna().sum())} missing values")
78
+ if gdf.geometry.isna().any() or gdf.geometry.is_empty.any():
79
+ problems.append("geometry: missing or empty positions")
80
+ elif not (gdf.geometry.geom_type == "Point").all():
81
+ problems.append("geometry: every position must be a Point")
82
+ elif not (np.isfinite(gdf.geometry.x) & np.isfinite(gdf.geometry.y)).all():
83
+ problems.append("geometry: positions with coordinates that are not numbers")
84
+ else:
85
+ if ((gdf.geometry.x < -180) | (gdf.geometry.x > 180)).any():
86
+ problems.append("geometry: longitude outside [-180, 180]")
87
+ if ((gdf.geometry.y < -90) | (gdf.geometry.y > 90)).any():
88
+ problems.append("geometry: latitude outside [-90, 90]")
89
+ if gdf["frame_id"].duplicated().any():
90
+ problems.append(f"frame_id: {int(gdf['frame_id'].duplicated().sum())} duplicates")
91
+ expected = gdf["source"].astype(str) + ":" + gdf["native_id"].astype(str)
92
+ if not (gdf["frame_id"].astype(str) == expected).all():
93
+ problems.append("frame_id must equal source + ':' + native_id")
94
+ for f in schema.FIELDS:
95
+ if f.values and f.name in gdf.columns:
96
+ bad = set(gdf[f.name].dropna().unique()) - set(f.values)
97
+ if bad:
98
+ problems.append(f"{f.name}: values {sorted(bad)} not in {list(f.values)}")
99
+ unknown = set(gdf["schema_version"].dropna()) - {schema.SCHEMA_VERSION}
100
+ if unknown:
101
+ problems.append(f"schema_version {sorted(unknown)} is not one this version reads ({schema.SCHEMA_VERSION})")
102
+ for name in ("intrinsics", "source_metadata"):
103
+ if name in gdf.columns:
104
+ for fid, text in zip(gdf["frame_id"], gdf[name]):
105
+ if isinstance(text, str):
106
+ try:
107
+ json.loads(text)
108
+ except ValueError:
109
+ problems.append(f"{name} of {fid} is not JSON")
110
+ break
111
+ if "heading_deg" in gdf.columns:
112
+ h = gdf["heading_deg"].dropna().astype(float)
113
+ if ((h < 0) | (h >= 360)).any():
114
+ problems.append("heading_deg outside [0, 360)")
115
+ if "pitch_deg" in gdf.columns:
116
+ p = gdf["pitch_deg"].dropna().astype(float)
117
+ if (p.abs() > 90).any():
118
+ problems.append("pitch_deg outside [-90, 90]")
119
+ if "roll_deg" in gdf.columns:
120
+ r = gdf["roll_deg"].dropna().astype(float)
121
+ if ((r < -180) | (r >= 180)).any():
122
+ problems.append("roll_deg outside [-180, 180)")
123
+ if problems:
124
+ raise SchemaError("; ".join(problems))
125
+
126
+
127
+ class FrameCollection:
128
+ """A thin, validated wrapper around a GeoDataFrame of frames.
129
+
130
+ ``.gdf`` is the plain GeoDataFrame, so any GeoPandas operation works without
131
+ this class.
132
+ """
133
+
134
+ def __init__(self, gdf: gpd.GeoDataFrame):
135
+ gdf = _coerce(gdf)
136
+ validate(gdf)
137
+ self.gdf = gdf.reset_index(drop=True)
138
+
139
+ # construction -----------------------------------------------------------
140
+ @classmethod
141
+ def from_records(cls, records: Iterable[Mapping[str, Any]]) -> "FrameCollection":
142
+ """Build from dictionaries with ``lon`` and ``lat`` (or a ``geometry``).
143
+
144
+ ``frame_id``, ``retrieved_at`` and ``schema_version`` are filled in when
145
+ absent. ``pose_quality`` and ``redistribution`` default to ``unknown``.
146
+ """
147
+ now = datetime.now(timezone.utc)
148
+ rows = []
149
+ for rec in records:
150
+ r = dict(rec)
151
+ if "geometry" not in r:
152
+ r["geometry"] = Point(float(r.pop("lon")), float(r.pop("lat")))
153
+ r.setdefault("frame_id", make_frame_id(r["source"], str(r["native_id"])))
154
+ r.setdefault("pose_quality", "unknown")
155
+ r.setdefault("redistribution", "unknown")
156
+ r.setdefault("retrieved_at", now)
157
+ r.setdefault("schema_version", schema.SCHEMA_VERSION)
158
+ rows.append(r)
159
+ if not rows:
160
+ return cls.empty()
161
+ return cls(gpd.GeoDataFrame(rows, geometry="geometry", crs=CRS))
162
+
163
+ @classmethod
164
+ def empty(cls) -> "FrameCollection":
165
+ gdf = gpd.GeoDataFrame({n: [] for n in schema.FIELD_NAMES if n != "geometry"},
166
+ geometry=gpd.GeoSeries([], crs=CRS), crs=CRS)
167
+ return cls(gdf)
168
+
169
+ @classmethod
170
+ def concat(cls, collections: Iterable["FrameCollection"]) -> "FrameCollection":
171
+ """Frames from several sources in one table."""
172
+ frames = [c.gdf for c in collections if len(c)]
173
+ if not frames:
174
+ return cls.empty()
175
+ return cls(gpd.GeoDataFrame(pd.concat(frames, ignore_index=True), crs=CRS))
176
+
177
+ # storage ----------------------------------------------------------------
178
+ def to_parquet(self, path: str | Path) -> None:
179
+ """Write GeoParquet. The table is checked again first, since ``.gdf`` can be changed freely."""
180
+ gdf = _coerce(self.gdf)
181
+ validate(gdf)
182
+ gdf.to_parquet(path, index=False)
183
+
184
+ @classmethod
185
+ def read_parquet(cls, path: str | Path) -> "FrameCollection":
186
+ return cls(gpd.read_parquet(path))
187
+
188
+ # access -----------------------------------------------------------------
189
+ def __len__(self) -> int:
190
+ return len(self.gdf)
191
+
192
+ def __repr__(self) -> str:
193
+ by = self.gdf["source"].value_counts().to_dict() if len(self) else {}
194
+ return f"FrameCollection({len(self)} frames, sources={by})"
195
+
196
+ def frame(self, frame_id: str) -> pd.Series:
197
+ """One frame's record."""
198
+ hit = self.gdf[self.gdf["frame_id"] == frame_id]
199
+ if hit.empty:
200
+ raise KeyError(frame_id)
201
+ return hit.iloc[0]
202
+
203
+ def select(self, mask) -> "FrameCollection":
204
+ """A collection of the rows where ``mask`` is true."""
205
+ return FrameCollection(self.gdf[mask])
206
+
207
+ def source_metadata(self, frame_id: str) -> Any:
208
+ """The provider's original record for a frame, decoded."""
209
+ raw = self.frame(frame_id)["source_metadata"]
210
+ return None if pd.isna(raw) else json.loads(raw)
@@ -0,0 +1,76 @@
1
+ """The conventions every frame follows (DESIGN.md section 6.2).
2
+
3
+ Stated once here and enforced where a source hands frames to the library.
4
+
5
+ - Angles are in degrees. Positions are longitude and latitude in EPSG:4326.
6
+ Distances are in meters.
7
+ - ``heading_deg`` is the compass bearing, clockwise from north, of the image
8
+ center, in [0, 360).
9
+ - ``pitch_deg`` is positive when the camera looks up.
10
+ - ``roll_deg`` is positive when the camera is rotated clockwise as seen from
11
+ behind it (its right-hand side dips).
12
+ - Pixel coordinates have the origin at the top-left corner of the image, ``x``
13
+ to the right and ``y`` down, and are continuous: the center of the top-left
14
+ pixel is (0.5, 0.5), the image spans [0, width] by [0, height].
15
+ - Normalized coordinates are pixel coordinates divided by the image size, so
16
+ they span [0, 1].
17
+
18
+ Sources that use other conventions convert on the way in with the functions
19
+ below. Known differences (from a reading of the code on 5 December 2026, to be
20
+ confirmed with the maintainers):
21
+
22
+ - RampNet ``perspective.heading_pitch_roll``: roll is positive when the
23
+ camera's right-hand side tilts *up*, the opposite sign.
24
+ - RampNet pixel indices ``c`` address pixel centers at ``c + 0.5``.
25
+ - ArtScape keeps headings in radians.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import numpy as np
30
+
31
+ CRS = "EPSG:4326"
32
+
33
+
34
+ def wrap360(deg):
35
+ """Wrap degrees into [0, 360).
36
+
37
+ >>> float(wrap360(-90.0))
38
+ 270.0
39
+ >>> float(wrap360(360.0))
40
+ 0.0
41
+ """
42
+ return np.asarray(deg, dtype=float) % 360.0
43
+
44
+
45
+ def wrap180(deg):
46
+ """Wrap degrees into [-180, 180).
47
+
48
+ >>> float(wrap180(190.0))
49
+ -170.0
50
+ """
51
+ return (np.asarray(deg, dtype=float) + 180.0) % 360.0 - 180.0
52
+
53
+
54
+ def angle_diff(a_deg, b_deg):
55
+ """Signed smallest rotation from ``b`` to ``a``, in [-180, 180).
56
+
57
+ >>> float(angle_diff(10.0, 350.0))
58
+ 20.0
59
+ """
60
+ return wrap180(np.asarray(a_deg, dtype=float) - np.asarray(b_deg, dtype=float))
61
+
62
+
63
+ def heading_from_radians(rad):
64
+ """A heading in radians (clockwise from north) to degrees in [0, 360)."""
65
+ return wrap360(np.degrees(rad))
66
+
67
+
68
+ def roll_from_right_side_up(roll_deg):
69
+ """Roll given as "positive when the camera's right-hand side tilts up"
70
+ (RampNet's sign) to this library's sign."""
71
+ return -np.asarray(roll_deg, dtype=float)
72
+
73
+
74
+ def pixel_from_index(index):
75
+ """An integer pixel index to the continuous coordinate of its center."""
76
+ return np.asarray(index, dtype=float) + 0.5
@@ -0,0 +1,80 @@
1
+ """The frame record (DESIGN.md section 6.1).
2
+
3
+ PROVISIONAL. This schema is a proposal to be settled with the Project Sidewalk
4
+ and RampNet maintainers; field names and types are expected to change. It
5
+ follows Project Sidewalk's ``pano_data`` table closely and adds what
6
+ perspective images need.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ SCHEMA_VERSION = "0.1-provisional"
13
+
14
+ PROJECTIONS = ("equirectangular", "perspective", "fisheye", "cubemap")
15
+ POSE_QUALITIES = ("reported", "computed", "reconstructed", "registered", "estimated", "unknown")
16
+ CAPTURED_PRECISIONS = ("year", "month", "day", "second")
17
+ REDISTRIBUTION = ("allowed", "allowed_with_attribution", "not_allowed", "unknown")
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Field:
22
+ name: str
23
+ kind: str # string, float, int, bool, timestamp, category, json, geometry
24
+ required: bool = False
25
+ values: tuple[str, ...] | None = None
26
+ doc: str = ""
27
+
28
+
29
+ FIELDS: tuple[Field, ...] = (
30
+ Field("frame_id", "string", True, doc="source:native_id, unique across sources"),
31
+ Field("source", "string", True, doc="Registered source name"),
32
+ Field("native_id", "string", True, doc="The provider's identifier, unchanged"),
33
+ Field("instance", "string", doc="For federated providers"),
34
+ Field("geometry", "geometry", True, doc="Camera position, point, EPSG:4326"),
35
+ Field("elevation_m", "float"),
36
+ Field("position_accuracy_m", "float"),
37
+ Field("heading_deg", "float", doc="Compass bearing of the image center, [0, 360)"),
38
+ Field("pitch_deg", "float", doc="Positive looking up"),
39
+ Field("roll_deg", "float", doc="Positive clockwise seen from behind the camera"),
40
+ Field("pose_quality", "category", True, POSE_QUALITIES),
41
+ Field("levelled", "bool", doc="Whether the raster is already gravity-aligned"),
42
+ Field("projection", "category", True, PROJECTIONS),
43
+ Field("width_px", "int"),
44
+ Field("height_px", "int"),
45
+ Field("hfov_deg", "float", doc="For perspective and fisheye"),
46
+ Field("vfov_deg", "float"),
47
+ Field("intrinsics", "json", doc="Focal length, principal point, distortion"),
48
+ Field("captured_at", "timestamp", doc="UTC"),
49
+ Field("captured_precision", "category", values=CAPTURED_PRECISIONS),
50
+ Field("sequence_id", "string"),
51
+ Field("sequence_index", "int"),
52
+ Field("platform", "string"),
53
+ Field("camera_make", "string"),
54
+ Field("camera_model", "string"),
55
+ Field("copyright", "string", doc="Holder as the provider states it"),
56
+ Field("license", "string", doc="SPDX identifier when known, else the provider's text"),
57
+ Field("attribution", "string", doc="The line to display"),
58
+ Field("redistribution", "category", True, REDISTRIBUTION),
59
+ Field("available", "bool"),
60
+ Field("checked_at", "timestamp"),
61
+ Field("uri", "string", doc="Where the pixels can be obtained"),
62
+ Field("sha256", "string"),
63
+ Field("bytes", "int"),
64
+ Field("source_metadata", "json", doc="The provider's original record, unchanged"),
65
+ Field("retrieved_at", "timestamp", True),
66
+ Field("schema_version", "string", True),
67
+ )
68
+
69
+ FIELD_NAMES = tuple(f.name for f in FIELDS)
70
+ REQUIRED = tuple(f.name for f in FIELDS if f.required)
71
+ BY_NAME = {f.name: f for f in FIELDS}
72
+
73
+ PANDAS_DTYPES = {
74
+ "string": "string",
75
+ "float": "Float64",
76
+ "int": "Int64",
77
+ "bool": "boolean",
78
+ "category": "string",
79
+ "json": "string",
80
+ }