Add standalone bilingual Gradio geolocation demo
Browse files- README.md +4 -0
- huggingface_demo/.gitignore +11 -0
- huggingface_demo/README.md +55 -0
- huggingface_demo/app.py +104 -0
- huggingface_demo/requirements.txt +6 -0
- huggingface_demo/streetgeo/__init__.py +10 -0
- huggingface_demo/streetgeo/core/__init__.py +5 -0
- huggingface_demo/streetgeo/core/checkpoints.py +79 -0
- huggingface_demo/streetgeo/core/config.py +71 -0
- huggingface_demo/streetgeo/core/geography.py +105 -0
- huggingface_demo/streetgeo/core/model.py +270 -0
- huggingface_demo/streetgeo/datasets/__init__.py +1 -0
- huggingface_demo/streetgeo/datasets/images.py +171 -0
- huggingface_demo/streetgeo/datasets/policy.py +30 -0
- huggingface_demo/streetgeo/datasets/road_mask.py +35 -0
- huggingface_demo/streetgeo/inference/__init__.py +1 -0
- huggingface_demo/streetgeo/inference/predict.py +59 -0
- huggingface_demo/streetgeo/paths.py +27 -0
README.md
CHANGED
|
@@ -14,6 +14,10 @@ S.V.G.T. estimates latitude and longitude from street-view images. The visual tr
|
|
| 14 |
|
| 15 |
[Github Link](https://github.com/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
## Local inference
|
| 18 |
|
| 19 |
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.
|
|
|
|
| 14 |
|
| 15 |
[Github Link](https://github.com/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer)
|
| 16 |
|
| 17 |
+
## Interactive demo
|
| 18 |
+
|
| 19 |
+
[Gradio demo](huggingface_demo/README.md) supports Chinese and English, 1–4 views, and ranked coordinates with Google Maps links. Run it locally with a separate checkpoint or deploy the demo folder as a Gradio Space.
|
| 20 |
+
|
| 21 |
## Local inference
|
| 22 |
|
| 23 |
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.
|
huggingface_demo/.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
.venv/
|
| 3 |
+
.env
|
| 4 |
+
.env.*
|
| 5 |
+
.cache/
|
| 6 |
+
*.pt
|
| 7 |
+
*.pth
|
| 8 |
+
*.ckpt
|
| 9 |
+
*.safetensors
|
| 10 |
+
*.onnx
|
| 11 |
+
*.bin
|
huggingface_demo/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Street-View Geolocation Transformer (S.V.G.T.)
|
| 3 |
+
emoji: 🌍
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: "6.10.0"
|
| 8 |
+
python_version: "3.12"
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
models:
|
| 12 |
+
- TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Street-View Geolocation Transformer (S.V.G.T.)
|
| 16 |
+
|
| 17 |
+
上传同一地点的 1–4 张街景图片,查看预测经纬度、地理网格概率和 Google Maps 链接。
|
| 18 |
+
|
| 19 |
+
Upload 1–4 perspective street-view images of the same location to see ranked coordinates, geographic cell probabilities, and Google Maps links.
|
| 20 |
+
|
| 21 |
+
## 本地运行 / Run locally
|
| 22 |
+
|
| 23 |
+
在本目录中执行以下命令,使用单独获得的兼容 S.V.G.T. checkpoint。Use a compatible S.V.G.T. checkpoint obtained separately and run these commands from this folder.
|
| 24 |
+
|
| 25 |
+
```powershell
|
| 26 |
+
python -m pip install -r requirements.txt
|
| 27 |
+
$env:SVGT_CHECKPOINT = 'C:\path\to\model.pt'
|
| 28 |
+
python app.py
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
python -m pip install -r requirements.txt
|
| 33 |
+
SVGT_CHECKPOINT=/path/to/model.pt python app.py
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
打开终端显示的本地地址。Open the local URL printed by Gradio.
|
| 37 |
+
|
| 38 |
+
## 部署到 Hugging Face Spaces / Deploy to Hugging Face Spaces
|
| 39 |
+
|
| 40 |
+
将本目录的内容放在 Gradio Space 的仓库根目录。通过 Space 的 **Settings → Variables and secrets** 配置权重文件。Place the contents of this folder at the root of a Gradio Space and configure its model checkpoint in **Settings → Variables and secrets**.
|
| 41 |
+
|
| 42 |
+
| 变量 / Variable | 用法 / Usage |
|
| 43 |
+
| --- | --- |
|
| 44 |
+
| `SVGT_MODEL_FILE` | 模型仓库内的 checkpoint 相对路径。 / Checkpoint path relative to the model repository root. |
|
| 45 |
+
| `SVGT_MODEL_REPO` | 可选。默认使用本项目的模型仓库。 / Optional model repository ID. Defaults to the project's model repository. |
|
| 46 |
+
| `SVGT_MODEL_REVISION` | 可选。可指定模型仓库的提交版本。 / Optional revision to pin the checkpoint. |
|
| 47 |
+
| `HF_TOKEN` | 私有或受限仓库所需的读取令牌,请添加为 Secret。 / Add a read token as a Secret for private or gated weights. |
|
| 48 |
+
|
| 49 |
+
模型权重通过 Hugging Face Hub 单独下载。界面可在配置权重前打开,首次预测时会加载模型。Model weights are downloaded separately from the Hub. The interface opens before a checkpoint is configured and loads the model on the first prediction.
|
| 50 |
+
|
| 51 |
+
[模型仓库 / Model repository](https://huggingface.co/TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer) · [Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio)
|
| 52 |
+
|
| 53 |
+
## 推理代码 / Inference code
|
| 54 |
+
|
| 55 |
+
本目录的 `streetgeo/` 来自项目的 `backend/streetgeo/`,保留原有图像预处理、checkpoint 加载和推理流程。The bundled `streetgeo/` is a snapshot of the project's backend modules for image preprocessing, checkpoint loading, and prediction.
|
huggingface_demo/app.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio demo for Street-View Geolocation Transformer (S.V.G.T.)."""
|
| 2 |
+
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
import logging
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
from streetgeo import PROJECT_TITLE
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
MODEL_REPO = "TheUserWW/S.V.G.T.-StreetViewGeolocationTransformer"
|
| 14 |
+
MODEL_URL = f"https://huggingface.co/{MODEL_REPO}"
|
| 15 |
+
LOCAL_CHECKPOINT = os.environ.get("SVGT_CHECKPOINT")
|
| 16 |
+
HUB_CHECKPOINT = os.environ.get("SVGT_MODEL_FILE")
|
| 17 |
+
LOGGER = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@lru_cache(maxsize=1)
|
| 21 |
+
def get_model():
|
| 22 |
+
from streetgeo.core.checkpoints import load_model
|
| 23 |
+
|
| 24 |
+
checkpoint = LOCAL_CHECKPOINT
|
| 25 |
+
if not checkpoint:
|
| 26 |
+
from huggingface_hub import hf_hub_download
|
| 27 |
+
|
| 28 |
+
checkpoint = hf_hub_download(
|
| 29 |
+
repo_id=os.environ.get("SVGT_MODEL_REPO", MODEL_REPO),
|
| 30 |
+
filename=HUB_CHECKPOINT,
|
| 31 |
+
revision=os.environ.get("SVGT_MODEL_REVISION"),
|
| 32 |
+
token=os.environ.get("HF_TOKEN") or False,
|
| 33 |
+
)
|
| 34 |
+
return load_model(checkpoint, device=os.environ.get("SVGT_DEVICE", "auto"))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def predict(image_paths, top_k):
|
| 38 |
+
if not image_paths or len(image_paths) > 4:
|
| 39 |
+
return "请上传同一地点的 1–4 张街景图。 / Upload 1–4 views of the same location."
|
| 40 |
+
if not (LOCAL_CHECKPOINT or HUB_CHECKPOINT):
|
| 41 |
+
return "请先配置模型权重。 / Configure a model checkpoint first."
|
| 42 |
+
|
| 43 |
+
from streetgeo.inference.predict import predict_images
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
model = get_model()
|
| 47 |
+
except Exception:
|
| 48 |
+
LOGGER.exception("Could not load the S.V.G.T. checkpoint")
|
| 49 |
+
return "模型加载失败,请检查权重文件与访问权限。 / Could not load the checkpoint. Check the file and access permissions."
|
| 50 |
+
|
| 51 |
+
if len(image_paths) > model.config.max_views:
|
| 52 |
+
return f"此模型最多接受 {model.config.max_views} 张图片。 / This model accepts up to {model.config.max_views} views."
|
| 53 |
+
try:
|
| 54 |
+
predictions = predict_images(model, image_paths, top_k=min(int(top_k), model.config.total_cells))
|
| 55 |
+
except (OSError, Image.DecompressionBombError):
|
| 56 |
+
return "无法读取图片,请换一张常规大小的 JPG 或 PNG。 / Could not read an image. Try a standard-size JPG or PNG."
|
| 57 |
+
|
| 58 |
+
rows = [
|
| 59 |
+
"| 排名 / Rank | 经纬度 / Coordinates | 网格概率 / Cell probability | 地图 / Map |",
|
| 60 |
+
"| ---: | :--- | ---: | :--- |",
|
| 61 |
+
]
|
| 62 |
+
rows.extend(
|
| 63 |
+
f"| {rank} | `{result.coordinates}` | {result.probability:.2%} | [Google Maps]({result.maps_url}) |"
|
| 64 |
+
for rank, result in enumerate(predictions, 1)
|
| 65 |
+
)
|
| 66 |
+
return "\n".join(rows)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
with gr.Blocks(title=PROJECT_TITLE, delete_cache=(3600, 3600)) as demo:
|
| 70 |
+
gr.Markdown(
|
| 71 |
+
f"# {PROJECT_TITLE}\n"
|
| 72 |
+
"从街景图片估计经纬度。上传同一地点的 1–4 张透视街景图。\n\n"
|
| 73 |
+
"Estimate coordinates from 1–4 perspective street views of the same location. "
|
| 74 |
+
f"[模型仓库 / Model repository]({MODEL_URL})"
|
| 75 |
+
)
|
| 76 |
+
if not (LOCAL_CHECKPOINT or HUB_CHECKPOINT):
|
| 77 |
+
gr.Markdown(
|
| 78 |
+
"**模型尚未配置 / Checkpoint not configured**\n\n"
|
| 79 |
+
"本地运行时设置 `SVGT_CHECKPOINT`。部署到 Space 后可设置 `SVGT_MODEL_FILE`。\n\n"
|
| 80 |
+
"Set `SVGT_CHECKPOINT` locally or `SVGT_MODEL_FILE` in the Space settings."
|
| 81 |
+
)
|
| 82 |
+
with gr.Row():
|
| 83 |
+
with gr.Column():
|
| 84 |
+
images = gr.File(
|
| 85 |
+
label="街景图片 / Street-view images",
|
| 86 |
+
file_types=[".jpg", ".jpeg", ".png", ".webp"],
|
| 87 |
+
file_count="multiple",
|
| 88 |
+
type="filepath",
|
| 89 |
+
)
|
| 90 |
+
count = gr.Slider(1, 10, value=5, step=1, label="候选数量 / Number of candidates")
|
| 91 |
+
run = gr.Button("预测位置 / Predict location", variant="primary")
|
| 92 |
+
with gr.Column():
|
| 93 |
+
gr.Markdown("### 候选地点 / Location candidates")
|
| 94 |
+
result = gr.Markdown("预测结果会显示在这里。 / Predictions will appear here.")
|
| 95 |
+
gr.Markdown("网格概率表示模型分配给该地理网格的概率。 / The score is the model probability assigned to the geographic cell.")
|
| 96 |
+
run.click(predict, inputs=[images, count], outputs=result, api_name="predict")
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
demo.queue(max_size=8).launch(
|
| 101 |
+
theme=gr.themes.Soft(primary_hue="teal"),
|
| 102 |
+
max_file_size="12mb",
|
| 103 |
+
footer_links=["api"],
|
| 104 |
+
)
|
huggingface_demo/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch==2.9.1+cpu; sys_platform == "linux" and platform_machine == "x86_64"
|
| 3 |
+
torch>=2.6,<3; sys_platform != "linux" or platform_machine != "x86_64"
|
| 4 |
+
gradio==6.10.0
|
| 5 |
+
huggingface-hub>=1,<2
|
| 6 |
+
Pillow>=10,<13
|
huggingface_demo/streetgeo/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Street-View Geolocation Transformer (S.V.G.T.)."""
|
| 2 |
+
|
| 3 |
+
from .paths import BACKEND_ROOT, FRONTEND_ROOT, ROOT
|
| 4 |
+
|
| 5 |
+
if ROOT != BACKEND_ROOT:
|
| 6 |
+
__path__.append(str(FRONTEND_ROOT / "streetgeo"))
|
| 7 |
+
|
| 8 |
+
PROJECT_NAME = "Street-View Geolocation Transformer"
|
| 9 |
+
PROJECT_SHORT_NAME = "S.V.G.T."
|
| 10 |
+
PROJECT_TITLE = f"{PROJECT_NAME} ({PROJECT_SHORT_NAME})"
|
huggingface_demo/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."""
|
huggingface_demo/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()
|
huggingface_demo/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
|
huggingface_demo/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)
|
huggingface_demo/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)
|
huggingface_demo/streetgeo/datasets/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""S.V.G.T. application package."""
|
huggingface_demo/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
|
huggingface_demo/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 清单为空")
|
huggingface_demo/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
|
huggingface_demo/streetgeo/inference/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""S.V.G.T. application package."""
|
huggingface_demo/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()
|
huggingface_demo/streetgeo/paths.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stable workspace paths, independent of package and launch locations."""
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path, PureWindowsPath
|
| 4 |
+
|
| 5 |
+
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
| 6 |
+
ROOT = BACKEND_ROOT
|
| 7 |
+
# The workbench package identifies the full workspace even if a portable client is named backend.
|
| 8 |
+
if BACKEND_ROOT.name == "backend" and (Path(__file__).with_name("workbench") / "__init__.py").is_file():
|
| 9 |
+
ROOT = BACKEND_ROOT.parent
|
| 10 |
+
FRONTEND_ROOT = ROOT / "frontend"
|
| 11 |
+
MAP_ASSETS = BACKEND_ROOT / "assets" / "maps"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def validate_checkpoint_path(value):
|
| 15 |
+
"""Reject invalid Windows names before model allocation or temporary writes."""
|
| 16 |
+
path = Path(value)
|
| 17 |
+
if not path.name or path.name in (".", ".."):
|
| 18 |
+
raise ValueError("请选择有效的模型输出文件")
|
| 19 |
+
if os.name == "nt":
|
| 20 |
+
for part in path.parts:
|
| 21 |
+
if part == path.anchor or part in (".", ".."):
|
| 22 |
+
continue
|
| 23 |
+
if any(char in '<>:"|?*' or ord(char) < 32 for char in part):
|
| 24 |
+
raise ValueError(f"模型保存路径含 Windows 非法字符:{part!r}。例如请用 SVGT_4B.pt,文件名不能含冒号。")
|
| 25 |
+
if part.endswith((" ", ".")) or PureWindowsPath(part).is_reserved():
|
| 26 |
+
raise ValueError(f"模型保存路径含 Windows 保留名称或无效结尾:{part!r}")
|
| 27 |
+
return path
|