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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
"""SynthForest: canopy height + tree crown delineation from overhead RGB.

Runs the SynthForest models (frozen DINOv3 ViT-L/16 backbone) released with
"SynthForest: A Multi-Task Synthetic Dataset for Real-World Forest Vision"
(Novoselova, Song, Yokoya):

  * Syn-20  β€” DINOv3 + DPT canopy-height model (`syn20.pth`)
  * HF+MT   β€” Mask R-CNN crown delineator with height fusion + Mean Teacher
              (`maskrcnn_syn_hf_mt.pth`), the best model in the paper's Table 5.

The inference path replicates the reference implementation in
https://github.com/iaroslavanovoselova/SynthForest exactly: border-black valid
mask, 0.05m -> 0.20m BOX downscale, center pad to a /16 multiple, ImageNet
normalisation, height precompute, 4-channel [RGB, height] detector input,
eval resize to 992, and valid-fraction filtering of detections.
"""

from __future__ import annotations

import math
import os
from collections import OrderedDict, deque
from typing import Any

import spaces  # MUST be imported before torch

import gradio as gr
import numpy as np
import torch
import torch.nn.functional as F
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision.models.detection import MaskRCNN
from torchvision.models.detection.anchor_utils import AnchorGenerator
from torchvision.models.detection.transform import GeneralizedRCNNTransform
from torchvision.ops import MultiScaleRoIAlign

# ---------------------------------------------------------------------------
# Hyperparameters (from the checkpoint-embedded training configs)
# ---------------------------------------------------------------------------

DINOV3_REPO = "camenduru/dinov3-vitl16-pretrain-lvd1689m"
HEIGHT_CKPT = "syn20.pth"
DETECTOR_CKPT = "maskrcnn_syn_hf_mt.pth"

IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)

# Syn-20 height model
HEIGHT_FEATURE_LAYERS = (5, 11, 17, 23)
HEIGHT_FEATURE_DIM = 256
HEIGHT_OUT_CHANNELS = (256, 512, 1024, 1024)

# Height -> detector fusion
SOURCE_GSD_M = 0.05
TARGET_GSD_M = 0.20
HEIGHT_CLIP_MIN_M = 0.0
HEIGHT_CLIP_MAX_M = 60.0
HEIGHT_MEAN_M = 30.0
HEIGHT_STD_M = 30.0
FUSION_LEVELS = ("p8", "p16")
FUSION_INIT_SCALE = 0.1
FUSION_HIDDEN = 64

# Detector
BACKBONE_OUT_CHANNELS = 256
NUM_CLASSES = 1
ANCHOR_SIZES = ((24, 34, 48), (68, 96, 136), (192, 272, 384))
ASPECT_RATIOS = ((0.75, 1.0, 1.25),) * 3
BOX_SCORE_THRESH = 0.05
BOX_NMS_THRESH = 0.5
BOX_DETECTIONS_PER_IMG = 500
EVAL_MIN_SIZE = 992
MAX_SIZE = 992
TRAIN_MIN_SIZES = (512, 608, 704, 800, 896, 992)
MASK_PROBABILITY_THRESHOLD = 0.5
PREDICTION_MIN_VALID_FRACTION = 0.6

PATCH_SIZE = 16
EMBED_DIM = 1024
PYRAMID_FEATURE_NAMES = ("p8", "p16", "p32")
FROZEN_BACKBONE_PREFIXES = ("backbone.dinov3.", "dinov3.")

MAX_PIXELS = 4_000_000  # 4 MP safety cap keeps ZeroGPU calls short


# ---------------------------------------------------------------------------
# Valid masks (reference: synthforest/training/valid_masks.py)
# ---------------------------------------------------------------------------


def border_black_valid_mask(image: Image.Image, tolerance: int = 0) -> np.ndarray:
    array = np.asarray(image.convert("RGB"))
    black = np.all(array <= int(tolerance), axis=-1)
    if not bool(black.any()):
        return np.ones(black.shape, dtype=bool)
    seed = np.zeros(black.shape, dtype=bool)
    seed[0, :] = black[0, :]
    seed[-1, :] = black[-1, :]
    seed[:, 0] = black[:, 0]
    seed[:, -1] = black[:, -1]
    if not bool(seed.any()):
        return np.ones(black.shape, dtype=bool)
    try:
        from scipy.ndimage import binary_propagation

        invalid = np.asarray(binary_propagation(seed, mask=black), dtype=bool)
    except ImportError:
        invalid = _flood_fill(black, seed)
    return ~invalid


def _flood_fill(candidate: np.ndarray, seed: np.ndarray) -> np.ndarray:
    height, width = candidate.shape
    connected = seed.copy()
    pending = deque(zip(*np.nonzero(seed)))
    while pending:
        row, col = pending.popleft()
        for next_row, next_col in (
            (row - 1, col),
            (row + 1, col),
            (row, col - 1),
            (row, col + 1),
        ):
            if (
                0 <= next_row < height
                and 0 <= next_col < width
                and candidate[next_row, next_col]
                and not connected[next_row, next_col]
            ):
                connected[next_row, next_col] = True
                pending.append((next_row, next_col))
    return connected


def fill_invalid_pixels(image: Image.Image, valid_mask: np.ndarray) -> Image.Image:
    if bool(valid_mask.all()):
        return image
    array = np.asarray(image.convert("RGB")).copy()
    fill = np.asarray(
        [round(float(value) * 255.0) for value in IMAGENET_MEAN], dtype=np.uint8
    )
    array[~valid_mask] = fill
    return Image.fromarray(array)


def box_valid_fractions(valid_mask: torch.Tensor, boxes: torch.Tensor) -> torch.Tensor:
    if boxes.ndim != 2 or boxes.shape[-1] != 4 or boxes.numel() == 0:
        return boxes.new_zeros((0,)) if boxes.numel() == 0 else boxes.new_ones((boxes.shape[0],))
    if valid_mask.ndim == 3 and valid_mask.shape[0] == 1:
        valid_mask = valid_mask[0]
    valid_mask = valid_mask.to(device=boxes.device, dtype=torch.bool)
    if bool(valid_mask.all()):
        return boxes.new_ones((boxes.shape[0],))
    height, width = valid_mask.shape
    x1 = boxes[:, 0].floor().clamp(0, width).to(torch.int64)
    y1 = boxes[:, 1].floor().clamp(0, height).to(torch.int64)
    x2 = boxes[:, 2].ceil().clamp(0, width).to(torch.int64)
    y2 = boxes[:, 3].ceil().clamp(0, height).to(torch.int64)
    integral = torch.nn.functional.pad(
        valid_mask.to(torch.int64).cumsum(0).cumsum(1), (1, 0, 1, 0)
    )
    valid_area = integral[y2, x2] - integral[y1, x2] - integral[y2, x1] + integral[y1, x1]
    box_area = (x2 - x1) * (y2 - y1)
    fractions = valid_area.to(boxes.dtype) / box_area.clamp_min(1).to(boxes.dtype)
    return torch.where(box_area > 0, fractions, torch.zeros_like(fractions))


def filter_detections_by_valid_masks(
    detections: list[dict[str, Any]],
    valid_masks: list[torch.Tensor],
    min_valid_fraction: float,
) -> list[dict[str, Any]]:
    filtered = []
    for detection, valid_mask in zip(detections, valid_masks):
        boxes = detection.get("boxes")
        if not torch.is_tensor(boxes):
            filtered.append(detection)
            continue
        fractions = box_valid_fractions(valid_mask, boxes)
        keep = fractions >= float(min_valid_fraction)
        filtered.append(
            {
                key: (
                    value[keep]
                    if torch.is_tensor(value)
                    and value.ndim > 0
                    and value.shape[0] == keep.shape[0]
                    else value
                )
                for key, value in detection.items()
            }
        )
    return filtered


# ---------------------------------------------------------------------------
# Height model (reference: synthforest/training/models/height.py)
# ---------------------------------------------------------------------------


class ResidualConvUnit(nn.Module):
    def __init__(self, features: int, use_batch_norm: bool) -> None:
        super().__init__()
        self.activation = nn.ReLU(inplace=False)
        self.conv1 = nn.Conv2d(features, features, 3, 1, 1)
        self.conv2 = nn.Conv2d(features, features, 3, 1, 1)
        self.norm1 = _norm_layer(features, use_batch_norm)
        self.norm2 = _norm_layer(features, use_batch_norm)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        out = self.activation(x)
        out = self.norm1(self.conv1(out))
        out = self.activation(out)
        out = self.norm2(self.conv2(out))
        return out + x


class FeatureFusionBlock(nn.Module):
    def __init__(self, features: int, use_batch_norm: bool) -> None:
        super().__init__()
        self.residual1 = ResidualConvUnit(features, use_batch_norm)
        self.residual2 = ResidualConvUnit(features, use_batch_norm)
        self.out_conv = nn.Conv2d(features, features, 1)

    def forward(
        self,
        x: torch.Tensor,
        skip: torch.Tensor | None = None,
        *,
        size: tuple[int, int] | None = None,
    ) -> torch.Tensor:
        if skip is not None:
            x = x + self.residual1(skip)
        x = self.residual2(x)
        if size is None:
            x = F.interpolate(x, scale_factor=2.0, mode="bilinear", align_corners=False)
        else:
            x = F.interpolate(x, size=size, mode="bilinear", align_corners=False)
        return self.out_conv(x)


class DPTHeightDecoder(nn.Module):
    def __init__(
        self,
        *,
        in_channels: int,
        features: int,
        out_channels: tuple[int, ...],
        use_batch_norm: bool,
        output_channels: int = 1,
    ) -> None:
        super().__init__()
        self.projects = nn.ModuleList(
            [nn.Conv2d(in_channels, c, kernel_size=1) for c in out_channels]
        )
        self.resize_layers = nn.ModuleList(
            [
                nn.ConvTranspose2d(out_channels[0], out_channels[0], 4, 4),
                nn.ConvTranspose2d(out_channels[1], out_channels[1], 2, 2),
                nn.Identity(),
                nn.Conv2d(out_channels[3], out_channels[3], 3, 2, 1),
            ]
        )
        self.layer1_rn = nn.Conv2d(out_channels[0], features, 3, padding=1, bias=False)
        self.layer2_rn = nn.Conv2d(out_channels[1], features, 3, padding=1, bias=False)
        self.layer3_rn = nn.Conv2d(out_channels[2], features, 3, padding=1, bias=False)
        self.layer4_rn = nn.Conv2d(out_channels[3], features, 3, padding=1, bias=False)
        self.refinenet1 = FeatureFusionBlock(features, use_batch_norm)
        self.refinenet2 = FeatureFusionBlock(features, use_batch_norm)
        self.refinenet3 = FeatureFusionBlock(features, use_batch_norm)
        self.refinenet4 = FeatureFusionBlock(features, use_batch_norm)
        self.output_conv = nn.Sequential(
            nn.Conv2d(features, features // 2, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(features // 2, 32, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(32, int(output_channels), 1),
        )

    def forward(self, feature_maps: list[torch.Tensor], output_size) -> torch.Tensor:
        resized = [
            resize(project(feature))
            for feature, project, resize in zip(feature_maps, self.projects, self.resize_layers)
        ]
        layer1, layer2, layer3, layer4 = resized
        layer1_rn = self.layer1_rn(layer1)
        layer2_rn = self.layer2_rn(layer2)
        layer3_rn = self.layer3_rn(layer3)
        layer4_rn = self.layer4_rn(layer4)
        path4 = self.refinenet4(layer4_rn, size=layer3_rn.shape[-2:])
        path3 = self.refinenet3(path4, layer3_rn, size=layer2_rn.shape[-2:])
        path2 = self.refinenet2(path3, layer2_rn, size=layer1_rn.shape[-2:])
        path1 = self.refinenet1(path2, layer1_rn)
        out = self.output_conv(path1)
        return F.interpolate(out, size=output_size, mode="bilinear", align_corners=False)


class DinoV3DPTHeightModel(nn.Module):
    """DINOv3 encoder + DPT height decoder (returns meters)."""

    def __init__(self, dinov3: nn.Module) -> None:
        super().__init__()
        self.dinov3 = dinov3
        self.patch_size = PATCH_SIZE
        self.feature_layers = list(HEIGHT_FEATURE_LAYERS)
        self.decoder = DPTHeightDecoder(
            in_channels=EMBED_DIM,
            features=HEIGHT_FEATURE_DIM,
            out_channels=list(HEIGHT_OUT_CHANNELS),
            use_batch_norm=False,
            output_channels=1,
        )

    def forward(self, images: torch.Tensor) -> dict[str, torch.Tensor]:
        with torch.no_grad():
            try:
                outputs = self.dinov3(
                    pixel_values=images,
                    output_hidden_states=True,
                    return_dict=True,
                )
            except TypeError:
                outputs = self.dinov3(
                    images, output_hidden_states=True, return_dict=True
                )
        hidden_states = getattr(outputs, "hidden_states", None)
        if hidden_states is None and isinstance(outputs, dict):
            hidden_states = outputs.get("hidden_states")
        if hidden_states is None:
            raise RuntimeError("DINOv3 did not return hidden_states; cannot decode height.")
        feature_maps = []
        for layer in self.feature_layers:
            tokens = _tokens_to_feature_map(
                hidden_states[layer + 1], images, self.patch_size
            )
            feature_maps.append(tokens)
        output = self.decoder(feature_maps, output_size=tuple(images.shape[-2:]))
        return {"height": output}


def _norm_layer(features: int, use_batch_norm: bool) -> nn.Module:
    if use_batch_norm:
        return nn.BatchNorm2d(features)
    groups = 32 if features % 32 == 0 else 1
    return nn.GroupNorm(groups, features)


def _tokens_to_feature_map(
    patch_tokens: torch.Tensor,
    images: torch.Tensor,
    patch_size: int,
) -> torch.Tensor:
    if patch_tokens.ndim == 4:
        return patch_tokens
    batch_size, num_tokens, channels = patch_tokens.shape
    height = images.shape[-2] // patch_size
    width = images.shape[-1] // patch_size
    expected_tokens = height * width
    if expected_tokens <= 0:
        raise ValueError(
            f"Input shape {tuple(images.shape[-2:])} is smaller than patch_size={patch_size}."
        )
    if num_tokens > expected_tokens:
        patch_tokens = patch_tokens[:, num_tokens - expected_tokens :, :]
        num_tokens = expected_tokens
    if expected_tokens != num_tokens:
        side = int(math.sqrt(num_tokens))
        if side * side != num_tokens:
            raise ValueError(
                f"Cannot reshape {num_tokens} DINOv3 tokens into a feature map."
            )
        height = width = side
    return patch_tokens.transpose(1, 2).reshape(batch_size, channels, height, width).contiguous()


# ---------------------------------------------------------------------------
# Detector (reference: synthforest/training/models/detector.py)
# ---------------------------------------------------------------------------


def _conv_norm_relu(
    in_channels: int,
    out_channels: int,
    kernel_size: int,
    stride: int = 1,
) -> nn.Sequential:
    padding = kernel_size // 2
    groups = 32 if out_channels % 32 == 0 else 1
    return nn.Sequential(
        nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding),
        nn.GroupNorm(groups, out_channels),
        nn.ReLU(inplace=True),
    )


def _resize_height_for_feature(height: torch.Tensor, size) -> torch.Tensor:
    if tuple(height.shape[-2:]) == tuple(size):
        return height
    in_h, in_w = int(height.shape[-2]), int(height.shape[-1])
    out_h, out_w = int(size[0]), int(size[1])
    if out_h <= in_h and out_w <= in_w:
        return F.interpolate(height, size=size, mode="area")
    return F.interpolate(height, size=size, mode="bilinear", align_corners=False)


class HeightPyramidFusion(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.levels = FUSION_LEVELS
        self.encoder = nn.Sequential(
            _conv_norm_relu(1, FUSION_HIDDEN, 3),
            _conv_norm_relu(FUSION_HIDDEN, BACKBONE_OUT_CHANNELS, 3),
        )
        self.level_scales = nn.ParameterDict(
            {
                level: nn.Parameter(torch.tensor(float(FUSION_INIT_SCALE)))
                for level in self.levels
            }
        )

    def forward(
        self, features: "OrderedDict[str, torch.Tensor]", height: torch.Tensor
    ) -> "OrderedDict[str, torch.Tensor]":
        fused = OrderedDict(features)
        for level in self.levels:
            target = fused[level]
            resized = _resize_height_for_feature(height, target.shape[-2:])
            encoded = self.encoder(resized)
            fused[level] = target + self.level_scales[level].to(dtype=target.dtype) * encoded
        return fused


class DinoV3FeatureBackbone(nn.Module):
    def __init__(self, dinov3: nn.Module) -> None:
        super().__init__()
        self.dinov3 = dinov3
        self.patch_size = PATCH_SIZE
        self.input_projection = _conv_norm_relu(EMBED_DIM, BACKBONE_OUT_CHANNELS, 1)
        self.p8_smooth = _conv_norm_relu(BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3)
        self.p16_smooth = _conv_norm_relu(BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3)
        self.p32_downsample = _conv_norm_relu(
            BACKBONE_OUT_CHANNELS, BACKBONE_OUT_CHANNELS, 3, stride=2
        )
        self.height_fusion = HeightPyramidFusion()
        self.out_channels = BACKBONE_OUT_CHANNELS

    def forward(self, images: torch.Tensor) -> "OrderedDict[str, torch.Tensor]":
        height = images[:, 3:4]
        images = images[:, :3]
        with torch.no_grad():
            try:
                raw = self.dinov3(pixel_values=images, return_dict=True)
            except TypeError:
                raw = self.dinov3(images)
        if isinstance(raw, dict):
            last_hidden = raw.get("last_hidden_state")
        else:
            last_hidden = getattr(raw, "last_hidden_state", None)
        if last_hidden is None:
            raise RuntimeError("DINOv3 did not return last_hidden_state.")
        feature_map = _tokens_to_feature_map(last_hidden, images, self.patch_size)
        base = self.input_projection(feature_map)
        p8 = self.p8_smooth(
            F.interpolate(base, scale_factor=2.0, mode="bilinear", align_corners=False)
        )
        p16 = self.p16_smooth(base)
        p32 = self.p32_downsample(base)
        features = OrderedDict([("p8", p8), ("p16", p16), ("p32", p32)])
        return self.height_fusion(features, height)


class TrainEvalResizeTransform(GeneralizedRCNNTransform):
    """Normalise [RGB, height-m] and resize to the fixed eval size (992)."""

    def __init__(self) -> None:
        image_mean = list(IMAGENET_MEAN) + [HEIGHT_MEAN_M]
        image_std = list(IMAGENET_STD) + [HEIGHT_STD_M]
        super().__init__(
            min_size=TRAIN_MIN_SIZES,
            max_size=MAX_SIZE,
            image_mean=image_mean,
            image_std=image_std,
        )
        self.train_min_sizes = TRAIN_MIN_SIZES
        self.eval_min_size = EVAL_MIN_SIZE

    def normalize(self, image):
        dtype = image.dtype
        device = image.device
        rgb_mean = torch.as_tensor(self.image_mean[:3], dtype=dtype, device=device)
        rgb_std = torch.as_tensor(self.image_std[:3], dtype=dtype, device=device)
        rgb = (image[:3] - rgb_mean[:, None, None]) / rgb_std[:, None, None]
        height = image[3:4].clamp(HEIGHT_CLIP_MIN_M, HEIGHT_CLIP_MAX_M)
        height = (height - HEIGHT_MEAN_M) / max(HEIGHT_STD_M, 1e-6)
        return torch.cat([rgb, height], dim=0)

    def resize(self, image, target):
        original_min_size = self.min_size
        self.min_size = self.train_min_sizes if self.training else (self.eval_min_size,)
        try:
            return super().resize(image, target)
        finally:
            self.min_size = original_min_size


def _build_detector(dinov3: nn.Module) -> MaskRCNN:
    backbone = DinoV3FeatureBackbone(dinov3)
    anchor_generator = AnchorGenerator(sizes=ANCHOR_SIZES, aspect_ratios=ASPECT_RATIOS)
    box_roi_pool = MultiScaleRoIAlign(
        featmap_names=list(PYRAMID_FEATURE_NAMES), output_size=7, sampling_ratio=2
    )
    mask_roi_pool = MultiScaleRoIAlign(
        featmap_names=list(PYRAMID_FEATURE_NAMES), output_size=14, sampling_ratio=2
    )
    model = MaskRCNN(
        backbone,
        num_classes=NUM_CLASSES + 1,
        rpn_anchor_generator=anchor_generator,
        box_roi_pool=box_roi_pool,
        mask_roi_pool=mask_roi_pool,
        min_size=TRAIN_MIN_SIZES,
        max_size=MAX_SIZE,
        image_mean=list(IMAGENET_MEAN),
        image_std=list(IMAGENET_STD),
        box_score_thresh=BOX_SCORE_THRESH,
        box_nms_thresh=BOX_NMS_THRESH,
        box_detections_per_img=BOX_DETECTIONS_PER_IMG,
    )
    model.transform = TrainEvalResizeTransform()
    return model


# ---------------------------------------------------------------------------
# Checkpoint loading
# ---------------------------------------------------------------------------


def load_trained_state_dict(model: nn.Module, state_dict: dict) -> None:
    result = model.load_state_dict(state_dict, strict=False)
    missing = [
        key
        for key in result.missing_keys
        if not key.startswith(FROZEN_BACKBONE_PREFIXES) or "lora" in key.lower()
    ]
    if missing or result.unexpected_keys:
        raise RuntimeError(
            "Checkpoint state does not match the model: "
            f"missing={missing[:5]}, unexpected={list(result.unexpected_keys)[:5]}"
        )


def _resolve_state_dict(checkpoint: dict) -> dict:
    for key in ("model_state_dict", "ema_teacher_state_dict", "student_state_dict"):
        value = checkpoint.get(key)
        if isinstance(value, dict) and value:
            return value
    raise RuntimeError("Checkpoint does not contain a model state dict.")


# ---------------------------------------------------------------------------
# Model loading (module scope, eager, on cuda)
# ---------------------------------------------------------------------------

print("Loading DINOv3 ViT-L/16 backbone from", DINOV3_REPO, flush=True)
from transformers import AutoModel

_dinov3 = AutoModel.from_pretrained(DINOV3_REPO, trust_remote_code=True)
_dinov3.eval()
for _p in _dinov3.parameters():
    _p.requires_grad = False

print("Loading Syn-20 height model", flush=True)
_height_model = DinoV3DPTHeightModel(_dinov3)
_height_ckpt = torch.load(
    hf_hub_download("novoselova/synthforest", HEIGHT_CKPT), map_location="cpu", weights_only=False
)
load_trained_state_dict(_height_model, _resolve_state_dict(_height_ckpt))
del _height_ckpt

print("Loading HF+MT crown detector", flush=True)
_detector = _build_detector(_dinov3)
_detector_ckpt = torch.load(
    hf_hub_download("novoselova/synthforest", DETECTOR_CKPT),
    map_location="cpu",
    weights_only=False,
)
load_trained_state_dict(_detector, _resolve_state_dict(_detector_ckpt))
del _detector_ckpt

del _dinov3

device = "cuda" if torch.cuda.is_available() else "cpu"
_height_model = _height_model.to(device).eval()
_detector = _detector.to(device).eval()
print(f"Models on {device}", flush=True)


# ---------------------------------------------------------------------------
# Inference pipeline (reference: benchmarking/inference.py + detector_precompute.py)
# ---------------------------------------------------------------------------


def _predict_height_map(image: Image.Image, valid_mask: np.ndarray) -> np.ndarray:
    """Syn-20 height in meters at the input resolution."""
    image = fill_invalid_pixels(image.convert("RGB"), valid_mask)
    original_size = image.size  # (W, H)
    scale = SOURCE_GSD_M / TARGET_GSD_M
    low_size = (
        max(1, int(round(original_size[0] * scale))),
        max(1, int(round(original_size[1] * scale))),
    )
    low_image = image.resize(low_size, Image.Resampling.BOX)
    low_mask = np.asarray(
        Image.fromarray(valid_mask.astype(np.uint8) * 255).resize(
            low_size, Image.Resampling.BOX
        )
    ) > 0
    # Center-pad to a /16 multiple with the ImageNet-mean fill colour.
    multiple = PATCH_SIZE
    width, height = low_image.size
    padded_width = int(math.ceil(width / multiple) * multiple)
    padded_height = int(math.ceil(height / multiple) * multiple)
    crop_left = (padded_width - width) // 2
    crop_top = (padded_height - height) // 2
    if padded_width == width and padded_height == height:
        padded_image = low_image
    else:
        fill = tuple(int(round(float(v) * 255.0)) for v in IMAGENET_MEAN)
        canvas = Image.new("RGB", (padded_width, padded_height), fill)
        canvas.paste(low_image, (crop_left, crop_top))
        padded_image = canvas

    array = np.asarray(padded_image.convert("RGB"), dtype=np.float32) / 255.0
    padded_mask = np.zeros((padded_height, padded_width), dtype=bool)
    padded_mask[crop_top : crop_top + low_size[1], crop_left : crop_left + low_size[0]] = low_mask
    if not bool(padded_mask.all()):
        array[~padded_mask] = np.asarray(IMAGENET_MEAN, dtype=np.float32)
    tensor = torch.from_numpy(array).permute(2, 0, 1).contiguous()
    mean = torch.as_tensor(IMAGENET_MEAN, dtype=tensor.dtype).view(-1, 1, 1)
    std = torch.as_tensor(IMAGENET_STD, dtype=tensor.dtype).view(-1, 1, 1).clamp_min(1e-6)
    tensor = (tensor - mean) / std

    with torch.no_grad():
        prediction = _height_model(tensor.unsqueeze(0).to(device))["height"]
    prediction = prediction.clamp_min(0.0)
    if prediction.shape[-2:] != tensor.shape[-2:]:
        prediction = F.interpolate(
            prediction, size=tensor.shape[-2:], mode="bilinear", align_corners=False
        )
    crop = prediction[
        :, :, crop_top : crop_top + low_size[1], crop_left : crop_left + low_size[0]
    ]
    upsampled = F.interpolate(
        crop,
        size=(original_size[1], original_size[0]),
        mode="bilinear",
        align_corners=False,
    )
    height_map = (
        upsampled.squeeze(0).squeeze(0).detach().cpu().numpy().astype(np.float32)
    )
    return np.where(valid_mask, height_map, 0.0).astype(np.float32)


def _detector_input(image: Image.Image, valid_mask: np.ndarray, height_map: np.ndarray):
    """[RGB(0-1), height(m)] tensor + valid mask, matching the reference dataset."""
    array = np.asarray(image.convert("RGB"), dtype=np.float32, copy=True) / 255.0
    if not bool(valid_mask.all()):
        array[~valid_mask] = np.asarray(IMAGENET_MEAN, dtype=np.float32)
    rgb = torch.from_numpy(array).permute(2, 0, 1).contiguous()
    height = torch.from_numpy(np.ascontiguousarray(height_map, dtype=np.float32)).unsqueeze(0)
    return torch.cat([rgb, height], dim=0)


def _colourise_height(height_map: np.ndarray, valid_mask: np.ndarray) -> Image.Image:
    """Viridis-style colour ramp for the height map."""
    mask = valid_mask & (height_map > 0.05)
    if not mask.any():
        blank = np.zeros((height_map.shape[0], height_map.shape[1], 3), dtype=np.uint8)
        return Image.fromarray(blank)
    vmin, vmax = float(height_map[mask].min()), float(height_map[mask].max())
    if vmax - vmin < 1e-6:
        vmax = vmin + 1e-6
    t = (height_map - vmin) / (vmax - vmin)
    t[~valid_mask] = 0.0
    stops = np.array(
        [
            [68, 1, 84],
            [72, 40, 120],
            [62, 132, 146],
            [49, 104, 142],
            [56, 189, 40],
            [127, 255, 0],
            [253, 231, 37],
        ],
        dtype=np.float32,
    )
    n = len(stops) - 1
    positions = t.reshape(-1) * n
    idx = np.clip(np.floor(positions).astype(np.int64), 0, n - 1)
    frac = positions - idx
    colours = stops[idx] * (1.0 - frac[:, None]) + stops[idx + 1] * frac[:, None]
    rgb = colours.reshape(height_map.shape[0], height_map.shape[1], 3)
    rgb[~valid_mask] = np.array([0, 0, 0], dtype=np.float32)
    return Image.fromarray(np.clip(rgb, 0, 255).astype(np.uint8))


def _draw_detections(
    image: Image.Image,
    boxes: list[list[float]],
    scores: list[float],
    masks: np.ndarray,
    valid_mask: np.ndarray,
) -> Image.Image:
    """Draw crown masks (score-coloured fill) + boxes + score labels on the RGB."""
    from PIL import ImageDraw

    base = np.asarray(image.convert("RGB"), dtype=np.float32)
    if len(masks):
        colour_sum = np.zeros(base.shape, dtype=np.float32)
        count = np.zeros(valid_mask.shape, dtype=np.float32)
        for score, mask in zip(scores, masks):
            binary = mask & valid_mask
            if not binary.any():
                continue
            colour = np.array(_box_colour(score), dtype=np.float32) * 255.0
            colour_sum[binary] += colour
            count[binary] += 1.0
        covered = count > 0
        if covered.any():
            avg = np.zeros_like(colour_sum)
            avg[covered] = colour_sum[covered] / count[covered, None]
            base = np.where(covered[..., None], base * 0.55 + avg * 0.45, base)
    canvas = Image.fromarray(np.clip(base, 0, 255).astype(np.uint8))
    draw = ImageDraw.Draw(canvas)
    for box, score in zip(boxes, scores):
        x1, y1, x2, y2 = box
        colour = tuple(int(c * 255) for c in _box_colour(score))
        draw.rectangle([x1, y1, x2, y2], outline=colour, width=3)
        draw.text((x1 + 3, y1 + 3), f"{score:.2f}", fill=colour)
    return canvas


def _box_colour(score: float) -> tuple[float, float, float]:
    """Score -> colour ramp from yellow (low) to red (high)."""
    t = max(0.0, min(1.0, float(score)))
    # yellow -> red
    return (1.0, 1.0 - t, 0.3 * (1.0 - t))


@spaces.GPU(duration=15)
def analyse(
    image: Image.Image | None,
    score_threshold: float = 0.5,
    progress=gr.Progress(track_tqdm=True),
):
    """Estimate canopy height and delineate tree crowns from an overhead RGB image.

    Args:
        image: Overhead (aerial/satellite) RGB image. Best results at the
            paper's operating point: ~2-10 cm GSD, roughly 992x992 pixels.
        score_threshold: Minimum detection score to display (the model's own
            NMS already ran at the training threshold).

    Returns:
        (detection overlay, colourised height map, stats text)
    """
    if image is None:
        raise gr.Error("Please upload an overhead RGB image first.")
    if image.mode != "RGB":
        image = image.convert("RGB")
    width, height = image.size
    if width * height > MAX_PIXELS:
        scale = math.sqrt(MAX_PIXELS / (width * height))
        image = image.resize(
            (max(1, int(width * scale)), max(1, int(height * scale))),
            Image.Resampling.BILINEAR,
        )
        gr.Info(
            f"Image resized to {image.size[0]}x{image.size[1]} to keep GPU time bounded."
        )

    valid_mask = border_black_valid_mask(image, tolerance=0)
    height_map = _predict_height_map(image, valid_mask)
    detector_input = _detector_input(image, valid_mask, height_map).to(device)

    with torch.no_grad():
        outputs = _detector([detector_input])
    outputs = filter_detections_by_valid_masks(
        outputs, [torch.from_numpy(valid_mask)], PREDICTION_MIN_VALID_FRACTION
    )
    output = outputs[0]
    boxes = output.get("boxes")
    scores = output.get("scores")
    masks = output.get("masks")

    boxes_list = boxes.detach().cpu().float().tolist() if torch.is_tensor(boxes) else []
    scores_list = (
        [float(v) for v in scores.detach().cpu().float().tolist()]
        if torch.is_tensor(scores)
        else []
    )
    if torch.is_tensor(masks):
        mask_tensor = masks[:, 0] if masks.ndim == 4 and masks.shape[1] == 1 else masks
        binary_masks = (mask_tensor.detach().cpu() >= MASK_PROBABILITY_THRESHOLD) & torch.from_numpy(
            valid_mask
        )
        mask_list = binary_masks.numpy()
    else:
        mask_list = np.zeros((0, height, width), dtype=bool)

    keep = [i for i, s in enumerate(scores_list) if s >= float(score_threshold)]
    boxes_list = [boxes_list[i] for i in keep]
    scores_list = [scores_list[i] for i in keep]
    if len(mask_list):
        mask_list = mask_list[keep]

    overlay = _draw_detections(image, boxes_list, scores_list, mask_list, valid_mask)
    height_vis = _colourise_height(height_map, valid_mask)

    valid_pixels = int(valid_mask.sum())
    if valid_pixels > 0:
        mean_height = float(height_map[valid_mask].mean())
        max_height = float(height_map[valid_mask].max())
    else:
        mean_height = 0.0
        max_height = 0.0
    canopy = valid_mask & (height_map > 1.0)
    canopy_pixels = int(canopy.sum())
    stats = (
        f"**Detections**: {len(boxes_list)} crowns (score β‰₯ {score_threshold:.2f})\n\n"
        f"**Mean canopy height**: {mean_height:.1f} m\n"
        f"**Max canopy height**: {max_height:.1f} m\n\n"
        f"**Canopy cover (>1 m)**: {100.0 * canopy_pixels / max(1, valid_pixels):.1f} %\n"
        f"**Valid pixels**: {100.0 * valid_pixels / valid_mask.size:.1f} % of image\n\n"
        f"**Input size**: {image.size[0]}Γ—{image.size[1]} px"
    )
    return overlay, height_vis, stats


# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------

_HEADER = """\
# 🌲 SynthForest β€” canopy height & tree crowns
Upload an **overhead RGB image** (aerial/satellite, ~2–10 cm GSD works best).
The demo runs the paper's two released models on it:

1. **Syn-20** β€” DINOv3+DPT canopy-height estimation β†’ height map (meters)
2. **HF+MT** β€” Mask R-CNN crown delineation with height fusion + Mean Teacher
   (best model, Table 5) β†’ per-tree crown masks and boxes

Models and example tiles from the
[SynthForest dataset & models](https://huggingface.co/novoselova/synthforest) (CC BY 4.0)."""

_FOOTER = """\
---
**Citation** (Novoselova, Song, Yokoya β€” *SynthForest: A Multi-Task Synthetic
Dataset for Real-World Forest Vision*):
```bibtex
@misc{novoselova2026synthforest,
  title         = {SynthForest: A Multi-Task Synthetic Dataset for Real-World Forest Vision},
  author        = {Iaroslava Novoselova and Jian Song and Naoto Yokoya},
  year          = {2026},
  eprint        = {2612.03462},
  archivePrefix = {arXiv},
  primaryClass  = {cs.CV}
}
```
Code: [github.com/iaroslavanovoselova/SynthForest](https://github.com/iaroslavanovoselova/SynthForest) Β·
Paper: [arXiv:2612.03462](https://arxiv.org/abs/2612.03462)"""

with gr.Blocks() as demo:
    gr.Markdown(_HEADER)
    with gr.Row():
        with gr.Column():
            image_in = gr.Image(
                type="pil",
                label="Overhead RGB image",
                sources=["upload", "clipboard"],
            )
            score_threshold = gr.Slider(
                0.05, 0.95, value=0.5, step=0.05, label="Score threshold"
            )
            run_btn = gr.Button("Analyse", variant="primary")
        with gr.Column():
            overlay_out = gr.Image(type="pil", label="Tree crown detections")
            height_out = gr.Image(type="pil", label="Canopy height (m)")
            stats_out = gr.Markdown()

    run_btn.click(
        analyse,
        inputs=[image_in, score_threshold],
        outputs=[overlay_out, height_out, stats_out],
    )

    gr.Examples(
        examples=[
            ["assets/example_sm.png", 0.5],
            ["assets/example_hn.png", 0.5],
            ["assets/example_lcc.png", 0.5],
        ],
        inputs=[image_in, score_threshold],
        fn=analyse,
        outputs=[overlay_out, height_out, stats_out],
        cache_examples=True,
        cache_mode="lazy",
        label="Example tiles from the SynthForest dataset (CC BY 4.0)",
    )

    gr.Markdown(_FOOTER)

demo.launch(mcp_server=True, theme=gr.themes.Citrus())