Skip to content

map_widgets module

Interactive widget for GeoAI.

DINOv3GUI

Bases: VBox

Interactive widget for DINOv3.

Source code in geoai/map_widgets.py
 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
class DINOv3GUI(widgets.VBox):
    """Interactive widget for DINOv3."""

    def __init__(
        self,
        raster: str,
        processor=None,
        features=None,
        host_map=None,
        position="topright",
        colormap_options=None,
        raster_args=None,
    ):
        """Initialize the DINOv3 GUI.

        Args:
            raster (str): The path to the raster image.
            processor (DINOv3GeoProcessor): The DINOv3 processor.
            features (torch.Tensor): The features of the raster image.
            host_map (Map): The host map.
            position (str): The position of the widget.
            colormap_options (list): The colormap options.
            raster_args (dict): The raster arguments.

        Example:
            >>> processor = DINOv3GeoProcessor()
            >>> features, h_patches, w_patches = processor.extract_features(raster)
            >>> gui = DINOv3GUI(raster, processor, features, host_map=m)
        """
        super().__init__()

        if raster_args is None:
            raster_args = {}

        if "layer_name" not in raster_args:
            raster_args["layer_name"] = "Raster"

        if colormap_options is None:
            colormap_options = [
                "jet",
                "viridis",
                "plasma",
                "inferno",
                "magma",
                "cividis",
            ]

        main_widget = widgets.VBox(layout=widgets.Layout(width="230px"))
        style = {"description_width": "initial"}
        layout = widgets.Layout(width="95%", padding="0px 5px 0px 5px")

        interpolation_checkbox = widgets.Checkbox(
            value=True,
            description="Use interpolation",
            style=style,
            layout=layout,
        )

        threshold_slider = widgets.FloatSlider(
            value=0.7,
            min=0,
            max=1,
            step=0.01,
            description="Threshold",
            style=style,
            layout=layout,
        )

        opacity_slider = widgets.FloatSlider(
            value=0.5,
            min=0,
            max=1,
            step=0.01,
            description="Opacity",
            style=style,
            layout=layout,
        )
        colormap_dropdown = widgets.Dropdown(
            options=colormap_options,
            value="jet",
            description="Colormap",
            style=style,
            layout=layout,
        )
        layer_name_input = widgets.Text(
            value="Similarity",
            description="Layer name",
            style=style,
            layout=layout,
        )

        save_button = widgets.Button(
            description="Save",
        )

        reset_button = widgets.Button(
            description="Reset",
        )

        output = widgets.Output()

        main_widget.children = [
            interpolation_checkbox,
            threshold_slider,
            opacity_slider,
            colormap_dropdown,
            layer_name_input,
            widgets.HBox([save_button, reset_button]),
            output,
        ]

        if host_map is not None:

            host_map.add_widget(main_widget, add_header=True, position=position)

            if raster is not None:
                host_map.add_raster(raster, **raster_args)

            def handle_map_interaction(**kwargs):
                try:
                    if kwargs.get("type") == "click":
                        latlon = kwargs.get("coordinates")
                        with output:
                            output.clear_output()

                            results = processor.compute_similarity(
                                source=raster,
                                features=features,
                                query_coords=latlon[::-1],
                                output_dir="dinov3_results",
                                use_interpolation=interpolation_checkbox.value,
                                coord_crs="EPSG:4326",
                            )
                            array = results["image_dict"]["image"]
                            binary_array = array > threshold_slider.value
                            image = dict_to_image(results["image_dict"])
                            binary_image = dict_to_image(
                                {
                                    "image": binary_array,
                                    "crs": results["image_dict"]["crs"],
                                    "bounds": results["image_dict"]["bounds"],
                                }
                            )
                            host_map.add_raster(
                                image,
                                colormap=colormap_dropdown.value,
                                opacity=opacity_slider.value,
                                layer_name=layer_name_input.value,
                                zoom_to_layer=False,
                                overwrite=True,
                            )
                            host_map.add_raster(
                                binary_image,
                                colormap="jet",
                                nodata=0,
                                opacity=opacity_slider.value,
                                layer_name="Foreground",
                                zoom_to_layer=False,
                                overwrite=True,
                                visible=False,
                            )
                except Exception as e:
                    with output:
                        print(e)

            host_map.on_interaction(handle_map_interaction)
            host_map.default_style = {"cursor": "crosshair"}

__init__(raster, processor=None, features=None, host_map=None, position='topright', colormap_options=None, raster_args=None)

Initialize the DINOv3 GUI.

Parameters:

Name Type Description Default
raster str

The path to the raster image.

required
processor DINOv3GeoProcessor

The DINOv3 processor.

None
features Tensor

The features of the raster image.

None
host_map Map

The host map.

None
position str

The position of the widget.

'topright'
colormap_options list

The colormap options.

None
raster_args dict

The raster arguments.

None
Example

processor = DINOv3GeoProcessor() features, h_patches, w_patches = processor.extract_features(raster) gui = DINOv3GUI(raster, processor, features, host_map=m)

Source code in geoai/map_widgets.py
 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
def __init__(
    self,
    raster: str,
    processor=None,
    features=None,
    host_map=None,
    position="topright",
    colormap_options=None,
    raster_args=None,
):
    """Initialize the DINOv3 GUI.

    Args:
        raster (str): The path to the raster image.
        processor (DINOv3GeoProcessor): The DINOv3 processor.
        features (torch.Tensor): The features of the raster image.
        host_map (Map): The host map.
        position (str): The position of the widget.
        colormap_options (list): The colormap options.
        raster_args (dict): The raster arguments.

    Example:
        >>> processor = DINOv3GeoProcessor()
        >>> features, h_patches, w_patches = processor.extract_features(raster)
        >>> gui = DINOv3GUI(raster, processor, features, host_map=m)
    """
    super().__init__()

    if raster_args is None:
        raster_args = {}

    if "layer_name" not in raster_args:
        raster_args["layer_name"] = "Raster"

    if colormap_options is None:
        colormap_options = [
            "jet",
            "viridis",
            "plasma",
            "inferno",
            "magma",
            "cividis",
        ]

    main_widget = widgets.VBox(layout=widgets.Layout(width="230px"))
    style = {"description_width": "initial"}
    layout = widgets.Layout(width="95%", padding="0px 5px 0px 5px")

    interpolation_checkbox = widgets.Checkbox(
        value=True,
        description="Use interpolation",
        style=style,
        layout=layout,
    )

    threshold_slider = widgets.FloatSlider(
        value=0.7,
        min=0,
        max=1,
        step=0.01,
        description="Threshold",
        style=style,
        layout=layout,
    )

    opacity_slider = widgets.FloatSlider(
        value=0.5,
        min=0,
        max=1,
        step=0.01,
        description="Opacity",
        style=style,
        layout=layout,
    )
    colormap_dropdown = widgets.Dropdown(
        options=colormap_options,
        value="jet",
        description="Colormap",
        style=style,
        layout=layout,
    )
    layer_name_input = widgets.Text(
        value="Similarity",
        description="Layer name",
        style=style,
        layout=layout,
    )

    save_button = widgets.Button(
        description="Save",
    )

    reset_button = widgets.Button(
        description="Reset",
    )

    output = widgets.Output()

    main_widget.children = [
        interpolation_checkbox,
        threshold_slider,
        opacity_slider,
        colormap_dropdown,
        layer_name_input,
        widgets.HBox([save_button, reset_button]),
        output,
    ]

    if host_map is not None:

        host_map.add_widget(main_widget, add_header=True, position=position)

        if raster is not None:
            host_map.add_raster(raster, **raster_args)

        def handle_map_interaction(**kwargs):
            try:
                if kwargs.get("type") == "click":
                    latlon = kwargs.get("coordinates")
                    with output:
                        output.clear_output()

                        results = processor.compute_similarity(
                            source=raster,
                            features=features,
                            query_coords=latlon[::-1],
                            output_dir="dinov3_results",
                            use_interpolation=interpolation_checkbox.value,
                            coord_crs="EPSG:4326",
                        )
                        array = results["image_dict"]["image"]
                        binary_array = array > threshold_slider.value
                        image = dict_to_image(results["image_dict"])
                        binary_image = dict_to_image(
                            {
                                "image": binary_array,
                                "crs": results["image_dict"]["crs"],
                                "bounds": results["image_dict"]["bounds"],
                            }
                        )
                        host_map.add_raster(
                            image,
                            colormap=colormap_dropdown.value,
                            opacity=opacity_slider.value,
                            layer_name=layer_name_input.value,
                            zoom_to_layer=False,
                            overwrite=True,
                        )
                        host_map.add_raster(
                            binary_image,
                            colormap="jet",
                            nodata=0,
                            opacity=opacity_slider.value,
                            layer_name="Foreground",
                            zoom_to_layer=False,
                            overwrite=True,
                            visible=False,
                        )
            except Exception as e:
                with output:
                    print(e)

        host_map.on_interaction(handle_map_interaction)
        host_map.default_style = {"cursor": "crosshair"}

moondream_gui(moondream, basemap='SATELLITE', out_dir=None, opacity=0.5, **kwargs)

Display an interactive GUI for using Moondream with leafmap.

This function creates an interactive map interface for using Moondream vision language model capabilities including: - Image captioning (short, normal, long) with streaming output - Visual question answering (query) with streaming output - Object detection with bounding boxes displayed on map - Point detection for locating objects with markers on map

Parameters:

Name Type Description Default
moondream MoondreamGeo

The MoondreamGeo object with a loaded image. Must have called load_image() or load_geotiff() first.

required
basemap str

The basemap to use. Defaults to "SATELLITE".

'SATELLITE'
out_dir str

The output directory for saving results. Defaults to None (uses temp directory).

None
opacity float

The opacity of overlay layers. Defaults to 0.5.

0.5
**kwargs Any

Additional keyword arguments passed to leafmap.Map().

{}

Returns:

Type Description

leafmap.Map: The interactive map with the Moondream GUI.

Example

from geoai import MoondreamGeo, moondream_gui moondream = MoondreamGeo() moondream.load_image("image.tif") m = moondream_gui(moondream) m

Source code in geoai/map_widgets.py
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
def moondream_gui(
    moondream,
    basemap: str = "SATELLITE",
    out_dir: Optional[str] = None,
    opacity: float = 0.5,
    **kwargs: Any,
):
    """Display an interactive GUI for using Moondream with leafmap.

    This function creates an interactive map interface for using Moondream
    vision language model capabilities including:
    - Image captioning (short, normal, long) with streaming output
    - Visual question answering (query) with streaming output
    - Object detection with bounding boxes displayed on map
    - Point detection for locating objects with markers on map

    Args:
        moondream (MoondreamGeo): The MoondreamGeo object with a loaded image.
            Must have called load_image() or load_geotiff() first.
        basemap (str, optional): The basemap to use. Defaults to "SATELLITE".
        out_dir (str, optional): The output directory for saving results.
            Defaults to None (uses temp directory).
        opacity (float, optional): The opacity of overlay layers. Defaults to 0.5.
        **kwargs: Additional keyword arguments passed to leafmap.Map().

    Returns:
        leafmap.Map: The interactive map with the Moondream GUI.

    Example:
        >>> from geoai import MoondreamGeo, moondream_gui
        >>> moondream = MoondreamGeo()
        >>> moondream.load_image("image.tif")
        >>> m = moondream_gui(moondream)
        >>> m
    """
    try:
        import ipyevents
        import ipyleaflet
        import leafmap
        from ipyfilechooser import FileChooser
    except ImportError:
        raise ImportError(
            "The moondream_gui function requires additional packages. "
            "Please install them with: pip install leafmap ipyevents ipyfilechooser"
        )

    if out_dir is None:
        out_dir = tempfile.gettempdir()

    # Create the map
    m = leafmap.Map(**kwargs)
    m.default_style = {"cursor": "crosshair"}
    if basemap is not None:
        m.add_basemap(basemap, show=False)

    # Try to add the image layer if source is available
    if moondream._source_path is not None:
        try:
            m.add_raster(moondream._source_path, layer_name="Image")
        except Exception:
            pass

    # Initialize marker storage for detection results
    m.detection_markers = []
    m.point_markers = []

    # Removed unused LayerGroups for detections and points.
    m.last_result_as_gdf = None

    # Widget styling
    widget_width = "300px"
    button_width = "90px"
    padding = "0px 4px 0px 4px"
    style = {"description_width": "initial"}

    # Create toolbar buttons
    toolbar_button = widgets.ToggleButton(
        value=True,
        tooltip="Toolbar",
        icon="gear",
        layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"),
    )

    close_button = widgets.ToggleButton(
        value=False,
        tooltip="Close the tool",
        icon="times",
        button_style="primary",
        layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"),
    )

    # Mode selection
    mode_dropdown = widgets.Dropdown(
        options=["Caption", "Query", "Detect", "Point"],
        value="Caption",
        description="Mode:",
        style=style,
        layout=widgets.Layout(width=widget_width, padding=padding),
    )

    # Text prompt input
    text_prompt = widgets.Text(
        description="Prompt:",
        placeholder="Enter text prompt...",
        style=style,
        layout=widgets.Layout(width=widget_width, padding=padding),
    )

    # Caption length selector (only visible in Caption mode)
    caption_length = widgets.Dropdown(
        options=["short", "normal", "long"],
        value="normal",
        description="Length:",
        style=style,
        layout=widgets.Layout(width=widget_width, padding=padding),
    )

    # Opacity slider for overlays
    opacity_slider = widgets.FloatSlider(
        description="Opacity:",
        min=0,
        max=1,
        value=opacity,
        readout=True,
        continuous_update=True,
        layout=widgets.Layout(width=widget_width, padding=padding),
        style=style,
    )

    # Color picker for detection/point markers
    colorpicker = widgets.ColorPicker(
        concise=False,
        description="Color:",
        value="#ff0000",
        layout=widgets.Layout(width="150px", padding=padding),
        style=style,
    )

    # Action buttons
    run_button = widgets.ToggleButton(
        description="Run",
        value=False,
        button_style="primary",
        layout=widgets.Layout(padding=padding, width=button_width),
    )

    save_button = widgets.ToggleButton(
        description="Save",
        value=False,
        button_style="primary",
        layout=widgets.Layout(width=button_width),
    )

    reset_button = widgets.ToggleButton(
        description="Reset",
        value=False,
        button_style="primary",
        layout=widgets.Layout(width=button_width),
    )

    # Output area for displaying results - using HTML for better text display
    output_html = widgets.HTML(
        value="",
        layout=widgets.Layout(
            width=widget_width,
            padding=padding,
            max_width=widget_width,
            min_height="0px",
            max_height="300px",
            overflow="auto",
        ),
    )

    # Build the toolbar layout
    toolbar_header = widgets.HBox()
    toolbar_header.children = [close_button, toolbar_button]

    toolbar_footer = widgets.VBox()
    toolbar_footer.children = [
        mode_dropdown,
        text_prompt,
        caption_length,
        opacity_slider,
        colorpicker,
        widgets.HBox(
            [run_button, save_button, reset_button],
            layout=widgets.Layout(padding="0px 4px 0px 4px"),
        ),
        output_html,
    ]

    toolbar_widget = widgets.VBox()
    toolbar_widget.children = [toolbar_header, toolbar_footer]

    # Event handling for toolbar collapse/expand
    toolbar_event = ipyevents.Event(
        source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]
    )

    def update_ui_visibility(change=None):
        """Update UI element visibility based on selected mode."""
        mode = mode_dropdown.value

        # Clear prompt and output when mode changes
        text_prompt.value = ""
        output_html.value = ""

        if mode == "Caption":
            text_prompt.layout.display = "none"
            caption_length.layout.display = "flex"
        elif mode == "Query":
            text_prompt.layout.display = "flex"
            text_prompt.placeholder = "Ask a question about the image..."
            caption_length.layout.display = "none"
        elif mode == "Detect":
            text_prompt.layout.display = "flex"
            text_prompt.placeholder = "Object type to detect (e.g., building, trees)..."
            caption_length.layout.display = "none"
        elif mode == "Point":
            text_prompt.layout.display = "flex"
            text_prompt.placeholder = "Object description to locate..."
            caption_length.layout.display = "none"

    mode_dropdown.observe(update_ui_visibility, "value")
    update_ui_visibility()  # Initial update

    def handle_toolbar_event(event):
        if event["type"] == "mouseenter":
            toolbar_widget.children = [toolbar_header, toolbar_footer]
        elif event["type"] == "mouseleave":
            if not toolbar_button.value:
                toolbar_widget.children = [toolbar_button]
                toolbar_button.value = False
                close_button.value = False

    toolbar_event.on_dom_event(handle_toolbar_event)

    def toolbar_btn_click(change):
        if change["new"]:
            close_button.value = False
            toolbar_widget.children = [toolbar_header, toolbar_footer]
        else:
            if not close_button.value:
                toolbar_widget.children = [toolbar_button]

    toolbar_button.observe(toolbar_btn_click, "value")

    def close_btn_click(change):
        if change["new"]:
            toolbar_button.value = False
            if m.toolbar_control in m.controls:
                m.remove_control(m.toolbar_control)
            toolbar_widget.close()

    close_button.observe(close_btn_click, "value")

    def clear_detections():
        """Clear all detection markers and layers."""
        if "Detections" in m.get_layer_names():
            m.remove_layer(m.find_layer("Detections"))

    def clear_points():
        """Clear all point markers."""
        if "Points" in m.get_layer_names():
            m.remove_layer(m.find_layer("Points"))

    def add_detection_boxes(result, color="#ff0000"):
        """Add bounding boxes from detection result to the map."""
        clear_detections()

        if "gdf" in result and len(result["gdf"]) > 0:
            gdf = result["gdf"].copy()
            m.add_gdf(
                gdf,
                layer_name="Detections",
                style={
                    "color": color,
                    "fillColor": color,
                    "fillOpacity": opacity_slider.value,
                    "weight": 2,
                },
                info_mode=None,
            )

    def add_point_markers(result, color="#ff0000", opacity=0.5):
        """Add point markers from point detection result to the map."""
        clear_points()

        if "gdf" in result and len(result["gdf"]) > 0:
            gdf = result["gdf"].copy().to_crs("EPSG:4326")
            gdf["x"] = gdf.geometry.centroid.x
            gdf["y"] = gdf.geometry.centroid.y

            m.add_circle_markers_from_xy(
                gdf,
                "x",
                "y",
                radius=6,
                color=color,
                fill_color=color,
                fill_opacity=opacity,
                layer_name="Points",
            )

    def update_output(text, append=False):
        """Update the output HTML widget."""
        # Escape HTML and convert newlines
        import html

        escaped = html.escape(text)
        formatted = escaped.replace("\n", "<br>")
        style = "font-family: monospace; font-size: 12px; word-wrap: break-word;"

        if append and output_html.value:
            # Extract existing content and append
            current = output_html.value
            if "<div" in current:
                # Find the content between div tags
                start = current.find(">") + 1
                end = current.rfind("</div>")
                existing = current[start:end]
                output_html.value = f'<div style="{style}">{existing}{formatted}</div>'
            else:
                output_html.value = f'<div style="{style}">{formatted}</div>'
        else:
            output_html.value = f'<div style="{style}">{formatted}</div>'

    def run_button_click(change):
        if change["new"]:
            run_button.value = False
            mode = mode_dropdown.value

            if moondream._source_path is None and moondream._metadata is None:
                update_output(
                    "Please load an image first using load_image() or load_geotiff()."
                )
                return

            try:

                if mode == "Caption":
                    update_output(f"Generating caption ({caption_length.value})...")

                    result = moondream.caption(
                        moondream._source_path,
                        length=caption_length.value,
                        stream=False,
                    )
                    caption_text = result.get("caption", str(result))
                    update_output(f"Caption ({caption_length.value}):\n{caption_text}")
                    m.last_result = result
                    m.last_result_as_gdf = None

                elif mode == "Query":
                    if len(text_prompt.value) == 0:
                        update_output("Please enter a question in the prompt field.")
                        return

                    update_output(f"Q: {text_prompt.value}\nGenerating answer...")

                    result = moondream.query(
                        text_prompt.value,
                        source=moondream._source_path,
                        stream=False,
                    )
                    answer_text = result.get("answer", str(result))
                    update_output(f"Q: {text_prompt.value}\nA: {answer_text}")
                    m.last_result = result

                elif mode == "Detect":
                    if len(text_prompt.value) == 0:
                        update_output("Please enter an object type to detect.")
                        return

                    update_output(f"Detecting: {text_prompt.value}...")

                    result = moondream.detect(
                        moondream._source_path,
                        text_prompt.value,
                    )
                    num_objects = len(result.get("objects", []))

                    # Show detection info
                    info_text = f"Detecting: {text_prompt.value}\nFound {num_objects} object(s)."
                    if "gdf" in result and len(result["gdf"]) > 0:
                        info_text += (
                            f"\nAdded {len(result['gdf'])} bounding box(es) to map."
                        )
                    update_output(info_text)

                    if num_objects > 0:
                        add_detection_boxes(result, colorpicker.value)
                    m.last_result = result
                    if "gdf" in result and len(result["gdf"]) > 0:
                        m.last_result_as_gdf = result["gdf"].to_crs("EPSG:4326")

                elif mode == "Point":
                    if len(text_prompt.value) == 0:
                        update_output("Please enter an object description to locate.")
                        return

                    update_output(f"Locating: {text_prompt.value}...")

                    result = moondream.point(
                        moondream._source_path,
                        text_prompt.value,
                    )
                    num_points = len(result.get("points", []))
                    update_output(
                        f"Locating: {text_prompt.value}\nFound {num_points} point(s)."
                    )

                    if num_points > 0:
                        add_point_markers(
                            result, colorpicker.value, opacity_slider.value
                        )
                    m.last_result = result
                    if "gdf" in result and len(result["gdf"]) > 0:
                        m.last_result_as_gdf = result["gdf"].to_crs("EPSG:4326")
            except Exception as e:
                import traceback

                update_output(f"Error: {e}\n\n{traceback.format_exc()}")

    run_button.observe(run_button_click, "value")

    def filechooser_callback(chooser):
        if chooser.selected is not None:
            try:
                filename = chooser.selected
                if hasattr(m, "last_result") and m.last_result:
                    result = m.last_result

                    # Save based on result type
                    if "gdf" in result and len(result["gdf"]) > 0:
                        gdf = result["gdf"]
                        ext = os.path.splitext(filename)[1].lower()
                        if ext == ".geojson":
                            gdf.to_file(filename, driver="GeoJSON")
                        elif ext == ".shp":
                            gdf.to_file(filename, driver="ESRI Shapefile")
                        elif ext == ".gpkg":
                            gdf.to_file(filename, driver="GPKG")
                        else:
                            gdf.to_file(filename)
                        update_output(f"Saved {len(gdf)} features to {filename}")

                    elif "caption" in result:
                        with open(filename, "w") as f:
                            f.write(result["caption"])
                        update_output(f"Saved caption to {filename}")

                    elif "answer" in result:
                        with open(filename, "w") as f:
                            f.write(f"Q: {text_prompt.value}\n")
                            f.write(f"A: {result['answer']}")
                        update_output(f"Saved Q&A to {filename}")

            except Exception as e:
                update_output(f"Error saving: {e}")

            if hasattr(m, "save_control") and m.save_control in m.controls:
                m.remove_control(m.save_control)
                delattr(m, "save_control")
            save_button.value = False

    def save_button_click(change):
        if change["new"]:
            if not hasattr(m, "last_result") or m.last_result is None:
                update_output("Please run an operation first.")
                save_button.value = False
                return

            result = m.last_result
            mode = mode_dropdown.value

            # Determine default filename and filter
            if mode in ["Detect", "Point"] and "gdf" in result:
                default_filename = f"{mode.lower()}_{random_string()}.geojson"
                filter_pattern = ["*.geojson", "*.gpkg", "*.shp"]
            else:
                default_filename = f"{mode.lower()}_{random_string()}.txt"
                filter_pattern = ["*.txt"]

            sandbox_path = os.environ.get("SANDBOX_PATH")
            filechooser = FileChooser(
                path=os.getcwd(),
                filename=default_filename,
                sandbox_path=sandbox_path,
                layout=widgets.Layout(width="454px"),
            )
            filechooser.use_dir_icons = True
            filechooser.filter_pattern = filter_pattern
            filechooser.register_callback(filechooser_callback)
            save_control = ipyleaflet.WidgetControl(
                widget=filechooser, position="topright"
            )
            m.add_control(save_control)
            m.save_control = save_control
        else:
            if hasattr(m, "save_control") and m.save_control in m.controls:
                m.remove_control(m.save_control)
                delattr(m, "save_control")

    save_button.observe(save_button_click, "value")

    def reset_button_click(change):
        if change["new"]:
            run_button.value = False
            save_button.value = False
            reset_button.value = False
            text_prompt.value = ""
            caption_length.value = "normal"
            opacity_slider.value = 0.5
            colorpicker.value = "#ff0000"
            output_html.value = ""

            # Clear all markers and detection boxes
            clear_detections()
            clear_points()

            # Clear last result
            if hasattr(m, "last_result"):
                m.last_result = None

    reset_button.observe(reset_button_click, "value")

    # Add the toolbar control to the map
    toolbar_control = ipyleaflet.WidgetControl(
        widget=toolbar_widget, position="topright"
    )
    m.add_control(toolbar_control)
    m.toolbar_control = toolbar_control

    return m

random_string(string_length=6)

Generate a random string of fixed length.

Parameters:

Name Type Description Default
string_length int

The length of the random string. Defaults to 6.

6

Returns:

Type Description
str

A random string of the specified length.

Source code in geoai/map_widgets.py
14
15
16
17
18
19
20
21
22
23
24
def random_string(string_length: int = 6) -> str:
    """Generate a random string of fixed length.

    Args:
        string_length: The length of the random string. Defaults to 6.

    Returns:
        A random string of the specified length.
    """
    letters = string.ascii_lowercase
    return "".join(random.choice(letters) for _ in range(string_length))