Safetensors
File size: 10,317 Bytes
f9c869c
 
 
 
 
 
 
8adeaa1
f9c869c
8adeaa1
f9c869c
 
d35edd7
8adeaa1
f9c869c
 
 
 
 
69c768f
e31116c
 
 
 
d35edd7
 
 
 
 
 
 
 
 
 
8adeaa1
 
 
 
 
 
 
f9c869c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8adeaa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d35edd7
 
 
 
 
8adeaa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d35edd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8adeaa1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c869c
69c768f
f9c869c
 
 
c6c1400
f9c869c
69c768f
f9c869c
 
 
e31116c
f9c869c
 
 
e31116c
d35edd7
8adeaa1
 
 
 
 
 
 
 
 
 
 
d35edd7
8adeaa1
e31116c
8adeaa1
 
d35edd7
 
 
 
 
 
 
 
e31116c
f9c869c
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""HTTP server for a GeoText-1652 custom Inference Endpoint container."""

from __future__ import annotations

import os
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple

import numpy as np
import torch
from fastapi import FastAPI, HTTPException
from hub_storage import persist_patch_embeddings
from infer import fetch_rgb_geotiff, load_model, model_outputs, tile_image
from pydantic import BaseModel, Field


class InferenceRequest(BaseModel):
    image_url: str = Field(..., description="Public RGB GeoTIFF/COG URL")
    queries: List[str] = Field(..., min_items=1, description="Text queries to rank")
    include_embeddings: bool = Field(
        False, description="Return 256-dimensional image and text vectors"
    )
    include_bboxes: bool = Field(False, description="Return text-conditioned normalized boxes")
    include_patch_embeddings: bool = Field(
        False,
        description="Return normalized 256-dimensional spatial patch embeddings",
    )
    store_patch_embeddings: bool = Field(
        False, description="Persist patch embeddings as Parquet in the configured Hub bucket"
    )
    output_prefix: Optional[str] = Field(
        None, description="Optional Hub bucket key prefix for persisted patch embeddings"
    )
    tile_overlap: int = Field(64, ge=0, description="Source-pixel overlap between tiles")
    tile_size: Optional[int] = Field(
        None, ge=64, description="Optional source-pixel tile size for tiled inference"
    )
    return_tile_results: bool = Field(
        False, description="Include per-tile scores and regions in addition to stitched results"
    )


@asynccontextmanager
async def lifespan(app: FastAPI):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model_dir = Path(os.environ.get("GEOTEXT_MODEL_DIR", "/repository"))
    source_dir = Path(os.environ.get("GEOTEXT_SOURCE_DIR", "/app/GeoText-1652"))
    model, tokenizer, config = load_model(source_dir, model_dir, device)
    app.state.runtime = {
        "config": config,
        "device": device,
        "model": model,
        "tokenizer": tokenizer,
    }
    yield


app = FastAPI(title="GeoText-1652", lifespan=lifespan)


def _pixel_box(box: List[float], tile: Dict[str, Any]) -> List[float]:
    """Convert a tile-local normalized cx/cy/w/h box into source pixel xyxy."""
    cx, cy, width, height = box
    x1 = max(tile["column"], tile["column"] + (cx - width / 2) * tile["width"])
    y1 = max(tile["row"], tile["row"] + (cy - height / 2) * tile["height"])
    x2 = min(tile["column"] + tile["width"], tile["column"] + (cx + width / 2) * tile["width"])
    y2 = min(tile["row"] + tile["height"], tile["row"] + (cy + height / 2) * tile["height"])
    return [float(x1), float(y1), float(x2), float(y2)]


def _iou(left: List[float], right: List[float]) -> float:
    x1 = max(left[0], right[0])
    y1 = max(left[1], right[1])
    x2 = min(left[2], right[2])
    y2 = min(left[3], right[3])
    intersection = max(0.0, x2 - x1) * max(0.0, y2 - y1)
    if not intersection:
        return 0.0
    left_area = max(0.0, left[2] - left[0]) * max(0.0, left[3] - left[1])
    right_area = max(0.0, right[2] - right[0]) * max(0.0, right[3] - right[1])
    return intersection / max(left_area + right_area - intersection, 1e-8)


def _stitch_boxes(
    tile_outputs: List[Tuple[Dict[str, Any], Dict[str, Any]]], image_width: int, image_height: int
) -> List[Dict[str, Any]]:
    candidates = []
    for tile, output in tile_outputs:
        score_by_query = {item["query"]: item["similarity"] for item in output["ranked_queries"]}
        for region in output.get("text_conditioned_boxes", []):
            pixel_box = _pixel_box(region["box"], tile)
            candidates.append(
                {
                    "box": pixel_box,
                    "query": region["query"],
                    "score": score_by_query[region["query"]],
                    "tile_index": tile["index"],
                }
            )

    stitched = []
    for query in sorted({candidate["query"] for candidate in candidates}):
        pending = sorted(
            (candidate for candidate in candidates if candidate["query"] == query),
            key=lambda candidate: candidate["score"],
            reverse=True,
        )
        while pending:
            selected = pending.pop(0)
            stitched.append(
                {
                    "query": query,
                    "score": selected["score"],
                    "source_pixel_xyxy": selected["box"],
                    "source_normalized_xyxy": [
                        selected["box"][0] / image_width,
                        selected["box"][1] / image_height,
                        selected["box"][2] / image_width,
                        selected["box"][3] / image_height,
                    ],
                    "tile_index": selected["tile_index"],
                }
            )
            pending = [
                candidate for candidate in pending if _iou(selected["box"], candidate["box"]) < 0.5
            ]
    return stitched


def _tiled_outputs(
    runtime: Dict[str, Any], image, request: InferenceRequest
) -> Dict[str, Any]:
    tiles = tile_image(image, request.tile_size, request.tile_overlap)
    tile_outputs = []
    for tile in tiles:
        output = model_outputs(
            runtime["model"], runtime["tokenizer"], runtime["config"], tile["image"],
            request.queries,
            runtime["device"],
            request.include_embeddings,
            request.include_bboxes,
            request.include_patch_embeddings or request.store_patch_embeddings,
        )
        tile_outputs.append((tile, output))

    best_by_query = {}
    for tile, output in tile_outputs:
        for item in output["ranked_queries"]:
            candidate = dict(item, tile_index=tile["index"])
            if (
                item["query"] not in best_by_query
                or item["similarity"] > best_by_query[item["query"]]["similarity"]
            ):
                best_by_query[item["query"]] = candidate
    result = {
        "ranked_queries": sorted(
            best_by_query.values(), key=lambda item: item["similarity"], reverse=True
        ),
        "tiling": {
            "tile_size": request.tile_size,
            "tile_overlap": request.tile_overlap,
            "tile_count": len(tiles),
            "similarity_stitching": "maximum tile similarity per query",
        },
    }
    if request.include_embeddings:
        weights = np.asarray(
            [tile["width"] * tile["height"] for tile, _ in tile_outputs], dtype=np.float32
        )
        vectors = np.asarray(
            [output["image_embedding"] for _, output in tile_outputs], dtype=np.float32
        )
        image_embedding = np.average(vectors, axis=0, weights=weights)
        image_embedding /= max(float(np.linalg.norm(image_embedding)), 1e-8)
        result["image_embedding"] = image_embedding.tolist()
        result["text_embeddings"] = tile_outputs[0][1]["text_embeddings"]
    if request.include_bboxes:
        result["stitched_text_conditioned_boxes"] = _stitch_boxes(
            tile_outputs, image.width, image.height
        )
    if request.include_patch_embeddings or request.store_patch_embeddings:
        patches = []
        for tile, output in tile_outputs:
            for patch in output["patch_embeddings"]["patches"]:
                x1, y1, x2, y2 = patch["source_pixel_xyxy"]
                patches.append(
                    {
                        **patch,
                        "tile_index": tile["index"],
                        "source_pixel_xyxy": [
                            x1 + tile["column"],
                            y1 + tile["row"],
                            x2 + tile["column"],
                            y2 + tile["row"],
                        ],
                    }
                )
        result["patch_embeddings"] = {
            "embedding_dimension": tile_outputs[0][1]["patch_embeddings"]["embedding_dimension"],
            "grid": "per_tile",
            "patches": patches,
        }
    if request.return_tile_results:
        result["tile_results"] = [
            {
                "tile_index": tile["index"],
                "source_pixel_window": [
                    tile["column"],
                    tile["row"],
                    tile["width"],
                    tile["height"],
                ],
                **output,
            }
            for tile, output in tile_outputs
        ]
    return result


@app.get("/health")
def health() -> Dict[str, str]:
    return {"status": "ok"}


@app.post("/")
@app.post("/infer")
def infer(request: InferenceRequest) -> Dict[str, Any]:
    try:
        image, image_metadata = fetch_rgb_geotiff(request.image_url)
        runtime = app.state.runtime
        result = {
            "image_url": request.image_url,
            "image_metadata": image_metadata,
            "device": str(runtime["device"]),
        }
        include_patches = request.include_patch_embeddings or request.store_patch_embeddings
        if request.tile_size is None:
            result.update(
                model_outputs(
                    runtime["model"],
                    runtime["tokenizer"],
                    runtime["config"],
                    image,
                    request.queries,
                    runtime["device"],
                    include_embeddings=request.include_embeddings,
                    include_bboxes=request.include_bboxes,
                    include_patch_embeddings=include_patches,
                )
            )
        else:
            result.update(_tiled_outputs(runtime, image, request))
        if request.store_patch_embeddings:
            result["patch_embeddings_storage"] = persist_patch_embeddings(
                image_url=request.image_url,
                patches=result["patch_embeddings"]["patches"],
                output_prefix=request.output_prefix,
            )
            if not request.include_patch_embeddings:
                result.pop("patch_embeddings")
        return result
    except Exception as error:
        raise HTTPException(status_code=422, detail=str(error)) from error