File size: 8,159 Bytes
fee9d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dda57c
fee9d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61a2db
fee9d25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61a2db
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
"""LEVIRDetNet: universal remote sensing object detection (159 categories).

Runs the authors' LEVIRDetNet-159 checkpoint (DEIMv2 + DINOv3 ViT-S/16 backbone,
GSD-guided queries, hierarchy-aware head) on an aerial/satellite image and draws
the predicted bounding boxes. Mirrors the reference `levir_image_demo.py` path:
1024x1024 resize, single image per batch, hierarchy-collapsed scores, boxes in
original-image coordinates.
"""
import os

# ZeroGPU: import spaces before anything CUDA-touching.
import spaces

import contextlib
import sys
import types

# mmcv-lite has no compiled CUDA ops. The vendored mmdet imports mmcv.ops
# symbols at import time but never calls the CUDA kernels on this model's
# inference path (decoder uses the pure-PyTorch deformable attention; the
# head applies no NMS). Stub the ext loader so imports resolve.
class _ExtStub(types.ModuleType):
    def __getattr__(self, name):
        if name.startswith('__') and name.endswith('__'):
            raise AttributeError(name)

        def _placeholder(*args, **kwargs):
            raise RuntimeError(
                f'mmcv CUDA op {name!r} called; not available in this no-ops build')

        return _placeholder


sys.modules.setdefault('mmcv._ext', _ExtStub('mmcv._ext'))

import glob
import json
import time
from pathlib import Path

import gradio as gr
import numpy as np
import torch

APP_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(APP_DIR))

from levir_net import build_model, load_image, singleton_prior, inactive_query_guard

from mmcv.transforms import Compose
from mmengine.dataset import pseudo_collate
from mmengine.registry import init_default_scope
from mmdet.registry import VISUALIZERS
from mmdet.utils import register_all_modules

MODEL_REPO = 'yangqinzhe/LEVIRDetNet-159'
CKPT_NAME = 'best_coco_weighted_bbox_mAP_epoch_110_159class.pth'
CONFIG_PATH = str(APP_DIR / 'configs/levirdetnet/levirdetnet-159class.py')

register_all_modules(init_default_scope=True)
init_default_scope('mmdet')

print(f'[app] downloading checkpoint from {MODEL_REPO}/{CKPT_NAME} ...')
from huggingface_hub import hf_hub_download
CKPT_PATH = hf_hub_download(MODEL_REPO, CKPT_NAME)
print(f'[app] checkpoint at {CKPT_PATH}')

print('[app] building LEVIRDetNet-159 ...')
MODEL, CFG, CLASSES = build_model(APP_DIR, CKPT_PATH, device='cuda')
MODEL = MODEL.to('cuda')
MODEL.eval()
print(f'[app] model ready: {len(CLASSES)} classes')

# Deterministic 159-class palette (mmdet 'random' palette seeds with 42).
from mmdet.visualization.palette import get_palette
PALETTE = get_palette('random', len(CLASSES))
MODEL.dataset_meta['palette'] = PALETTE

SAMPLE_DIR = APP_DIR / 'samples'
SAMPLE_IMAGES = sorted(SAMPLE_DIR.glob('*.jpg'))


def _draw(image_path, labels, scores, boxes, score_thr):
    """Draw boxes with mmdet's own DetLocalVisualizer (authors' visualization path)."""
    from mmengine.structures import InstanceData
    from mmdet.structures import DetDataSample

    import cv2
    img = cv2.imread(str(image_path))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    keep = [i for i, s in enumerate(scores) if s >= score_thr]
    instances = InstanceData()
    instances.bboxes = torch.tensor([boxes[i] for i in keep], dtype=torch.float32)
    instances.scores = torch.tensor([scores[i] for i in keep], dtype=torch.float32)
    instances.labels = torch.tensor([labels[i] for i in keep], dtype=torch.long)

    sample = DetDataSample()
    sample.pred_instances = instances
    sample.set_metainfo(dict(img_path=str(image_path), scale_factor=np.array([1.0, 1.0, 1.0, 1.0])))

    vis = VISUALIZERS.build(dict(type='DetLocalVisualizer', name='levir', vis_backends=[]))
    vis.dataset_meta = dict(classes=CLASSES, palette=PALETTE)
    vis.set_image(img)
    vis.add_datasample('detection', img, sample, draw_gt=False, show=False,
                       pred_score_thr=score_thr, out_file=None)
    return vis.get_image()


@spaces.GPU(duration=30)
def detect(image, score_threshold=0.3, max_boxes=300):
    """Detect objects in a remote sensing image with LEVIRDetNet.

    Args:
        image: input aerial/satellite image (any size; resized to 1024x1024 internally).
        score_threshold: minimum confidence score to draw/report a box.
        max_boxes: maximum detections drawn (highest-scoring kept).

    Returns:
        (annotated image, detections summary + full list as JSON)
    """
    if image is None:
        raise gr.Error('Please upload an image first.')
    t0 = time.time()
    # Gradio hands us a numpy array (RGB). Save to a temp file so the mmdet
    # LoadImageFromFile pipeline handles it exactly like the reference demo.
    import tempfile
    with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as f:
        # Gradio >= 4 numpy arrays are RGB; cv2.imwrite wants BGR.
        import cv2
        cv2.imwrite(f.name, cv2.cvtColor(image, cv2.COLOR_RGB2BGR))
        tmp_path = f.name
    try:
        data = load_image(tmp_path)
        batched = pseudo_collate([data])
        with torch.no_grad(), singleton_prior(MODEL, torch), inactive_query_guard(MODEL, torch):
            outputs = MODEL.test_step(batched)
        sample = outputs[0] if isinstance(outputs[0], dict) else outputs[0]
        pred = sample['pred_instances'] if isinstance(sample, dict) else sample.pred_instances
        labels = pred.labels.detach().cpu().tolist()
        scores = pred.scores.detach().cpu().tolist()
        boxes = pred.bboxes.detach().cpu().tolist()

        vis_img = _draw(tmp_path, labels, scores, boxes, score_threshold)
    finally:
        with contextlib.suppress(Exception):
            os.unlink(tmp_path)

    keep = [i for i, s in enumerate(scores) if s >= score_threshold][:max_boxes]
    dets = [
        dict(label=CLASSES[l], label_id=int(l), score=round(s, 4),
             bbox=[round(v, 1) for v in b])
        for i, (l, s, b) in enumerate(zip(labels, scores, boxes)) if i in set(keep)
    ]
    elapsed = time.time() - t0
    summary = dict(num_detections=len(dets), classes_present=sorted({d['label'] for d in dets}),
                   score_threshold=score_threshold, elapsed_seconds=round(elapsed, 2))
    return vis_img, json.dumps(dict(summary=summary, detections=dets), ensure_ascii=False, indent=2)


CSS = '''
.dark .gradio-container, .dark {
  --bg: #0b0d12 !important;
  --button-primary-bg-hover: #6b7cff !important;
}
.gradio-container .prose h1 { font-size: 26px; }
'''

with gr.Blocks() as demo:
    gr.HTML('''
<div style="display:flex;align-items:center;gap:12px">
  <div style="font-size:44px;line-height:1">🛰️</div>
  <div>
    <h1 style="margin:0;font-size:26px">LEVIRDetNet — Universal Remote Sensing Object Detection</h1>
    <p style="margin:2px 0 0;font-size:14px;opacity:.75">
      159-category aerial detection with GSD-guided queries and a hierarchy-aware head
      (DEIMv2 + DINOv3 ViT-S/16). From the paper
      <a href="https://huggingface.co/papers/2606.25312" target="_blank">LEVIRDet: A Million-Scale 159-Category Dataset and Foundation Model for Universal Remote Sensing Object Detection</a>.
    </p>
  </div>
</div>
''')
    with gr.Row():
        with gr.Column():
            image_in = gr.Image(type='numpy', label='Aerial / satellite image', height=420)
            score_thr = gr.Slider(0.05, 0.95, value=0.3, step=0.05, label='Score threshold')
            max_boxes = gr.Slider(1, 300, value=300, step=1, label='Max detections shown')
            run_btn = gr.Button('Detect', variant='primary')
        with gr.Column():
            image_out = gr.Image(type='numpy', label='Detections', height=420)
            dets_json = gr.JSON(label='Detections (label, score, bbox [x1 y1 x2 y2])')
    gr.Examples(
        examples=[[str(p)] for p in SAMPLE_IMAGES],
        inputs=[image_in],
        fn=detect,
        outputs=[image_out, dets_json],
        cache_examples=True,
        cache_mode='lazy',
        label='Example images (from the LEVIRDet release)',
    )
    run_btn.click(detect, inputs=[image_in, score_thr, max_boxes], outputs=[image_out, dets_json])

if __name__ == '__main__':
    demo.launch(mcp_server=True, theme=gr.themes.Citrus(), css=CSS)