File size: 14,403 Bytes
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10d226e
2340e8b
 
bf99854
2340e8b
 
 
 
 
 
 
 
 
 
 
9bda7b2
 
 
 
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10d226e
 
 
 
 
 
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf99854
 
 
 
 
 
 
 
 
 
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
10d226e
bf99854
 
 
 
 
10d226e
2340e8b
 
 
 
bf99854
2340e8b
 
 
 
 
 
 
 
 
 
10d226e
2340e8b
 
 
 
 
bf99854
 
 
 
 
 
 
 
 
2340e8b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf99854
2340e8b
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""Research-only single-photo BEV and cross-view retrieval service."""
import spaces  # Must precede torch/Gradio imports on ZeroGPU.

from pathlib import Path
import json
import os
import resource
import tempfile
import time

import gradio as gr
import numpy as np
import torch
from spaces.config import Config

from inference_core import (
    ROOT, MODEL_DIR, sample_model, infer_bev_cpu,
    infer_embedding_cpu, prepare_bev, prepare_embedding, visualize_bev,
)
from bev_matching import match_features

ZERO_GPU = bool(Config.zero_gpu)
OUTPUT_ROOT = Path(tempfile.gettempdir()) / "geo-bev-outputs"
OUTPUT_ROOT.mkdir(exist_ok=True)
# Official ZeroGPU guidance: place CUDA models at module scope. CPU uses separate
# ONNX sessions; never move one shared model between devices during requests.
SAMPLE_GPU = sample_model("cuda") if ZERO_GPU else None


@spaces.GPU(duration=15)
def gpu_inference(kind, arrays):
    # The first hosted BEV probe failed numeric agreement with CUDA TF32 enabled.
    # Use full FP32 convolution/matmul; keep the original verification tolerance.
    torch.backends.cudnn.allow_tf32 = False
    torch.backends.cuda.matmul.allow_tf32 = False
    with torch.inference_mode():
        if kind == "embedding":
            return [SAMPLE_GPU(torch.from_numpy(x).to("cuda")).detach().cpu().numpy() for x in arrays]
    raise ValueError("Unknown model kind")


def capacity_error(exc):
    # Only scheduler/quota failures may trigger fallback, not arbitrary model bugs.
    title = str(getattr(exc, "title", ""))
    message = str(getattr(exc, "message", str(exc)))
    if title in {"ZeroGPU quota exceeded", "ZeroGPU pending credits exceeded", "ZeroGPU queue timeout"}:
        return True
    return isinstance(exc, gr.Error) and any(text in message for text in (
        "Space app has reached its GPU limit", "You have exceeded your free ZeroGPU quota",
        "You have exceeded your ZeroGPU quota", "You have exceeded your ZeroGPU runs limit",
        "too many ZeroGPU credits allocated", "No GPU is currently available",
    ))


def run_model(kind, arrays, compute="auto"):
    if compute not in {"auto", "cpu", "gpu"}:
        raise ValueError("compute must be auto, cpu or gpu")
    if kind == "bev":
        if compute == "gpu":
            raise ValueError("GPU BEV is disabled: it failed strict numerical agreement. Use cpu or auto (verified ONNX CPU).")
        # CPU BEV passed both photos' strict hosted numerical gate and is faster
        # than GPU allocation here. Keep the failed GPU route out of production.
        compute = "cpu"
    fallback = None
    started = time.perf_counter()
    if compute != "cpu" and ZERO_GPU:
        try:
            output = gpu_inference(kind, arrays)
            return output, {"backend": "pytorch-cuda-zerogpu", "fallback": None, "inference_seconds": round(time.perf_counter() - started, 4)}
        except Exception as exc:
            if compute == "gpu" or not capacity_error(exc):
                raise
            fallback = "ZeroGPU scheduler/quota unavailable; independent ONNX CPU inference used"
    elif compute == "gpu":
        raise ValueError("GPU route is only available inside the ZeroGPU deployment")
    if kind == "bev":
        output = infer_bev_cpu(*arrays)
    else:
        output = [infer_embedding_cpu(x) for x in arrays]
    return output, {"backend": "onnxruntime-cpu", "fallback": fallback, "inference_seconds": round(time.perf_counter() - started, 4)}


def artifact(name, **arrays):
    directory = Path(tempfile.mkdtemp(prefix="request-", dir=OUTPUT_ROOT))
    path = directory / name
    np.savez_compressed(path, **arrays)
    return str(path)


def check_outputs(arrays):
    if not all(np.isfinite(np.asarray(x)).all() for x in arrays):
        raise ValueError("Model produced non-finite output")


def bev(image, hfov=60.0, pitch=0.0, roll=0.0, compute="auto"):
    """Extract real OrienterNet BEV features; camera geometry is assumed, not calibrated."""
    tensor, camera, camera_meta = prepare_bev(image, hfov, pitch, roll)
    outputs, receipt = run_model("bev", [tensor, camera], compute)
    check_outputs(outputs)
    features, confidence, valid = outputs
    metadata = {
        "model": "OrienterNet-MGL", "feature_shape": list(features.shape),
        "grid": {"lateral_meters": [-32, 32], "forward_meters": [0.5, 32], "pixels_per_meter": 2,
                 "row_order": "far-to-near", "column_order": "left-to-right"},
        "valid_fraction": float(np.mean(valid)), "camera": camera_meta, **receipt,
        "location_verified": False, "coordinates": None,
        "warning": "Feature visualization, NOT reconstructed satellite imagery. No semantic-map matching or coordinate solving in this endpoint.",
    }
    file = artifact("orienternet-bev.npz", features=features, confidence=confidence, valid=valid,
                    camera=camera, metadata=np.array(json.dumps(metadata)))
    return visualize_bev(*outputs), file, metadata


def embed(image, view="ground", compute="auto"):
    """Return a real L2-normalized 1024D Sample4Geo CVUSA embedding."""
    tensor, preprocessing = prepare_embedding(image, view)
    outputs, receipt = run_model("embedding", [tensor], compute)
    check_outputs(outputs)
    vector = outputs[0][0]
    metadata = {"model": "Sample4Geo-CVUSA", "embedding_dim": int(vector.size),
                "l2_norm": float(np.linalg.norm(vector)), "preprocessing": preprocessing,
                "location_verified": False, "coordinates": None, **receipt}
    file = artifact("sample4geo-embedding.npz", embedding=vector, metadata=np.array(json.dumps(metadata)))
    return {**metadata, "embedding": vector.tolist()}, file


def rank(image, candidates, compute="auto"):
    """Rank 1..12 caller-supplied satellite images; scores do not establish target presence."""
    if not candidates or len(candidates) > 12:
        raise ValueError("Supply 1..12 candidate satellite image files per request")
    ground, pre_ground = prepare_embedding(image, "ground")
    satellite = [prepare_embedding(path, "satellite")[0] for path in candidates]
    outputs, receipt = run_model("embedding", [ground, *satellite], compute)
    check_outputs(outputs)
    query = outputs[0][0]
    gallery = np.concatenate(outputs[1:], axis=0)
    scores = gallery @ query
    indices = np.argsort(-scores, kind="stable")
    results = [{"rank": i + 1, "candidate_index": int(index), "candidate_file": Path(candidates[index]).name,
                "cosine_similarity": float(scores[index])} for i, index in enumerate(indices)]
    metadata = {
        "model": "Sample4Geo-CVUSA", "candidate_count": len(candidates), "ranking": results,
        "top1_top2_margin": float(scores[indices[0]] - scores[indices[1]]) if len(indices) > 1 else None,
        "preprocessing": pre_ground, **receipt,
        "target_presence": "unassessed", "location_verified": False, "coordinates": None,
        "warning": "Uncalibrated ranking only, not probability or proof of presence. Night/narrow-FOV China images require independent scene verification.",
    }
    file = artifact("sample4geo-ranking.npz", query=query, candidate_embeddings=gallery,
                    cosine_scores=scores, metadata=np.array(json.dumps(metadata)))
    return metadata, file


def match_bev(features_npz, maps_npz):
    """Match one existing BEV against 1..12 caller-supplied semantic map crops."""
    if not features_npz or not maps_npz:
        raise ValueError("BEV features and a semantic-map NPZ pack are required")
    metadata, arrays = match_features(features_npz, maps_npz)
    file = artifact("orienternet-map-matching.npz", **arrays,
                    metadata=np.array(json.dumps(metadata, allow_nan=False)))
    return metadata, file


def status():
    """Observed process/container limits, not an advertised hardware guarantee."""
    limits = {}
    for name, path in (("memory_max", "/sys/fs/cgroup/memory.max"), ("cpu_max", "/sys/fs/cgroup/cpu.max"),
                       ("memory_limit_v1", "/sys/fs/cgroup/memory/memory.limit_in_bytes")):
        file = Path(path)
        if file.exists():
            limits[name] = file.read_text().strip()
    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
    import platform
    peak_mib = peak / (1024 ** 2 if platform.system() == "Darwin" else 1024)
    manifest = json.loads((ROOT / "MODEL_PROVENANCE.json").read_text())
    return {"service": "single-photo-geolocation-features", "zerogpu": ZERO_GPU,
            "gpu_models_initialized": SAMPLE_GPU is not None,
            "model_backends": {"bev": ["onnxruntime-cpu"], "embedding_and_rank": ["onnxruntime-cpu", "pytorch-cuda-zerogpu"],
                               "match_bev": ["pytorch-cpu-pretrained-map-encoder-and-voting"]},
            "semantic_map_matching": {"endpoint": "/match_bev", "pretrained_weights": "OrienterNet-MGL",
                                      "map_limit": "1..12 integer [3,256,256] semantic rasters, 2 pixels/meter",
                                      "target_presence": "unassessed", "coordinates_verified": False},
            "bev_gpu_policy": "Disabled after strict numeric gate failure, including with TF32 off; auto BEV uses verified CPU. Failed route evidence retained in the deployment report.",
            "cpu_backend": "onnxruntime", "torch_threads": torch.get_num_threads(),
            "os_cpu_count": os.cpu_count(), "process_peak_rss_mib": round(peak_mib, 1), "observed_cgroup_limits": limits,
            "models": manifest, "location_verified": False,
            "privacy": "Public research service; do not upload sensitive photos. Results expire from the app cache after about one hour; hosting provider retention is separate.",
            "limits": "Queue 8, inference concurrency 1, max upload 10MB/file, 16MP/image, 12 gallery images/maps per request; NPZ uncompressed <=32MiB. Free service may sleep or be unavailable."}


with gr.Blocks(analytics_enabled=False, delete_cache=(600, 3600), title="BEV + CVGL research inference") as demo:
    gr.Markdown("# 单照片 BEV / CVGL 实验\n真实 **OrienterNet-MGL** 特征 + **Sample4Geo-CVUSA** 向量检索。**不是自动驾驶多相机 BEV,也不直接给出已验证经纬度。**\n\n公开研究服务,请勿上传敏感照片;原始照片不会作为仓库示例发布。GPU 有正常配额,CPU 也不保证永远在线。")
    with gr.Tab("BEV 特征"):
        photo = gr.Image(type="pil", label="原始照片(不要使用生成式修复图作真值)")
        with gr.Row():
            hfov = gr.Number(value=60, label="假设水平视场角(度)")
            pitch = gr.Number(value=0, label="假设 pitch(度,upstream ZX convention)")
            roll = gr.Number(value=0, label="假设 roll(度)")
        compute_bev = gr.Dropdown(["auto", "cpu"], value="auto", label="BEV 使用已验证的 ONNX CPU;auto 等同 cpu")
        button_bev = gr.Button("提取 BEV", variant="primary")
        preview = gr.Image(label="左:特征伪彩色;右:模型置信度(均不是定位置信度)", format="png")
        bev_file = gr.File(label="原始 BEV 张量 NPZ")
        bev_meta = gr.JSON(label="推理与相机假设收据")
        button_bev.click(bev, [photo, hfov, pitch, roll, compute_bev], [preview, bev_file, bev_meta], api_name="bev", concurrency_id="inference")
    with gr.Tab("BEV 与语义地图匹配"):
        gr.Markdown("使用 `/bev` 的真实特征与调用者准备的 OSM 语义地图匹配。每个候选返回局部位置/朝向假设;**错误地图也可能得高分,不能据此确认地点。** 输入规范见 `MAP_MATCHING.md`。")
        match_features_file = gr.File(file_types=[".npz"], label="BEV 特征 NPZ(/bev 输出)")
        match_maps_file = gr.File(file_types=[".npz"], label="1–12 个 256×256 三通道语义地图 NPZ")
        match_button = gr.Button("真实 BEV → 语义地图匹配(CPU)")
        match_meta = gr.JSON(label="候选姿态与非校准原始分数;经纬度未验证")
        match_output_file = gr.File(label="逐候选相关性热图 NPZ")
        match_button.click(match_bev, [match_features_file, match_maps_file], [match_meta, match_output_file],
                           api_name="match_bev", concurrency_id="inference")
    with gr.Tab("CVGL 向量"):
        embed_photo = gr.Image(type="pil", label="图片")
        embed_view = gr.Radio(["ground", "satellite"], value="ground", label="图片视角")
        embed_compute = gr.Dropdown(["auto", "cpu", "gpu"], value="auto", label="计算路径")
        embed_button = gr.Button("计算 1024 维向量")
        embed_result = gr.JSON(label="L2 归一化向量与收据")
        embed_file = gr.File(label="向量 NPZ")
        embed_button.click(embed, [embed_photo, embed_view, embed_compute], [embed_result, embed_file], api_name="embed", concurrency_id="inference")
    with gr.Tab("候选卫星图排序"):
        query = gr.Image(type="pil", label="地面原图")
        gallery = gr.File(file_count="multiple", file_types=[".jpg", ".jpeg", ".png", ".webp"], label="1–12 张候选卫星切片(不自动搜索全球)")
        rank_compute = gr.Dropdown(["auto", "cpu", "gpu"], value="auto", label="计算路径")
        rank_button = gr.Button("跨视角粗排")
        ranking = gr.JSON(label="相似度不是概率,不代表目标一定在候选库中")
        ranking_file = gr.File(label="查询/候选向量与分数 NPZ")
        rank_button.click(rank, [query, gallery, rank_compute], [ranking, ranking_file], api_name="rank", concurrency_id="inference")
    with gr.Tab("运行状态 / API"):
        status_button = gr.Button("读取实际运行状态")
        status_json = gr.JSON()
        status_button.click(status, [], status_json, api_name="status")
        gr.Markdown("API: `/bev`、`/match_bev`、`/embed`、`/rank`、`/status`。使用 `gradio_client.Client('SammySnake/BEV')`。\n\nOrienterNet 原始代码/权重为 CC-BY-NC;Sample4Geo 未声明清晰许可,不能视作商业授权。详见仓库归属说明。")

demo.queue(max_size=8, default_concurrency_limit=1)

if __name__ == "__main__":
    demo.launch(server_name=os.environ.get("GEO_BIND", "0.0.0.0"),
                server_port=int(os.environ.get("PORT", "7860")), max_file_size="10mb",
                allowed_paths=[str(OUTPUT_ROOT)], show_error=True)