TheUserWW commited on
Commit
f10d4d7
·
verified ·
1 Parent(s): 4b4b493

Publish S.V.G.T. inference source and model configurations

Browse files

Source snapshot: TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer@341043621f307de225b3e04ddb4b5e3b8fc9e52b

README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - pytorch
4
+ - geolocation
5
+ - street-view
6
+ ---
7
+
8
+ # Street-View Geolocation Transformer (S.V.G.T.)
9
+
10
+ S.V.G.T. estimates latitude and longitude from street-view images. The visual transformer encodes each perspective view, ranks geographic cells, and predicts a coordinate within each candidate cell. A single fixed-view screenshot can be used as input.
11
+
12
+ ## Local inference
13
+
14
+ Use Python 3.10 or later and a compatible local S.V.G.T. checkpoint obtained separately. This repository contains the inference source and configurations.
15
+
16
+ ```bash
17
+ python -m pip install -r requirements.txt
18
+ python -m streetgeo.inference.predict street_view.jpg --checkpoint /path/to/model.pt --device auto --top-k 5 --json
19
+ ```
20
+
21
+ Run the command from this repository's root. It prints candidate coordinates, cell probabilities, and map links. For the optional country and region coverage filter, add `--google-coverage-only`. The bundled polygons provide a country and region approximation of coverage. See [map source metadata](assets/maps/un_map_sources.json).
22
+
23
+ The checkpoint carries the architecture configuration. The [400M configuration](configs/streetgeo_400m.json) and [legacy 135M configuration](configs/streetgeo_514m.json) are included for reference.
24
+
25
+ The source snapshot comes from [GitHub commit 3410436](https://github.com/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer/commit/341043621f307de225b3e04ddb4b5e3b8fc9e52b). The [full project](https://github.com/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer) contains the training workbench, Windows client, and tests.
assets/maps/google_streetview_regions.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "version": "2026-11-01",
3
+ "scope": "country_region_approximation",
4
+ "description": "Maintained country/region allowlist for offline prediction filtering. Includes countries with partial coverage. This is not Google's official coverage dataset, is not exhaustive, and does not verify roads, individual panoramas or current imagery availability. Third-party-only imagery does not qualify a region.",
5
+ "boundary_source": "un_countries.geojson (UN Geospatial / OCHA)",
6
+ "sources": [
7
+ "https://www.google.com/streetview/how-it-works/",
8
+ "https://blog.google/products-and-platforms/products/earth/3-imagery-updates-to-google-earth-and-maps/",
9
+ "https://blog.google/products-and-platforms/products/maps/nepal-street-view/",
10
+ "https://blog.google/products-and-platforms/products/maps/georgia-street-view/"
11
+ ],
12
+ "iso3_codes": [
13
+ "ABW", "ALB", "AND", "ARE", "ARG", "ASM", "AUS", "AUT",
14
+ "BEL", "BGD", "BGR", "BIH", "BMU", "BOL", "BRA", "BTN", "BWA",
15
+ "CAN", "CHE", "CHL", "COL", "CRI", "CUW", "CZE",
16
+ "DEU", "DNK", "DOM", "ECU", "ESP", "EST", "FIN", "FRA", "FRO",
17
+ "GBR", "GEO", "GHA", "GIB", "GRC", "GRL", "GTM", "GUM",
18
+ "HKG", "HRV", "HUN", "IDN", "IMN", "IND", "IRL", "ISL", "ISR", "ITA",
19
+ "JEY", "JOR", "JPN", "KAZ", "KEN", "KGZ", "KHM", "KOR",
20
+ "LAO", "LIE", "LKA", "LSO", "LTU", "LUX", "LVA", "MAC", "MCO", "MDG",
21
+ "MEX", "MKD", "MLT", "MNE", "MNG", "MNP", "MYS",
22
+ "NAM", "NGA", "NLD", "NOR", "NPL", "NZL", "OMN",
23
+ "PAN", "PER", "PHL", "POL", "PRI", "PRT", "PRY", "QAT",
24
+ "REU", "ROU", "RUS", "RWA", "SEN", "SGP", "SMR", "SRB",
25
+ "SVK", "SVN", "SWE", "SWZ", "THA", "TUN", "TUR", "TWN",
26
+ "UGA", "UKR", "URY", "USA", "VIR", "ZAF"
27
+ ]
28
+ }
assets/maps/un_countries.geojson ADDED
The diff for this file is too large to render. See raw diff
 
assets/maps/un_map_sources.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"provider":"United Nations / OCHA","service":"https://gis.unocha.org/server/rest/services/Hosted/Global_AB_25M_simplified_fs_gray/FeatureServer","item":"https://gis.unocha.org/portal/sharing/rest/content/items/455567f87cfc43718978b6b2662770a8","downloaded_at":"2026-10-31T00:52:52.446213+00:00","crs":"EPSG:4326","scale":"1:25,000,000 (source simplified reference layers)","disclaimer":"The boundaries and names shown and the designations used on this map do not imply official endorsement or acceptance by the United Nations.","boundary_styles":{"0":{"label":"Coastline","symbol":{"color":[153,191,229,255],"width":0.5,"style":"esriSLSSolid","type":"esriSLS"}},"1":{"label":"International boundary","symbol":{"color":[104,104,104,255],"width":1,"style":"esriSLSSolid","type":"esriSLS"}},"2":{"label":"Special boundary line","symbol":{"color":[153,153,153,255],"width":1.3,"style":"esriSLSDash","type":"esriSLS"}},"3":{"label":"Armistice or International administrative line","symbol":{"color":[153,153,153,255],"width":1.3,"style":"esriSLSDash","type":"esriSLS"}},"4":{"label":"Other line of seperation","symbol":{"color":[153,153,153,255],"width":1.3,"style":"esriSLSSolid","type":"esriSLS"}},"8":{"label":"Autnomous region boundary","symbol":{"color":[178,178,178,255],"width":1,"style":"esriSLSDash","type":"esriSLS"}},"9":{"label":"Sovereign base limit","symbol":{"color":[153,153,153,255],"width":0.5,"style":"esriSLSSolid","type":"esriSLS"}},"99":{"label":"Other","symbol":{"color":[191,191,191,255],"width":0.2,"style":"esriSLSSolid","type":"esriSLS"}}},"credits":"UN Geospatial, OCHA FISS","license_info":"<p><span style='font-weight:bold;'>Terms of use</span></p><p>The boundaries and names shown and the designations used on this map do not imply official endorsement or acceptance by the United Nations.</p><p><span style='font-style:italic; font-weight:bold;'>The designations employed and the presentation of material on this map do not imply the expression of any opinion whatsoever on the part of the Secretariat of the United Nations concerning the legal status of any country, territory, city or area or of its authorities, or concerning the delimitation of its frontiers or boundaries.</span></p><p><span style='font-style:italic; font-weight:bold;'>Final boundary between the Republic of Sudan and the Republic of South Sudan has not yet been determined. Dotted line represents approximately the Line of Control in Jammu and Kashmir agreed upon by India and Pakistan. The final status of Jammu and Kashmir has not yet been agreed upon by the parties. A dispute exists between the Governments of Argentina and the United Kingdom of Great Britain and Northern Ireland concerning sovereignty over the Falkland Islands (Malvinas).</span></p><p>Includes Non-Self-Governing Territories as defined by the United Nations.</p>","source_modified_ms":1789046595556,"item_metadata_error":null,"files":{"un_countries.geojson":{"sha256":"7f0623665b0ecd1a3d55544728fba1430f6b8f13078af198fed0d0abfc195754","bytes":2327508,"features":262},"un_boundaries.geojson":{"sha256":"d1e68a534d91ae5437ea30ab51433d3492669322577cbd28a6acd3c79c135184","bytes":2604735,"features":1894}}}
configs/streetgeo_400m.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_size": 224,
3
+ "patch_size": 16,
4
+ "n_embed": 1024,
5
+ "n_head": 16,
6
+ "n_layer": 28,
7
+ "fusion_layers": 2,
8
+ "view_queries": 4,
9
+ "max_views": 4,
10
+ "mlp_ratio": 4,
11
+ "dropout": 0.1,
12
+ "coarse_lat_bins": 18,
13
+ "coarse_lon_bins": 36,
14
+ "fine_bins": 4,
15
+ "cell_embed_dim": 128,
16
+ "offset_loss_weight": 1.0,
17
+ "spherical_loss_weight": 1.0
18
+ }
configs/streetgeo_514m.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "image_size": 224,
3
+ "patch_size": 16,
4
+ "n_embed": 768,
5
+ "n_head": 12,
6
+ "n_layer": 15,
7
+ "fusion_layers": 2,
8
+ "view_queries": 4,
9
+ "max_views": 4,
10
+ "mlp_ratio": 4,
11
+ "dropout": 0.1,
12
+ "coarse_lat_bins": 18,
13
+ "coarse_lon_bins": 36,
14
+ "fine_bins": 4,
15
+ "cell_embed_dim": 128,
16
+ "offset_loss_weight": 1.0,
17
+ "spherical_loss_weight": 1.0
18
+ }
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ torch>=2.3
2
+ Pillow>=10.0
3
+ shapely>=2.0
4
+ numpy>=1.26
streetgeo/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Street-View Geolocation Transformer (S.V.G.T.)."""
2
+
3
+ PROJECT_NAME = "Street-View Geolocation Transformer"
4
+ PROJECT_SHORT_NAME = "S.V.G.T."
5
+ PROJECT_TITLE = f"{PROJECT_NAME} ({PROJECT_SHORT_NAME})"
streetgeo/core/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """S.V.G.T. application package."""
2
+
3
+
4
+ class EmptyPredictionDomainError(ValueError):
5
+ """No model-generated coordinate satisfies the selected prediction domain."""
streetgeo/core/checkpoints.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned checkpoints carry the architecture, not just tensor weights."""
2
+
3
+ from dataclasses import asdict
4
+ from pathlib import Path
5
+ import os
6
+ import random
7
+ import shutil
8
+ import tempfile
9
+
10
+ import torch
11
+
12
+ from streetgeo.core.config import ModelConfig
13
+ from streetgeo.core.model import StreetGeoModel
14
+ from streetgeo.paths import validate_checkpoint_path
15
+
16
+ ARCHITECTURE = "streetview_hierarchical_vit_v1"
17
+
18
+
19
+ def resolve_device(name="auto"):
20
+ if name == "auto":
21
+ name = "cuda" if torch.cuda.is_available() else "cpu"
22
+ device = torch.device(name)
23
+ if device.type == "cuda" and not torch.cuda.is_available():
24
+ raise ValueError("CUDA was requested but is unavailable; use --device cpu")
25
+ return device
26
+
27
+
28
+ def save_checkpoint(model, path, *, training_state=None, keep_previous=False):
29
+ """Commit by atomic rename; a failed write leaves the old file usable."""
30
+ path = validate_checkpoint_path(path)
31
+ path.parent.mkdir(parents=True, exist_ok=True)
32
+ descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
33
+ try:
34
+ with os.fdopen(descriptor, "wb") as stream:
35
+ torch.save({"architecture": ARCHITECTURE, "model_config": asdict(model.config),
36
+ "model_state_dict": model.state_dict(),
37
+ "training_state": training_state or {}}, stream)
38
+ stream.flush()
39
+ os.fsync(stream.fileno())
40
+ if keep_previous and path.exists():
41
+ previous = path.with_name(path.stem + ".previous" + path.suffix)
42
+ backup = str(temporary) + ".backup"
43
+ try:
44
+ shutil.copyfile(path, backup)
45
+ os.replace(backup, previous)
46
+ finally:
47
+ Path(backup).unlink(missing_ok=True)
48
+ os.replace(temporary, path)
49
+ finally:
50
+ Path(temporary).unlink(missing_ok=True)
51
+
52
+
53
+ def capture_rng_state():
54
+ return {"python": random.getstate(), "torch": torch.get_rng_state(),
55
+ "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else []}
56
+
57
+
58
+ def restore_rng_state(state):
59
+ random.setstate(state["python"])
60
+ torch.set_rng_state(state["torch"].cpu())
61
+ if state["cuda"] and torch.cuda.is_available():
62
+ if len(state["cuda"]) != torch.cuda.device_count():
63
+ raise ValueError("CUDA device count changed; use the same devices for exact resume")
64
+ torch.cuda.set_rng_state_all([value.cpu() for value in state["cuda"]])
65
+
66
+
67
+ def read_checkpoint(path):
68
+ checkpoint = torch.load(path, map_location="cpu", weights_only=True)
69
+ if not isinstance(checkpoint, dict) or checkpoint.get("architecture") != ARCHITECTURE:
70
+ raise ValueError("Expected an S.V.G.T. visual checkpoint; old text GPT weights are incompatible")
71
+ return checkpoint
72
+
73
+
74
+ def load_model(path, device="auto"):
75
+ device = resolve_device(device)
76
+ checkpoint = read_checkpoint(path)
77
+ model = StreetGeoModel(ModelConfig(**checkpoint["model_config"]))
78
+ model.load_state_dict(checkpoint["model_state_dict"], strict=True)
79
+ return model.to(device).eval()
streetgeo/core/config.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Configuration shared by training, inference and saved checkpoints."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass
7
+ class ModelConfig:
8
+ image_size: int = 224
9
+ patch_size: int = 16
10
+ n_embed: int = 1024
11
+ n_head: int = 16
12
+ n_layer: int = 28
13
+ fusion_layers: int = 2
14
+ view_queries: int = 4
15
+ max_views: int = 4
16
+ mlp_ratio: int = 4
17
+ dropout: float = 0.1
18
+ coarse_lat_bins: int = 18
19
+ coarse_lon_bins: int = 36
20
+ fine_bins: int = 4
21
+ cell_embed_dim: int = 128
22
+ offset_loss_weight: float = 1.0
23
+ spherical_loss_weight: float = 1.0
24
+
25
+ def __post_init__(self):
26
+ integer_fields = (
27
+ "image_size", "patch_size", "n_embed", "n_head", "n_layer",
28
+ "fusion_layers", "view_queries", "max_views", "mlp_ratio",
29
+ "coarse_lat_bins", "coarse_lon_bins", "fine_bins", "cell_embed_dim",
30
+ )
31
+ for name in integer_fields:
32
+ value = getattr(self, name)
33
+ if type(value) is not int or value <= 0:
34
+ raise ValueError(f"{name} must be a positive integer")
35
+ if self.image_size % self.patch_size:
36
+ raise ValueError("image_size must be divisible by patch_size")
37
+ if self.n_embed % self.n_head:
38
+ raise ValueError("n_embed must be divisible by n_head")
39
+ if not 0 <= self.dropout < 1:
40
+ raise ValueError("dropout must be in [0, 1)")
41
+ if self.offset_loss_weight < 0 or self.spherical_loss_weight < 0:
42
+ raise ValueError("loss weights cannot be negative")
43
+
44
+ @property
45
+ def coarse_cells(self):
46
+ return self.coarse_lat_bins * self.coarse_lon_bins
47
+
48
+ @property
49
+ def children_per_cell(self):
50
+ return self.fine_bins ** 2
51
+
52
+ @property
53
+ def total_cells(self):
54
+ return self.coarse_cells * self.children_per_cell
55
+
56
+
57
+ @dataclass
58
+ class TrainConfig:
59
+ batch_size: int = 32
60
+ epochs: int = 4
61
+ learning_rate: float = 3e-4
62
+ weight_decay: float = 0.1
63
+ grad_clip: float = 1.0
64
+ warmup_steps: int = 1000
65
+ num_workers: int = 4
66
+ device: str = "auto"
67
+ seed: int = 1337
68
+ model_path: str = "checkpoints/streetgeo_400m_mapillary/best.pt"
69
+ save_every_steps: int = 500
70
+ save_every_seconds: float = 300.0
71
+ log_every_steps: int = 10
streetgeo/core/geography.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Spherical geometry and a data-independent hierarchical equal-area grid.
2
+
3
+ Cells partition sin(latitude) and longitude. IDs are parent-major.
4
+ All coordinates use (latitude, longitude) in degrees.
5
+ """
6
+
7
+ import math
8
+ from dataclasses import dataclass
9
+ from urllib.parse import urlencode
10
+
11
+ import torch
12
+ from streetgeo.core.config import ModelConfig
13
+
14
+ EARTH_RADIUS_KM = 6371.0088
15
+
16
+
17
+ def validate_coordinates(coordinates):
18
+ if coordinates.ndim < 1 or coordinates.shape[-1] != 2:
19
+ raise ValueError("coordinates must have shape (..., 2): latitude, longitude")
20
+ if not torch.isfinite(coordinates).all():
21
+ raise ValueError("coordinates must be finite")
22
+ if (coordinates[..., 0].abs() > 90).any():
23
+ raise ValueError("latitude must be in [-90, 90]")
24
+ if (coordinates[..., 1].abs() > 180).any():
25
+ raise ValueError("longitude must be in [-180, 180]")
26
+
27
+
28
+ def coordinates_to_unit_vectors(coordinates):
29
+ lat, lon = torch.deg2rad(coordinates.double()).unbind(-1)
30
+ return torch.stack((lat.cos() * lon.cos(), lat.cos() * lon.sin(), lat.sin()), -1)
31
+
32
+
33
+ def haversine_km(predicted, target):
34
+ """Great-circle error for evaluation, including the antimeridian."""
35
+ lat1, lon1 = torch.deg2rad(predicted.double()).unbind(-1)
36
+ lat2, lon2 = torch.deg2rad(target.double()).unbind(-1)
37
+ a = ((lat2 - lat1) / 2).sin().square()
38
+ a = a + lat1.cos() * lat2.cos() * ((lon2 - lon1) / 2).sin().square()
39
+ a = a.clamp(0, 1)
40
+ return 2 * EARTH_RADIUS_KM * torch.atan2(a.sqrt(), (1 - a).sqrt())
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class LocationPrediction:
45
+ latitude: float
46
+ longitude: float
47
+ probability: float # Raw joint cell probability, not calibrated accuracy.
48
+ cell_id: int
49
+
50
+ @property
51
+ def coordinates(self):
52
+ return f"{self.latitude:.6f}, {self.longitude:.6f}"
53
+
54
+ @property
55
+ def maps_url(self):
56
+ query = f"{self.latitude:.6f},{self.longitude:.6f}"
57
+ return "https://www.google.com/maps/search/?" + urlencode({"api": 1, "query": query})
58
+
59
+
60
+ class HierarchicalGeoGrid:
61
+ def __init__(self, config: ModelConfig):
62
+ self.lat_bins = config.coarse_lat_bins
63
+ self.lon_bins = config.coarse_lon_bins
64
+ self.fine_bins = config.fine_bins
65
+ self.children = config.children_per_cell
66
+ self.total_cells = config.total_cells
67
+
68
+ def encode(self, coordinates):
69
+ """Return coarse ID, local child ID and within-cell offsets in [-1, 1]."""
70
+ validate_coordinates(coordinates)
71
+ latitude, longitude = coordinates.double().unbind(-1)
72
+ u = (torch.deg2rad(latitude).sin() + 1) / 2
73
+ v = torch.remainder(longitude + 180, 360) / 360
74
+ rows, cols = self.lat_bins * self.fine_bins, self.lon_bins * self.fine_bins
75
+ row_position, col_position = u * rows, v * cols
76
+ row = row_position.floor().long().clamp(0, rows - 1)
77
+ col = col_position.floor().long().clamp(0, cols - 1)
78
+ coarse = (row // self.fine_bins) * self.lon_bins + col // self.fine_bins
79
+ child = (row % self.fine_bins) * self.fine_bins + col % self.fine_bins
80
+ offsets = torch.stack((2 * (row_position - row) - 1,
81
+ 2 * (col_position - col) - 1), -1).clamp(-1, 1)
82
+ return coarse, child, offsets
83
+
84
+ def _positions(self, cell_ids, offsets):
85
+ parent, child = cell_ids // self.children, cell_ids % self.children
86
+ row = (parent // self.lon_bins) * self.fine_bins + child // self.fine_bins
87
+ col = (parent % self.lon_bins) * self.fine_bins + child % self.fine_bins
88
+ # FP64 avoids losing latitude precision close to the poles, where
89
+ # sin(latitude) can round to exactly 1 in FP32. Only geometry uses FP64.
90
+ offsets = offsets.double()
91
+ u = (row + (offsets[..., 0] + 1) / 2) / (self.lat_bins * self.fine_bins)
92
+ v = (col + (offsets[..., 1] + 1) / 2) / (self.lon_bins * self.fine_bins)
93
+ return (2 * u - 1).clamp(-1, 1), (v * 2 - 1) * math.pi
94
+
95
+ def decode(self, cell_ids, offsets):
96
+ z, longitude = self._positions(cell_ids, offsets)
97
+ latitude = torch.rad2deg(z.asin())
98
+ longitude = torch.remainder(torch.rad2deg(longitude) + 180, 360) - 180
99
+ return torch.stack((latitude, longitude), -1)
100
+
101
+ def unit_vectors(self, cell_ids, offsets):
102
+ """Differentiable spherical positions without asin's polar singularity."""
103
+ z, longitude = self._positions(cell_ids, offsets)
104
+ radius = (1 - z.square()).clamp_min(1e-12).sqrt()
105
+ return torch.stack((radius * longitude.cos(), radius * longitude.sin(), z), -1)
streetgeo/core/model.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Street-view images -> hierarchical location hypotheses -> numeric coordinates.
2
+
3
+ Images must be preprocessed with streetgeo.datasets.images.load_image; optional headings are degrees
4
+ clockwise from north. This module never downloads weights or training data.
5
+ """
6
+
7
+ from dataclasses import dataclass
8
+ import torch
9
+ from torch import nn
10
+ from torch.nn import functional as F
11
+
12
+ from streetgeo.core import EmptyPredictionDomainError
13
+ from streetgeo.core.config import ModelConfig
14
+ from streetgeo.core.geography import HierarchicalGeoGrid, LocationPrediction, coordinates_to_unit_vectors
15
+
16
+
17
+ class MultiHeadAttention(nn.Module):
18
+ """Bidirectional self-attention; True in valid_mask means a real token."""
19
+
20
+ def __init__(self, config):
21
+ super().__init__()
22
+ self.n_head = config.n_head
23
+ self.head_size = config.n_embed // config.n_head
24
+ self.qkv = nn.Linear(config.n_embed, 3 * config.n_embed)
25
+ self.proj = nn.Linear(config.n_embed, config.n_embed)
26
+ self.dropout = config.dropout
27
+
28
+ def forward(self, x, valid_mask=None):
29
+ batch, length, width = x.shape
30
+ qkv = self.qkv(x).reshape(batch, length, 3, self.n_head, self.head_size)
31
+ q, k, v = qkv.permute(2, 0, 3, 1, 4).unbind(0)
32
+ mask = None if valid_mask is None else valid_mask[:, None, None, :]
33
+ attended = F.scaled_dot_product_attention(
34
+ q, k, v, attn_mask=mask, is_causal=False,
35
+ dropout_p=self.dropout if self.training else 0.0,
36
+ )
37
+ attended = attended.transpose(1, 2).reshape(batch, length, width)
38
+ return F.dropout(self.proj(attended), self.dropout, self.training)
39
+
40
+
41
+ class Block(nn.Module):
42
+ """Preserve the original pre-norm Transformer residual structure."""
43
+
44
+ def __init__(self, config):
45
+ super().__init__()
46
+ self.ln1 = nn.LayerNorm(config.n_embed)
47
+ self.attention = MultiHeadAttention(config)
48
+ self.ln2 = nn.LayerNorm(config.n_embed)
49
+ self.ffn = nn.Sequential(
50
+ nn.Linear(config.n_embed, config.mlp_ratio * config.n_embed), nn.GELU(),
51
+ nn.Linear(config.mlp_ratio * config.n_embed, config.n_embed),
52
+ nn.Dropout(config.dropout),
53
+ )
54
+
55
+ def forward(self, x, valid_mask=None):
56
+ x = x + self.attention(self.ln1(x), valid_mask)
57
+ return x + self.ffn(self.ln2(x))
58
+
59
+
60
+ class StreetViewEncoder(nn.Module):
61
+ def __init__(self, config):
62
+ super().__init__()
63
+ self.config = config
64
+ patches = (config.image_size // config.patch_size) ** 2
65
+ self.patch_embedding = nn.Conv2d(
66
+ 3, config.n_embed, kernel_size=config.patch_size, stride=config.patch_size,
67
+ )
68
+ self.position_embedding = nn.Parameter(torch.zeros(1, patches, config.n_embed))
69
+ self.visual_blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
70
+ self.visual_norm = nn.LayerNorm(config.n_embed)
71
+ self.pool_queries = nn.Parameter(torch.zeros(1, config.view_queries, config.n_embed))
72
+ self.pool_attention = nn.MultiheadAttention(
73
+ config.n_embed, config.n_head, dropout=config.dropout, batch_first=True,
74
+ )
75
+ # No view-index embedding: unordered views remain permutation invariant.
76
+ self.heading_embedding = nn.Sequential(nn.Linear(3, config.n_embed), nn.GELU(),
77
+ nn.Linear(config.n_embed, config.n_embed))
78
+ self.geo_token = nn.Parameter(torch.zeros(1, 1, config.n_embed))
79
+ self.fusion_blocks = nn.ModuleList([Block(config) for _ in range(config.fusion_layers)])
80
+ self.fusion_norm = nn.LayerNorm(config.n_embed)
81
+
82
+ def forward(self, images, view_mask=None, headings=None):
83
+ if images.ndim == 4:
84
+ images = images.unsqueeze(1)
85
+ size = self.config.image_size
86
+ if images.ndim != 5 or tuple(images.shape[2:]) != (3, size, size):
87
+ raise ValueError(f"images must have shape (B, 3, {size}, {size}) or (B, V, 3, {size}, {size})")
88
+ batch, views = images.shape[:2]
89
+ if batch == 0 or not 1 <= views <= self.config.max_views:
90
+ raise ValueError(f"nonempty batch and 1..{self.config.max_views} views required")
91
+ if not images.is_floating_point():
92
+ raise ValueError("images must be normalized floating-point RGB tensors")
93
+ if view_mask is None:
94
+ view_mask = torch.ones(batch, views, dtype=torch.bool, device=images.device)
95
+ elif view_mask.shape != (batch, views) or view_mask.dtype != torch.bool:
96
+ raise ValueError("view_mask must be boolean with shape (B, V)")
97
+ view_mask = view_mask.to(images.device)
98
+ if not view_mask.any(dim=1).all():
99
+ raise ValueError("every sample needs at least one valid view")
100
+ # Only valid views are encoded, so padding cannot contaminate gradients.
101
+ valid_images = images[view_mask]
102
+ if not torch.isfinite(valid_images).all():
103
+ raise ValueError("valid images must contain finite values")
104
+ x = self.patch_embedding(valid_images).flatten(2).transpose(1, 2)
105
+ x = x + self.position_embedding
106
+ for block in self.visual_blocks:
107
+ x = block(x)
108
+ x = self.visual_norm(x)
109
+ queries = self.pool_queries.expand(x.shape[0], -1, -1)
110
+ pooled, _ = self.pool_attention(queries, x, x, need_weights=False)
111
+ pooled = pooled + queries
112
+ tokens = pooled.new_zeros(batch, views, self.config.view_queries, self.config.n_embed)
113
+ tokens[view_mask] = pooled
114
+ if headings is None:
115
+ headings = torch.full((batch, views), float("nan"), device=images.device)
116
+ elif headings.shape != (batch, views):
117
+ raise ValueError("headings must have shape (B, V); NaN means unknown")
118
+ headings = headings.to(device=images.device, dtype=torch.float32)
119
+ if torch.isinf(headings[view_mask]).any():
120
+ raise ValueError("headings must be finite or NaN (unknown)")
121
+ known = torch.isfinite(headings) & view_mask
122
+ angle = torch.deg2rad(torch.where(known, headings, 0.0).remainder(360))
123
+ features = torch.stack((angle.sin() * known, angle.cos() * known, known.float()), -1)
124
+ tokens = tokens + self.heading_embedding(features).unsqueeze(2)
125
+ tokens = tokens.flatten(1, 2)
126
+ x = torch.cat((self.geo_token.expand(batch, -1, -1), tokens), dim=1)
127
+ valid = torch.cat((torch.ones(batch, 1, dtype=torch.bool, device=images.device),
128
+ view_mask.repeat_interleave(self.config.view_queries, dim=1)), dim=1)
129
+ for block in self.fusion_blocks:
130
+ x = block(x, valid)
131
+ return self.fusion_norm(x[:, 0])
132
+
133
+
134
+ @dataclass
135
+ class GeolocationOutput:
136
+ coordinates: torch.Tensor # (B, 2), highest-probability candidate
137
+ candidate_coordinates: torch.Tensor # (B, K, 2)
138
+ candidate_probabilities: torch.Tensor # (B, K), probabilities over ALL cells
139
+ candidate_cell_ids: torch.Tensor # (B, K)
140
+ coarse_logits: torch.Tensor # (B, coarse_cells)
141
+ fine_logits: torch.Tensor # (B, coarse_cells, children_per_cell)
142
+ embedding: torch.Tensor # (B, n_embed), for future retrieval
143
+ loss: torch.Tensor | None
144
+ loss_components: dict[str, torch.Tensor]
145
+
146
+
147
+ class StreetGeoModel(nn.Module):
148
+ def __init__(self, config=None):
149
+ super().__init__()
150
+ self.config = config or ModelConfig()
151
+ cfg = self.config
152
+ self.grid = HierarchicalGeoGrid(cfg)
153
+ self.encoder = StreetViewEncoder(cfg)
154
+ self.coarse_head = nn.Linear(cfg.n_embed, cfg.coarse_cells)
155
+ self.fine_head = nn.Linear(cfg.n_embed, cfg.total_cells)
156
+ self.cell_embedding = nn.Embedding(cfg.total_cells, cfg.cell_embed_dim)
157
+ self.offset_head = nn.Sequential(
158
+ nn.Linear(cfg.n_embed + cfg.cell_embed_dim, cfg.n_embed), nn.GELU(),
159
+ nn.Linear(cfg.n_embed, 2), nn.Tanh(),
160
+ )
161
+ self.apply(self._init_weights)
162
+ for parameter in (self.encoder.position_embedding, self.encoder.pool_queries,
163
+ self.encoder.geo_token):
164
+ nn.init.trunc_normal_(parameter, std=0.02)
165
+
166
+ @staticmethod
167
+ def _init_weights(module):
168
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.Embedding)):
169
+ nn.init.trunc_normal_(module.weight, std=0.02)
170
+ if getattr(module, "bias", None) is not None:
171
+ nn.init.zeros_(module.bias)
172
+
173
+ def _offsets(self, embedding, cell_ids):
174
+ visual = embedding.unsqueeze(1).expand(-1, cell_ids.shape[1], -1)
175
+ return self.offset_head(torch.cat((visual, self.cell_embedding(cell_ids)), dim=-1))
176
+
177
+ def _rank_candidates(self, embedding, log_probs, top_k, coordinate_filter=None):
178
+ if coordinate_filter is None:
179
+ values, cell_ids = log_probs.topk(top_k, dim=-1)
180
+ coordinates = self.grid.decode(cell_ids, self._offsets(embedding, cell_ids))
181
+ return values, cell_ids, coordinates
182
+ # Scan in probability order with bounded offset-head memory. Filtering the
183
+ # original top five alone could miss every valid lower-ranked candidate.
184
+ order = log_probs.argsort(dim=-1, descending=True, stable=True)
185
+ selected_ids, selected_coordinates = [], []
186
+ for sample in range(embedding.shape[0]):
187
+ kept_ids, kept_coordinates = [], []
188
+ count = 0
189
+ for start in range(0, order.shape[1], 256):
190
+ ids = order[sample:sample + 1, start:start + 256]
191
+ coordinates = self.grid.decode(ids, self._offsets(embedding[sample:sample + 1], ids))
192
+ mask = torch.as_tensor(coordinate_filter(coordinates[0].detach().cpu().numpy()),
193
+ dtype=torch.bool, device=ids.device)
194
+ if mask.shape != ids[0].shape:
195
+ raise ValueError("coordinate filter must return one boolean per coordinate")
196
+ kept_ids.append(ids[0, mask])
197
+ kept_coordinates.append(coordinates[0, mask])
198
+ count += int(mask.sum())
199
+ if count >= top_k:
200
+ break
201
+ if not count:
202
+ raise EmptyPredictionDomainError("No predicted coordinates fall inside the selected coverage domain")
203
+ selected_ids.append(torch.cat(kept_ids)[:top_k])
204
+ selected_coordinates.append(torch.cat(kept_coordinates)[:top_k])
205
+ # Tiny/custom grids can have fewer than top_k eligible locations.
206
+ size = min(len(ids) for ids in selected_ids)
207
+ ids = torch.stack([ids[:size] for ids in selected_ids])
208
+ coordinates = torch.stack([coords[:size] for coords in selected_coordinates])
209
+ return log_probs.gather(1, ids), ids, coordinates
210
+
211
+ def forward(self, images, targets=None, *, view_mask=None, headings=None, top_k=5,
212
+ coordinate_filter=None):
213
+ if type(top_k) is not int or not 1 <= top_k <= self.config.total_cells:
214
+ raise ValueError(f"top_k must be an integer in [1, {self.config.total_cells}]")
215
+ embedding = self.encoder(images, view_mask, headings)
216
+ return self.forward_embedding(embedding, targets, top_k=top_k, coordinate_filter=coordinate_filter)
217
+
218
+ def forward_embedding(self, embedding, targets=None, *, top_k=5, coordinate_filter=None):
219
+ """Run the geographic heads on features from this model's frozen encoder."""
220
+ if type(top_k) is not int or not 1 <= top_k <= self.config.total_cells:
221
+ raise ValueError(f"top_k must be an integer in [1, {self.config.total_cells}]")
222
+ if embedding.ndim != 2 or embedding.shape[1] != self.config.n_embed:
223
+ raise ValueError("embedding must have shape [batch, n_embed]")
224
+ batch = embedding.shape[0]
225
+ coarse = self.coarse_head(embedding)
226
+ fine = self.fine_head(embedding).reshape(batch, self.config.coarse_cells, -1)
227
+ # Exact joint probabilities over all leaves, without pruning coarse cells.
228
+ log_probs = F.log_softmax(coarse.float(), -1).unsqueeze(-1)
229
+ log_probs = (log_probs + F.log_softmax(fine.float(), -1)).flatten(1)
230
+ values, cell_ids, coordinates = self._rank_candidates(embedding, log_probs, top_k, coordinate_filter)
231
+ losses = {}
232
+ loss = None
233
+ if targets is not None:
234
+ if targets.shape != (batch, 2):
235
+ raise ValueError("targets must have shape (B, 2): latitude, longitude")
236
+ targets = targets.to(device=embedding.device, dtype=torch.float32)
237
+ parent, child, target_offsets = self.grid.encode(targets)
238
+ true_ids = parent * self.config.children_per_cell + child
239
+ # Teacher forcing trains the true cell even when classification is wrong.
240
+ offsets = self._offsets(embedding, true_ids.unsqueeze(1)).squeeze(1).float()
241
+ predicted_xyz = self.grid.unit_vectors(true_ids, offsets)
242
+ target_xyz = coordinates_to_unit_vectors(targets)
243
+ losses = {
244
+ "coarse": F.cross_entropy(coarse.float(), parent),
245
+ "fine": F.cross_entropy(fine[torch.arange(batch, device=embedding.device), parent].float(), child),
246
+ "offset": F.smooth_l1_loss(offsets, target_offsets),
247
+ "spherical": torch.linalg.vector_norm(predicted_xyz - target_xyz, dim=-1).mean(),
248
+ }
249
+ loss = (losses["coarse"] + losses["fine"]
250
+ + self.config.offset_loss_weight * losses["offset"]
251
+ + self.config.spherical_loss_weight * losses["spherical"])
252
+ return GeolocationOutput(coordinates[:, 0], coordinates, values.exp(), cell_ids,
253
+ coarse, fine, F.normalize(embedding, dim=-1), loss, losses)
254
+
255
+ @torch.inference_mode()
256
+ def predict(self, images, *, view_mask=None, headings=None, top_k=5, coordinate_filter=None):
257
+ """One ranked list per sample. Restores the caller's train/eval state."""
258
+ was_training = self.training
259
+ self.eval()
260
+ try:
261
+ output = self(images, view_mask=view_mask, headings=headings, top_k=top_k,
262
+ coordinate_filter=coordinate_filter)
263
+ coords = output.candidate_coordinates.cpu().tolist()
264
+ probs = output.candidate_probabilities.cpu().tolist()
265
+ ids = output.candidate_cell_ids.cpu().tolist()
266
+ return [[LocationPrediction(lat, lon, prob, cell)
267
+ for (lat, lon), prob, cell in zip(sample, scores, cells)]
268
+ for sample, scores, cells in zip(coords, probs, ids)]
269
+ finally:
270
+ self.train(was_training)
streetgeo/datasets/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """S.V.G.T. application package."""
streetgeo/datasets/images.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local image preprocessing and JSONL manifests. No network access."""
2
+
3
+ import json
4
+ import math
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from PIL import Image, ImageOps
9
+ from torch.utils.data import Dataset
10
+
11
+ from streetgeo.core.config import ModelConfig
12
+ from streetgeo.datasets.policy import require_mapillary_row
13
+ from streetgeo.datasets.road_mask import RoadMask, MASK_FILL
14
+
15
+ IMAGE_MEAN = (0.485, 0.456, 0.406)
16
+ IMAGE_STD = (0.229, 0.224, 0.225)
17
+ IMAGE_FILL = MASK_FILL
18
+
19
+
20
+ def manifest_lines(path):
21
+ """Stream large imported datasets instead of keeping another full text copy."""
22
+ with path.open(encoding="utf-8-sig") as stream:
23
+ yield from enumerate(stream, 1)
24
+
25
+
26
+ def load_image(path, image_size=224, *, road_mask=None, mask_bottom_third=False):
27
+ """RGB, EXIF orientation, aspect-preserving letterbox, then normalization.
28
+
29
+ Avoid random horizontal flips: they can reverse driving-side/sign clues.
30
+ Training and inference always use exactly the same preprocessing.
31
+ """
32
+ with Image.open(path) as source:
33
+ image = ImageOps.exif_transpose(source).convert("RGB")
34
+ if road_mask is not None and mask_bottom_third:
35
+ raise ValueError("choose one environment mask shape")
36
+ if road_mask is not None:
37
+ image = road_mask.apply(image)
38
+ if mask_bottom_third:
39
+ # Retained only to resume checkpoints created with recipe version 1.
40
+ image.paste(IMAGE_FILL, (0, image.height * 2 // 3, image.width, image.height))
41
+ image = ImageOps.pad(image, (image_size, image_size),
42
+ method=Image.Resampling.BICUBIC, color=IMAGE_FILL)
43
+ pixels = torch.frombuffer(bytearray(image.tobytes()), dtype=torch.uint8)
44
+ pixels = pixels.reshape(image_size, image_size, 3).permute(2, 0, 1).float() / 255
45
+ mean = pixels.new_tensor(IMAGE_MEAN).view(3, 1, 1)
46
+ std = pixels.new_tensor(IMAGE_STD).view(3, 1, 1)
47
+ return (pixels - mean) / std
48
+
49
+
50
+ class StreetViewDataset(Dataset):
51
+ """Each JSONL row is one location with 1..max_views local image paths.
52
+
53
+ {"images": ["front.jpg", "back.jpg"], "latitude": 34.0,
54
+ "longitude": -118.0, "headings": [0, 180]}
55
+
56
+ A single view may use "image": "front.jpg". Headings are optional and may
57
+ contain null for unknown directions. Relative paths resolve beside JSONL.
58
+ """
59
+
60
+ def __init__(self, manifest_path, config=None, *, mapillary_only=False, environment_specialist=False,
61
+ road_mask=None, legacy_environment_mask=False):
62
+ self.config = config or ModelConfig()
63
+ self.environment_specialist = environment_specialist
64
+ self.road_mask = road_mask if road_mask is not None else RoadMask()
65
+ self.legacy_environment_mask = legacy_environment_mask
66
+ manifest = Path(manifest_path).resolve()
67
+ self.samples = []
68
+ self.source_counts = {}
69
+ self.geographic_bounds = {"south": 90.0, "north": -90.0, "west": 180.0, "east": -180.0}
70
+ for line_number, line in manifest_lines(manifest):
71
+ if not line.strip():
72
+ continue
73
+ try:
74
+ row = json.loads(line)
75
+ if mapillary_only:
76
+ require_mapillary_row(row)
77
+ if not isinstance(row, dict):
78
+ raise ValueError("each row must be a JSON object")
79
+ if "images" in row and "image" in row:
80
+ raise ValueError("use either image or images")
81
+ paths = row.get("images", [row["image"]] if "image" in row else [])
82
+ if not isinstance(paths, list) or not 1 <= len(paths) <= self.config.max_views:
83
+ raise ValueError(f"provide 1..{self.config.max_views} image paths")
84
+ if not all(isinstance(path, str) and path for path in paths):
85
+ raise ValueError("image paths must be nonempty strings")
86
+ latitude, longitude = float(row["latitude"]), float(row["longitude"])
87
+ if not math.isfinite(latitude) or not -90 <= latitude <= 90:
88
+ raise ValueError("latitude must be finite and in [-90, 90]")
89
+ if not math.isfinite(longitude) or not -180 <= longitude <= 180:
90
+ raise ValueError("longitude must be finite and in [-180, 180]")
91
+ headings = row.get("headings", [None] * len(paths))
92
+ if not isinstance(headings, list) or len(headings) != len(paths):
93
+ raise ValueError("headings must match the number of images")
94
+ headings = [float("nan") if value is None else float(value) for value in headings]
95
+ for original, value in zip(row.get("headings", [None] * len(paths)), headings):
96
+ if original is not None and not math.isfinite(value):
97
+ raise ValueError("headings must be finite numbers or null")
98
+ self.samples.append((
99
+ [manifest.parent / path for path in paths],
100
+ (latitude, longitude), headings,
101
+ ))
102
+ source = str(row.get("source", "Mapillary" if "mapillary_id" in row else "custom"))
103
+ self.source_counts[source] = self.source_counts.get(source, 0) + 1
104
+ bounds = self.geographic_bounds
105
+ bounds["south"], bounds["north"] = min(bounds["south"], latitude), max(bounds["north"], latitude)
106
+ bounds["west"], bounds["east"] = min(bounds["west"], longitude), max(bounds["east"], longitude)
107
+ except (ValueError, TypeError, KeyError) as error:
108
+ raise ValueError(f"{manifest}:{line_number}: {error}") from error
109
+ if not self.samples:
110
+ raise ValueError("manifest contains no samples")
111
+
112
+ def __len__(self):
113
+ return len(self.samples)
114
+
115
+ def __getitem__(self, index):
116
+ phase = None
117
+ if isinstance(index, tuple):
118
+ index, phase = index
119
+ if not self.environment_specialist or phase not in (0, 1):
120
+ raise ValueError("invalid environment training phase")
121
+ paths, coordinates, headings = self.samples[index]
122
+ # Workers spawned by an already-running version-1 trainer may unpickle
123
+ # a dataset created before these shape attributes existed.
124
+ legacy = getattr(self, "legacy_environment_mask", True)
125
+ sample = {
126
+ "images": torch.stack([load_image(path, self.config.image_size,
127
+ road_mask=self.road_mask if phase == 1 and not legacy else None,
128
+ mask_bottom_third=phase == 1 and legacy) for path in paths]),
129
+ "coordinates": torch.tensor(coordinates, dtype=torch.float32),
130
+ "headings": torch.tensor(headings, dtype=torch.float32),
131
+ }
132
+ if phase is not None:
133
+ sample["training_phase"] = phase
134
+ return sample
135
+
136
+
137
+ class EnvironmentViewDataset(Dataset):
138
+ """Reuse a validated dataset for masked evaluation without copying its metadata."""
139
+ def __init__(self, dataset):
140
+ self.dataset = dataset
141
+
142
+ def __len__(self):
143
+ return len(self.dataset)
144
+
145
+ def __getitem__(self, index):
146
+ return self.dataset[index, 1]
147
+
148
+
149
+ def collate_streetviews(samples):
150
+ """Pad view counts and explicitly mask padded views."""
151
+ if not samples:
152
+ raise ValueError("cannot collate an empty batch")
153
+ views = max(sample["images"].shape[0] for sample in samples)
154
+ batch = len(samples)
155
+ shape = samples[0]["images"].shape[1:]
156
+ images = samples[0]["images"].new_zeros(batch, views, *shape)
157
+ mask = torch.zeros(batch, views, dtype=torch.bool)
158
+ headings = torch.full((batch, views), float("nan"))
159
+ for index, sample in enumerate(samples):
160
+ count = sample["images"].shape[0]
161
+ images[index, :count] = sample["images"]
162
+ mask[index, :count] = True
163
+ headings[index, :count] = sample["headings"]
164
+ result = {"images": images, "view_mask": mask, "headings": headings,
165
+ "targets": torch.stack([sample["coordinates"] for sample in samples])}
166
+ phases = {sample.get("training_phase") for sample in samples}
167
+ if len(phases) != 1:
168
+ raise ValueError("a batch must contain exactly one training phase")
169
+ if phases != {None}:
170
+ result["training_phase"] = torch.tensor(phases.pop())
171
+ return result
streetgeo/datasets/policy.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mapillary admission rules shared by preparation, the workbench and training."""
2
+ import json
3
+ from pathlib import Path
4
+ import re
5
+
6
+ MAPILLARY_SOURCE = "Mapillary"
7
+
8
+
9
+ def require_mapillary_row(row):
10
+ if not isinstance(row, dict) or row.get("source") != MAPILLARY_SOURCE:
11
+ raise ValueError("预训练仅接受 Mapillary;请使用 Mapillary API 下载生成的清单")
12
+ identifier, image = row.get("mapillary_id"), row.get("image")
13
+ if (not isinstance(identifier, str) or not re.fullmatch(r"[0-9]+", identifier) or
14
+ not isinstance(image, str) or not image or "images" in row or
15
+ Path(image).stem != identifier or "osv5m_id" in row):
16
+ raise ValueError("Mapillary 清单缺少有效的原始图片 ID,或图片文件名与 ID 不匹配;请重新下载/导入")
17
+
18
+
19
+ def check_mapillary_manifest_header(path):
20
+ """Fast GUI preflight; training validates every row, including resumed runs."""
21
+ path = Path(path)
22
+ with path.open(encoding="utf-8-sig") as stream:
23
+ for number, line in enumerate(stream, 1):
24
+ if line.strip():
25
+ try:
26
+ require_mapillary_row(json.loads(line))
27
+ except ValueError as error:
28
+ raise ValueError(f"{path}:{number}: {error}") from error
29
+ return
30
+ raise ValueError(f"{path}: Mapillary 清单为空")
streetgeo/datasets/road_mask.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Normalized, bottom-anchored road trapezoid shared by training and preview."""
2
+ from dataclasses import dataclass
3
+ import math
4
+
5
+ from PIL import ImageDraw
6
+
7
+ MASK_FILL = (124, 116, 104)
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class RoadMask:
12
+ top_width: float = .20
13
+ bottom_width: float = 1.0
14
+ height: float = .45
15
+
16
+ def __post_init__(self):
17
+ if (not all(math.isfinite(value) for value in (self.top_width, self.bottom_width, self.height))
18
+ or not 0 < self.top_width <= self.bottom_width <= 1 or not 0 < self.height <= 1):
19
+ raise ValueError("梯形参数须满足:0 < 上底 ≤ 下底 ≤ 100%,0 < 高 ≤ 100%")
20
+
21
+ def vertices(self, size):
22
+ width, height = size[0] - 1, size[1] - 1
23
+ return [(round((1 - self.top_width) * width / 2), round((1 - self.height) * height)),
24
+ (round((1 + self.top_width) * width / 2), round((1 - self.height) * height)),
25
+ (round((1 + self.bottom_width) * width / 2), height),
26
+ (round((1 - self.bottom_width) * width / 2), height)]
27
+
28
+ @property
29
+ def area_fraction(self):
30
+ return (self.top_width + self.bottom_width) * self.height / 2
31
+
32
+ def apply(self, image):
33
+ result = image.copy()
34
+ ImageDraw.Draw(result).polygon(self.vertices(result.size), fill=MASK_FILL)
35
+ return result
streetgeo/inference/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """S.V.G.T. application package."""
streetgeo/inference/coverage.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline country/region approximation of Google-operated Street View coverage.
2
+
3
+ This is an allowlist, not a road-level coverage map or an API availability check.
4
+ Geometries retain holes and separate territories from the bundled UN boundaries.
5
+ """
6
+
7
+ from functools import lru_cache
8
+ import json
9
+
10
+ from streetgeo.paths import MAP_ASSETS
11
+
12
+
13
+ @lru_cache(maxsize=1)
14
+ def coverage_metadata():
15
+ data = json.loads((MAP_ASSETS / "google_streetview_regions.json").read_text(encoding="utf-8"))
16
+ if data.get("scope") != "country_region_approximation" or not data.get("iso3_codes"):
17
+ raise ValueError("Invalid Google Street View region allowlist")
18
+ return data
19
+
20
+
21
+ @lru_cache(maxsize=1)
22
+ def _coverage_geometry():
23
+ from shapely import make_valid, prepare, union_all
24
+ from shapely.geometry import shape
25
+
26
+ allowed = set(coverage_metadata()["iso3_codes"])
27
+ source = json.loads((MAP_ASSETS / "un_countries.geojson").read_text(encoding="utf-8"))
28
+ geometries, found = [], set()
29
+ for feature in source["features"]:
30
+ code = feature["properties"].get("iso3cd")
31
+ if code in allowed and feature.get("geometry"):
32
+ geometries.append(make_valid(shape(feature["geometry"])))
33
+ found.add(code)
34
+ if allowed - found:
35
+ raise ValueError("Missing Street View region boundaries: " + ", ".join(sorted(allowed - found)))
36
+ geometry = union_all(geometries)
37
+ if geometry.is_empty:
38
+ raise ValueError("Empty Google Street View region coverage")
39
+ prepare(geometry)
40
+ return geometry
41
+
42
+
43
+ def google_coverage_mask(coordinates):
44
+ """Boolean array for (..., latitude/longitude); boundary points are included."""
45
+ import numpy as np
46
+ from shapely import intersects_xy
47
+
48
+ values = np.asarray(coordinates, dtype=float)
49
+ if values.ndim < 1 or values.shape[-1] != 2:
50
+ raise ValueError("coordinates must end in latitude, longitude")
51
+ lat, lon = values[..., 0], values[..., 1]
52
+ valid = np.isfinite(values).all(axis=-1) & (np.abs(lat) <= 90) & (np.abs(lon) <= 180)
53
+ return valid & intersects_xy(_coverage_geometry(), lon, lat)
54
+
55
+
56
+ def coverage_details():
57
+ data = coverage_metadata()
58
+ return {"scope": data["scope"], "version": data["version"],
59
+ "region_count": len(data["iso3_codes"]), "road_level_verified": False}
streetgeo/inference/predict.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Predict one location from one or more local street-view images."""
2
+
3
+ import argparse
4
+ import json
5
+ import math
6
+
7
+ import torch
8
+
9
+ from streetgeo.core.checkpoints import load_model
10
+ from streetgeo.core.config import TrainConfig
11
+ from streetgeo.datasets.images import load_image
12
+
13
+
14
+ def predict_images(model, image_paths, *, headings=None, top_k=5, google_coverage_only=False):
15
+ if not 1 <= len(image_paths) <= model.config.max_views:
16
+ raise ValueError(f"provide 1..{model.config.max_views} images of the SAME location")
17
+ device = next(model.parameters()).device
18
+ images = torch.stack([load_image(path, model.config.image_size) for path in image_paths])
19
+ direction_tensor = None
20
+ if headings is not None:
21
+ if len(headings) != len(image_paths):
22
+ raise ValueError("provide one heading per image")
23
+ if not all(value is None or math.isfinite(float(value)) for value in headings):
24
+ raise ValueError("headings must be finite numbers or None")
25
+ direction_tensor = torch.tensor([[float("nan") if value is None else value
26
+ for value in headings]], device=device)
27
+ options = {}
28
+ if google_coverage_only:
29
+ from streetgeo.inference.coverage import google_coverage_mask
30
+ options["coordinate_filter"] = google_coverage_mask
31
+ return model.predict(images.unsqueeze(0).to(device), headings=direction_tensor, top_k=top_k, **options)[0]
32
+
33
+
34
+ def main():
35
+ parser = argparse.ArgumentParser(description=__doc__)
36
+ parser.add_argument("images", nargs="+", help="1..max_views images of the same location")
37
+ parser.add_argument("--checkpoint", default=TrainConfig().model_path)
38
+ parser.add_argument("--headings", nargs="+", type=float, help="degrees clockwise from north")
39
+ parser.add_argument("--top-k", type=int, default=1)
40
+ parser.add_argument("--device", default="auto")
41
+ parser.add_argument("--google-coverage-only", action="store_true",
42
+ help="restrict coordinates to the offline Google Street View country/region allowlist (not road-level coverage)")
43
+ parser.add_argument("--json", action="store_true", help="include candidate scores and Maps URLs")
44
+ args = parser.parse_args()
45
+ model = load_model(args.checkpoint, args.device)
46
+ predictions = predict_images(model, args.images, headings=args.headings, top_k=args.top_k,
47
+ google_coverage_only=args.google_coverage_only)
48
+ if args.json:
49
+ print(json.dumps([{"coordinates": p.coordinates, "latitude": p.latitude,
50
+ "longitude": p.longitude, "cell_probability": p.probability,
51
+ "cell_id": p.cell_id, "maps_url": p.maps_url}
52
+ for p in predictions], ensure_ascii=False, indent=2))
53
+ else:
54
+ for prediction in predictions:
55
+ print(prediction.coordinates)
56
+
57
+
58
+ if __name__ == "__main__":
59
+ main()
streetgeo/paths.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stable workspace paths, independent of package and launch locations."""
2
+ import os
3
+ from pathlib import Path, PureWindowsPath
4
+
5
+ ROOT = Path(__file__).resolve().parents[1]
6
+ MAP_ASSETS = ROOT / "assets" / "maps"
7
+
8
+
9
+ def validate_checkpoint_path(value):
10
+ """Reject invalid Windows names before model allocation or temporary writes."""
11
+ path = Path(value)
12
+ if not path.name or path.name in (".", ".."):
13
+ raise ValueError("请选择有效的模型输出文件")
14
+ if os.name == "nt":
15
+ for part in path.parts:
16
+ if part == path.anchor or part in (".", ".."):
17
+ continue
18
+ if any(char in '<>:"|?*' or ord(char) < 32 for char in part):
19
+ raise ValueError(f"模型保存路径含 Windows 非法字符:{part!r}。例如请用 SVGT_4B.pt,文件名不能含冒号。")
20
+ if part.endswith((" ", ".")) or PureWindowsPath(part).is_reserved():
21
+ raise ValueError(f"模型保存路径含 Windows 保留名称或无效结尾:{part!r}")
22
+ return path