le-map-tools 0.36.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. le_map_tools/__init__.py +62 -0
  2. le_map_tools/ai.py +2341 -0
  3. le_map_tools/basemaps.py +631 -0
  4. le_map_tools/cartoee.py +1375 -0
  5. le_map_tools/chart.py +2027 -0
  6. le_map_tools/cli.py +16 -0
  7. le_map_tools/colormaps.py +243 -0
  8. le_map_tools/common.py +15829 -0
  9. le_map_tools/conversion.py +1412 -0
  10. le_map_tools/core.py +1437 -0
  11. le_map_tools/coreutils.py +792 -0
  12. le_map_tools/data/census_data.json +1430 -0
  13. le_map_tools/data/fonts/alibaba.otf +0 -0
  14. le_map_tools/data/fonts/arial.ttf +0 -0
  15. le_map_tools/data/gee_f.json +1 -0
  16. le_map_tools/data/javascripts/ClippedComposite.js +22 -0
  17. le_map_tools/data/javascripts/FromName.js +7 -0
  18. le_map_tools/data/javascripts/ModisQaBands.js +59 -0
  19. le_map_tools/data/javascripts/NormalizedDifference.js +25 -0
  20. le_map_tools/data/javascripts/QualityMosaic.js +53 -0
  21. le_map_tools/data/python/javascript_to_python.py +19 -0
  22. le_map_tools/data/template/NLCD.qml +60 -0
  23. le_map_tools/data/template/ee_api_docs.csv +1574 -0
  24. le_map_tools/data/template/ee_api_docs.html +97 -0
  25. le_map_tools/data/template/ee_data_catalog.csv +568 -0
  26. le_map_tools/data/template/ee_legend_table.txt +19 -0
  27. le_map_tools/data/template/legend.html +57 -0
  28. le_map_tools/data/template/legend.txt +89 -0
  29. le_map_tools/data/template/legend_style.html +78 -0
  30. le_map_tools/data/template/template.py +53 -0
  31. le_map_tools/data/template/toolbox.csv +15 -0
  32. le_map_tools/datasets.py +197 -0
  33. le_map_tools/deck.py +390 -0
  34. le_map_tools/ee_tile_layers.py +311 -0
  35. le_map_tools/examples/__init__.py +68 -0
  36. le_map_tools/examples/datasets.txt +45 -0
  37. le_map_tools/foliumap.py +3229 -0
  38. le_map_tools/kepler.py +526 -0
  39. le_map_tools/le_map_tools.py +5232 -0
  40. le_map_tools/legends.py +528 -0
  41. le_map_tools/map_widgets.py +2806 -0
  42. le_map_tools/maplibregl.py +3073 -0
  43. le_map_tools/ml.py +422 -0
  44. le_map_tools/osm.py +371 -0
  45. le_map_tools/plot.py +1021 -0
  46. le_map_tools/plotlymap.py +813 -0
  47. le_map_tools/report.py +40 -0
  48. le_map_tools/static/basemap_selector.js +1422 -0
  49. le_map_tools/static/color_picker.js +963 -0
  50. le_map_tools/static/container.js +1274 -0
  51. le_map_tools/static/inspector.js +1539 -0
  52. le_map_tools/static/ipywidgets_styles.js +788 -0
  53. le_map_tools/static/layer_editor.js +2625 -0
  54. le_map_tools/static/layer_manager.js +1393 -0
  55. le_map_tools/static/layer_manager_row.js +1300 -0
  56. le_map_tools/static/legend.js +1433 -0
  57. le_map_tools/static/legend_customization.js +1105 -0
  58. le_map_tools/static/lit_widget.js +630 -0
  59. le_map_tools/static/palette_editor.js +1238 -0
  60. le_map_tools/static/raster_layer_editor.js +1759 -0
  61. le_map_tools/static/search_bar.js +1817 -0
  62. le_map_tools/static/styles.js +636 -0
  63. le_map_tools/static/tab_panel.js +1247 -0
  64. le_map_tools/static/toolbar.js +1614 -0
  65. le_map_tools/static/toolbar_item.js +1147 -0
  66. le_map_tools/static/tree_node.js +1075 -0
  67. le_map_tools/static/utils.js +638 -0
  68. le_map_tools/static/vector_layer_editor.js +1525 -0
  69. le_map_tools/timelapse.py +5324 -0
  70. le_map_tools/toolbar.py +5258 -0
  71. le_map_tools-0.36.4.dist-info/METADATA +260 -0
  72. le_map_tools-0.36.4.dist-info/RECORD +75 -0
  73. le_map_tools-0.36.4.dist-info/WHEEL +4 -0
  74. le_map_tools-0.36.4.dist-info/entry_points.txt +2 -0
  75. le_map_tools-0.36.4.dist-info/licenses/LICENSE +21 -0
le_map_tools/ai.py ADDED
@@ -0,0 +1,2341 @@
1
+ """This module contains functions for interacting with AI models.
2
+ The Genie class source code is adapted from the ee_genie.ipynb at <https://bit.ly/3YEm7B6>.
3
+ Credit to the original author Simon Ilyushchenko (<https://github.com/simonff>).
4
+ The DataExplorer class source code is adapted from <https://bit.ly/48cE24D>.
5
+ Credit to the original author Renee Johnston (<https://github.com/raj02006>)
6
+ """
7
+
8
+ # Standard library imports
9
+ import io
10
+ import json
11
+ import math
12
+ import os
13
+ import time
14
+ from concurrent import futures
15
+ from contextlib import redirect_stdout
16
+ import dataclasses
17
+ import datetime
18
+ import logging
19
+ import re
20
+ import sys
21
+ from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
22
+ import uuid
23
+
24
+ import numpy as np
25
+ import pandas as pd
26
+
27
+ import PIL
28
+ import requests
29
+
30
+ import le
31
+ import typing_extensions
32
+ import ipywidgets as widgets
33
+ from ipyleaflet import LayerException
34
+ from jinja2 import Template
35
+ from IPython.display import HTML, Javascript, display
36
+
37
+ try:
38
+
39
+ import vertexai
40
+ import google.generativeai as genai
41
+ import google.ai.generativelanguage as glm
42
+ import google.api_core
43
+ from google.cloud import storage
44
+ from google.api_core import exceptions as google_exceptions
45
+ from vertexai.preview.language_models import TextEmbeddingModel
46
+ from langchain.embeddings.base import Embeddings
47
+ from langchain.indexes import VectorstoreIndexCreator
48
+ from langchain.schema import Document
49
+ from langchain_google_genai import ChatGoogleGenerativeAI
50
+ from langchain_core.vectorstores.base import VectorStore
51
+ from langchain.indexes.vectorstore import VectorStoreIndexWrapper
52
+ from langchain_core.language_models.base import BaseLanguageModel
53
+ except ImportError:
54
+ print("Please install the required packages.")
55
+ print("pip install 'le_map_tools[ai]'")
56
+
57
+ # Third-party imports
58
+ import iso8601
59
+ import tenacity
60
+ from tenacity import (
61
+ retry,
62
+ stop_after_attempt,
63
+ wait_exponential,
64
+ retry_if_exception_type,
65
+ )
66
+
67
+ from .le_map_tools import Map, get_env_var, js_snippet_to_py, ee_initialize, temp_file_path
68
+
69
+ # Google Colab-specific imports (only if you're working in Google Colab)
70
+ if "google.colab" in sys.modules:
71
+ from google.colab import output, data_table, syntax
72
+
73
+
74
+ class Genie(widgets.VBox):
75
+ """A widget for interacting with the Genie AI model.
76
+
77
+ The source code is adapted from the ee_genie.ipynb at <https://bit.ly/3YEm7B6>.
78
+ Credit to the original author Simon Ilyushchenko (<https://github.com/simonff>).
79
+
80
+ Args:
81
+ project (Optional[str], optional): Google Cloud project ID. Defaults to None.
82
+ google_api_key (Optional[str], optional): Google API key. Defaults to None.
83
+ gemini_model (str, optional): The Gemini model to use. Defaults to "gemini-1.5-flash".
84
+ For a list of available models, see https://bit.ly/4fKfXW7.
85
+ target_score (float, optional): The target score for the model. Defaults to 0.8.
86
+ widget_height (str, optional): The height of the widget. Defaults to "600px".
87
+ initialize_ee (bool, optional): Whether to initialize Earth Engine. Defaults to True.
88
+
89
+ Raises:
90
+ ValueError: If the project ID or Google API key is not provided.
91
+ """
92
+
93
+ def __init__(
94
+ self,
95
+ project: Optional[str] = None,
96
+ google_api_key: Optional[str] = None,
97
+ gemini_model: str = "gemini-1.5-flash",
98
+ target_score: float = 0.8,
99
+ widget_height: str = "600px",
100
+ initialize_ee: bool = True,
101
+ ) -> None:
102
+ # Initialization
103
+
104
+ if project is None:
105
+ project = get_env_var("EE_PROJECT_ID") or get_env_var("GOOGLE_PROJECT_ID")
106
+ if project is None:
107
+ raise ValueError(
108
+ "Please provide a valid project ID via the 'project' parameter."
109
+ )
110
+
111
+ if google_api_key is None:
112
+ google_api_key = get_env_var("GOOGLE_API_KEY")
113
+ if google_api_key is None:
114
+ raise ValueError(
115
+ "Please provide a valid Google API key via the 'google_api_key' parameter."
116
+ )
117
+
118
+ if initialize_ee:
119
+ ee_initialize(project=project)
120
+
121
+ genai.configure(api_key=google_api_key)
122
+ storage_client = storage.Client(project=project)
123
+ bucket = storage_client.get_bucket("earthengine-stac")
124
+
125
+ # Score to aim for (on the 0-1 scale). The exact meaning of what "score" means
126
+ # is left to the LLM.
127
+
128
+ # Count of analysis rounds
129
+
130
+ self.iteration = 1
131
+ self.map_dirty = False
132
+
133
+ m = Map()
134
+ m.add("layer_manager")
135
+ self.map = m
136
+
137
+ analysis_model = None
138
+
139
+ image_model = genai.GenerativeModel(gemini_model)
140
+
141
+ # UI widget definitions
142
+
143
+ # We define the widgets early because some functions will write to the debug
144
+ # and/or chat panels.
145
+
146
+ command_input = widgets.Text(
147
+ value="show a whole continent Australia DEM visualization using a palette that captures the elevation range",
148
+ # value='show NYC',
149
+ # value='show an area with many center pivot irrigation circles',
150
+ # value='show a fire scar',
151
+ # value='show an open pit mine',
152
+ # value='a sea port',
153
+ # value='flood consequences',
154
+ # value='show an interesting modis composite with the relevant visualization and analyze it over Costa Rica',
155
+ description="❓",
156
+ layout=widgets.Layout(width="100%", height="50px"),
157
+ )
158
+
159
+ command_output = widgets.Label(
160
+ value="Last command will be here",
161
+ )
162
+
163
+ status_label = widgets.Textarea(
164
+ value="LLM response will be here",
165
+ layout=widgets.Layout(width="50%", height="100px"),
166
+ )
167
+
168
+ # widget_height = "600px"
169
+ debug_output = widgets.Output(
170
+ layout={
171
+ "border": "1px solid black",
172
+ "height": widget_height,
173
+ "overflow": "scroll",
174
+ "width": "500px",
175
+ "padding": "5px",
176
+ }
177
+ )
178
+ with debug_output:
179
+ print("DEBUG COLUMN\n")
180
+
181
+ logo = requests.get(
182
+ "https://drive.usercontent.google.com/download?id=1zE6G_nxXa3G5N0G_32jEhzdum2kMDfNY&export=view&authuser=0"
183
+ ).content
184
+
185
+ image_widget = widgets.Image(value=logo, format="png", width=400, height=600)
186
+
187
+ chat_output = widgets.Output(
188
+ layout={
189
+ "border": "1px solid black",
190
+ "height": "600px",
191
+ "overflow": "scroll",
192
+ "width": "300px",
193
+ }
194
+ )
195
+
196
+ with chat_output:
197
+ print("CHAT COLUMN\n")
198
+
199
+ # Simple functions that LLM will call
200
+
201
+ def set_center(x: float, y: float, zoom: int) -> str:
202
+ """Sets the map center to the given coordinates and zoom level and
203
+ returns instructions on what to do next."""
204
+ with debug_output:
205
+ print(f"SET_CENTER({x}, {y}, {zoom})\n")
206
+ m.set_center(x, y)
207
+ m.zoom = zoom
208
+ # global map_dirty
209
+ self.map_dirty = True
210
+ return (
211
+ "Do not call any more functions in this request to let le_map_tools bounds "
212
+ "update. Wait for user input."
213
+ )
214
+
215
+ def add_image_layer(image_id: str) -> str:
216
+ """Adds to the map center an ee.Image with the given id
217
+ and returns status message (success or failure)."""
218
+ m.clear()
219
+ command_output.value = f"add_image_layer('{image_id}')"
220
+ m.addLayer(le.Image(image_id))
221
+ return "success"
222
+
223
+ def get_dataset_description(dataset_id: str) -> str:
224
+ """Fetches JSON STAC description for the given Earth Engine dataset id."""
225
+ with debug_output:
226
+ print(f"LOOKING UP {dataset_id}\n")
227
+ parent = dataset_id.split("/")[0]
228
+
229
+ # Get the blob (file)
230
+ path = (
231
+ os.path.join("catalog", parent, dataset_id.replace("/", "_")) + ".json"
232
+ )
233
+ blob = bucket.blob(path)
234
+
235
+ if not blob.exists():
236
+ return "dataset file not found: " + path
237
+
238
+ file_contents = blob.download_as_string().decode()
239
+ return file_contents
240
+
241
+ def get_image(image_url: str) -> bytes:
242
+ """Fetches from Earth Engine the content of the given URL as bytes."""
243
+ response = requests.get(image_url)
244
+
245
+ if response.status_code == 200:
246
+ image_widget.value = response.content
247
+ return response.content
248
+ else:
249
+ error_message = f"Error downloading image: {response}"
250
+ try:
251
+ error_details = (
252
+ json.loads(response.content.decode())
253
+ .get("error", {})
254
+ .get("message")
255
+ )
256
+ if error_details:
257
+ error_message += f" - {error_details}"
258
+ except json.JSONDecodeError:
259
+ pass
260
+ with debug_output:
261
+ print(error_message)
262
+ raise ValueError("URL %s causes %s" % (image_url, error_message))
263
+
264
+ def show_layer(python_code: str) -> str:
265
+ """Execute the given Earth Engine Python client code and add the result to
266
+ the map. Returns the status message (success or error message)."""
267
+ m.layers = m.layers[:2]
268
+ while '\\"' in python_code:
269
+ python_code = python_code.replace('\\"', '"')
270
+ command_output.value = f"show_layer('{python_code}')"
271
+ with debug_output:
272
+ print(f"IMAGE:\n {python_code}\n")
273
+ try:
274
+ locals = {}
275
+ exec(f"import ee; im = {python_code}", {}, locals)
276
+ m.addLayer(locals["im"])
277
+ except Exception as e:
278
+ with debug_output:
279
+ print(f"ERROR: {e}")
280
+ return str(e)
281
+ return "success"
282
+
283
+ def inner_monologue(thoughts: str) -> str:
284
+ """Sends the current thinking of the LLM model to the user so that they are
285
+ aware of what the model is thinking between function calls."""
286
+ with debug_output:
287
+ print(f"THOUGHTS:\n {thoughts}\n")
288
+ return "success"
289
+
290
+ # Functions for textual analysis of images
291
+
292
+ def _lat_lon_to_tile(lon, lat, zoom_level):
293
+ # Convert latitude and longitude to Mercator coordinates
294
+ x_merc = (lon + 180) / 360
295
+ y_merc = (
296
+ 1
297
+ - math.log(
298
+ math.tan(math.radians(lat)) + 1 / math.cos(math.radians(lat))
299
+ )
300
+ / math.pi
301
+ ) / 2
302
+
303
+ # Calculate number of tiles
304
+ n = 2**zoom_level
305
+
306
+ # Convert to tile coordinates
307
+ X = int(x_merc * n)
308
+ Y = int(y_merc * n)
309
+
310
+ return X, Y
311
+
312
+ def analyze_image(additional_instructions: str = "") -> str:
313
+ """Returns GenAI image analysis describing the current map image.
314
+ Optional additional instructions might be passed to target the analysis
315
+ more precisely.
316
+ """
317
+ # global map_dirty
318
+ if self.map_dirty:
319
+ print("MAP DIRTY")
320
+ return (
321
+ "Map is not ready. Stop further processing and ask for user input"
322
+ )
323
+
324
+ try:
325
+ return _analyze_image(additional_instructions)
326
+ except ValueError as e:
327
+ return str(e)
328
+
329
+ def _analyze_image(additional_instructions: str = "") -> str:
330
+ # bounds = m.bounds
331
+ # s, w = bounds[0]
332
+ # n, e = bounds[1]
333
+ # zoom = int(m.zoom)
334
+
335
+ # min_tile_x, max_tile_y = _lat_lon_to_tile(w, s, zoom)
336
+ # max_tile_x, min_tile_y = _lat_lon_to_tile(e, n, zoom)
337
+ # min_tile_x = max(0, min_tile_x)
338
+ # max_tile_x = min(2**zoom - 1, max_tile_x)
339
+ # min_tile_y = max(0, min_tile_y)
340
+ # max_tile_y = min(2**zoom - 1, max_tile_y)
341
+
342
+ # with debug_output:
343
+ # if additional_instructions:
344
+ # print(f"RUNNING IMAGE ANALYSIS: {additional_instructions}...\n")
345
+ # else:
346
+ # print("RUNNING IMAGE ANALYSIS...\n")
347
+
348
+ # layers = list(m.ee_layer_dict.values())
349
+ # if not layers:
350
+ # return "No data layers loaded"
351
+ # url_template = layers[-1]["ee_layer"].url
352
+ # tile_width = 256
353
+ # tile_height = 256
354
+ # image_width = (max_tile_x - min_tile_x + 1) * tile_width
355
+ # image_height = (max_tile_y - min_tile_y + 1) * tile_height
356
+
357
+ # # Create a new blank image
358
+ # image = PIL.Image.new("RGB", (image_width, image_height))
359
+
360
+ # for y in range(min_tile_y, max_tile_y + 1):
361
+ # for x in range(min_tile_x, max_tile_x + 1):
362
+ # tile_url = str.format(url_template, x=x, y=y, z=zoom)
363
+ # # print(tile_url)
364
+ # tile_img = PIL.Image.open(io.BytesIO(get_image(tile_url)))
365
+
366
+ # offset_x = (x - min_tile_x) * tile_width
367
+ # offset_y = (y - min_tile_y) * tile_height
368
+ # image.paste(tile_img, (offset_x, offset_y))
369
+
370
+ # width, height = image.size
371
+ # num_bands = len(image.getbands())
372
+
373
+ with debug_output:
374
+ if additional_instructions:
375
+ print(f"RUNNING IMAGE ANALYSIS: {additional_instructions}...\n")
376
+ else:
377
+ print("RUNNING IMAGE ANALYSIS...\n")
378
+
379
+ layers = list(m.ee_layer_dict.values())
380
+ if not layers:
381
+ return "No data layers loaded"
382
+ image_temp_file = temp_file_path(extension="jpg")
383
+ layer_name = layers[-1]["ee_layer"].name
384
+ m.layer_to_image(layer_name, output=image_temp_file, scale=m.get_scale())
385
+ image = PIL.Image.open(image_temp_file)
386
+
387
+ image_array = np.array(image)
388
+ image_min = np.min(image_array)
389
+ image_max = np.max(image_array)
390
+
391
+ file = open(image_temp_file, "rb")
392
+ image_widget.value = file.read()
393
+ file.close()
394
+
395
+ # Skip an LLM call when we can simply tell that something is wrong.
396
+ # (Also, LLMs might hallucinate on uniform images.)
397
+ if image_min == image_max:
398
+ return (
399
+ f"The image tile has a single uniform color with value "
400
+ f"{image_min}."
401
+ )
402
+
403
+ query = """You are an objective, precise overhead imagery analyst.
404
+ Describe what the provided map tile depicts in terms of:
405
+
406
+ 1. The colors, textures, and patterns visible in the image.
407
+ 2. The spatial distribution, shape, and extent of distinct features or regions.
408
+ 3. Any notable contrasts, boundaries, or gradients between different areas.
409
+
410
+ Avoid making assumptions about the specific geographic location, time period,
411
+ or cause of the observed features. Focus solely on the literal contents of the
412
+ image itself. Clearly indicate which features look natural, which look human-made,
413
+ and which look like image artifacts. (Eg, a completely straight blue line
414
+ is unlikely to be a river.)
415
+
416
+ If the image is ambiguous or unclear, state so directly. Do not speculate or
417
+ hypothesize beyond what is directly visible.
418
+
419
+ If the image is of mostly the same color (white, gray, or black) with little
420
+ contrast, just report that and do not describe the features.
421
+
422
+ Use clear, concise language. Avoid subjective interpretations or analogies.
423
+ Organize your response into structured paragraphs.
424
+ """
425
+ if additional_instructions:
426
+ query += additional_instructions
427
+ req = {
428
+ "parts": [
429
+ {"text": query},
430
+ {"inline_data": image},
431
+ ]
432
+ }
433
+ image_response = image_model.generate_content(req)
434
+ try:
435
+ with debug_output:
436
+ print(f"ANALYSIS RESULT: {image_response.text}\n")
437
+ return image_response.text
438
+ except ValueError as e:
439
+ with debug_output:
440
+ print(f"UNEXPECTED IMAGE RESPONSE: {e}")
441
+ print(image_response)
442
+ breakpoint()
443
+
444
+ # Function for scoring how well image analysis corresponds to the user query.
445
+
446
+ # Note that we ask for the score outside of the main agent chat to keep
447
+ # the scoring more objective.
448
+
449
+ scoring_system_prompt = """
450
+ After looking at the user query and the map tile analysis, start
451
+ your answer with a number between 0 and 1 indicating how relevant
452
+ the image is as an answer to the query. (0=irrelevant, 1=perfect answer)
453
+
454
+ Make sure you have enough justification to definitively declare the analysis
455
+ relevant - it's better to give a false negative than a false positive. However,
456
+ the image analysis identifies specific matching landmarks (eg, the
457
+ the outlines of Manhattan island for a request to show NYC), believe it.
458
+
459
+ Do not assume too much (eg, that the presence of green doesn't by itself mean the
460
+ image shows forest); attempt to find multiple (at least three) independent
461
+ lines of evidence before declaring victory and cite all these lines of evidence
462
+ in your response.
463
+
464
+ Be very, very skeptical - look for specific features that match only the query
465
+ and nothing else (eg, if the query looks for a river, a completely straight blue
466
+ line is unlikely to be a river). Think about what size the features are based on
467
+ the zoom level and whether this size matches the feature size expected from
468
+ first principles.
469
+
470
+ If there is ambiguity or uncertainty, express it in your analysis and
471
+ lower the score accordingly. If the image analysis is inconclusive, try zooming
472
+ out to make sure you are looking at the right spot. Do not reduce the score if
473
+ the analysis does not mention visualization parameters - they are just given for
474
+ your reference. The image might show an area slightly larger than requested -
475
+ this is okay, do not reduce the score on this account.
476
+ """
477
+
478
+ def score_response(
479
+ query: str, visualization_parameters: str, analysis: str
480
+ ) -> str:
481
+ """Returns how well the given analysis describes a map tile returned for
482
+ the given query. The analysis starts with a number between 0 and 1.
483
+
484
+ Arguments:
485
+ query: user-specified query
486
+ visualization_parameters: description of the bands used and visualization
487
+ parameters applied to the map tile
488
+ analysis: the textual description of the map tile
489
+ """
490
+ with debug_output:
491
+ print(f"VIZ PARAMS: {visualization_parameters}\n")
492
+ question = f"""For user query {query} please score the following analysis:
493
+ {analysis}. The answer must start with a number between 0 and 1."""
494
+ if visualization_parameters:
495
+ question += f"""Do not assume that common bands or visualization
496
+ parameters should have been used, as the visualization used the
497
+ following parameters: {visualization_parameters}"""
498
+
499
+ result = analysis_model.ask(question)
500
+ # global iteration
501
+ with debug_output:
502
+ print(f"SCORE #{self.iteration}:\n {result}\n")
503
+ try:
504
+ self.iteration += 1
505
+ except Exception as e:
506
+ with debug_output:
507
+ print(f"UNEXPECTED SCORE RESPONSE: {e}")
508
+ return result
509
+
510
+ # Main prompt for the agent
511
+
512
+ system_prompt = f"""
513
+ The client is running in a Python notebook with a le_map_tools Map displayed.
514
+ When composing Python code, do not use getMapId - just return the single-line
515
+ layer definition like 'ee.Image("USGS/SRTMGL1_003")' that we will pass to
516
+ Map.addLayer(). Do not escape quotation marks in Python code.
517
+
518
+ Be sure to use Python, not Javascript, syntax for keyword parameters in
519
+ Python code (that is, "function(arg=value)") Using the provided functions,
520
+ respond to the user command following below (or respond why it's not possible).
521
+ If you get an Earth Engine error, attempt to fix it and then try again.
522
+
523
+ Before you choose a dataset, think about what kind of dataset would be most
524
+ suitable for the query. Also think about what zoom level would be suitable for
525
+ the query, keeping in mind that for high-resolution image collections higher
526
+ zoom levels are better to speed up tile loading.
527
+
528
+ Once you have chosen a dataset, read its description using the provided function
529
+ to see what spatial and temporal range it covers, what bands it has, as well as
530
+ to find the recommended visualization parameters. Explain using the inner
531
+ monlogue function why you chose a specific dataset, zoom level and map location.
532
+
533
+ Prefer mosaicing image collections using the mosaic() function, don't get
534
+ individual images from collections via
535
+ 'first()'. Choose a tile size and zoom level that will ensure the
536
+ tile has enough pixels in it to avoid graininess, but not so many
537
+ that processing becomes very expensive. Do not use wide date ranges
538
+ with collections that have many images, but remember that Landsat and
539
+ Sentinel-2 have revisit period of several days. Do not use sample
540
+ locations - try to come up with actual locations that are relevant to
541
+ the request.
542
+
543
+ Use Landsat Collection 2, not Landsat Collection 1 ids. If you are getting
544
+ repeated errors when filtering by a time range, read the dataset description
545
+ to confirm that the dataset has data for the selected range.
546
+
547
+ Important: after using the set_center() function, just say that you have called
548
+ this function and wait for the user to hit enter, after which you should
549
+ continue answering the original request. This will make sure the map is updated
550
+ on the client side.
551
+
552
+ Once the map is updated and the user told you to proceed, call the analyze_image
553
+ function() to describe the image for the same location that will be shown in
554
+ le_map_tools. If you pass additional instructions to analyze_image(), do not disclose
555
+ what the image is supposed to be to discourage hallucinations - you can only tell
556
+ the analysis function to pay attention to specific areas (eg, center or top left)
557
+ or shapes (eg, a line at the bottom) in the image. You can also tell the analysis
558
+ function about the chosen bands, color palette and min/max visualization
559
+ parameters, if any, to help it interpret the colors correctly. If the image
560
+ turns out to be uniform in color with no features,
561
+ use min/max visualization parameters to enhance contrast.
562
+
563
+ Frequently call the inner_monologue() functions to tell the user about your
564
+ current thought process. This is a good time to reflect if you have been running
565
+ into repeated errors of the same kind, and if so, to try a different approach.
566
+
567
+ When you are done, call the score_response() function to evaluate the analysis.
568
+ You can also tell the scoring function about the chosen bands, color palette
569
+ and min/max visualization parameters, if any. If the analysis score is below
570
+ {target_score},
571
+ keep trying to find and show a better image. You might have to change the dataset,
572
+ map location, zoom level, date range, bands, or other parameters - think about
573
+ what went wrong in the previous attempt and make the change that's most likely
574
+ to improve the score.
575
+ """
576
+
577
+ # Class for LLM chat with function calling
578
+
579
+ gemini_tools = [
580
+ set_center,
581
+ show_layer,
582
+ analyze_image,
583
+ inner_monologue,
584
+ get_dataset_description,
585
+ score_response,
586
+ ]
587
+
588
+ class Gemini:
589
+ """Gemini LLM."""
590
+
591
+ def __init__(
592
+ self, system_prompt, tools=None, model_name="gemini-1.5-pro-latest"
593
+ ):
594
+ if not tools:
595
+ tools = []
596
+ self._text_model = genai.GenerativeModel(
597
+ model_name=model_name, tools=tools
598
+ )
599
+
600
+ initial_messages = glm.Content(
601
+ role="model", parts=[glm.Part(text=system_prompt)]
602
+ )
603
+ self._chat_proxy = self._text_model.start_chat(
604
+ history=initial_messages, enable_automatic_function_calling=True
605
+ )
606
+
607
+ def ask(self, question, temperature=0):
608
+ while True:
609
+ condition = ""
610
+ try:
611
+ sleep_duration = 10
612
+ response = self._text_model.generate_content(
613
+ question + condition
614
+ )
615
+ return response.text
616
+ except genai.types.generation_types.StopCandidateException as e:
617
+ if (
618
+ glm.Candidate.FinishReason.RECITATION
619
+ == e.args[0].finish_reason
620
+ ):
621
+ condition = (
622
+ "Previous attempt returned a RECITATION error. "
623
+ "Rephrase the answer to avoid it."
624
+ )
625
+ with chat_output:
626
+ command_input.description = "🆁"
627
+ time.sleep(1)
628
+ with chat_output:
629
+ command_input.description = "🤔"
630
+ continue
631
+ except (
632
+ google.api_core.exceptions.TooManyRequests,
633
+ google.api_core.exceptions.DeadlineExceeded,
634
+ ):
635
+ with debug_output:
636
+ command_input.description = "💤"
637
+ time.sleep(sleep_duration)
638
+ continue
639
+ except ValueError as e:
640
+ with debug_output:
641
+ print(f"Response {response} led to error: {e}")
642
+ breakpoint()
643
+ i = 1
644
+
645
+ def chat(self, question: str, temperature=0) -> str:
646
+ """Adds a question to the ongoing chat session."""
647
+ # Always delay a bit to reduce the chance for rate-limiting errors.
648
+ time.sleep(1)
649
+ condition = ""
650
+ sleep_duration = 10
651
+ while True:
652
+ response = ""
653
+ try:
654
+ response = self._chat_proxy.send_message(
655
+ question + condition,
656
+ generation_config={
657
+ "temperature": temperature,
658
+ # Use a generous but limited output size to encourage in-depth
659
+ # replies.
660
+ "max_output_tokens": 5000,
661
+ },
662
+ )
663
+ if not response.parts:
664
+ raise ValueError(
665
+ "Cannot get analysis with reason"
666
+ f" {response.candidates[0].finish_reason.name}, terminating"
667
+ )
668
+ except genai.types.generation_types.StopCandidateException as e:
669
+ if (
670
+ glm.Candidate.FinishReason.RECITATION
671
+ == e.args[0].finish_reason
672
+ ):
673
+ condition = (
674
+ "Previous attempt returned a RECITATION error. "
675
+ "Rephrase the answer to avoid it."
676
+ )
677
+ with chat_output:
678
+ command_input.description = "🆁"
679
+ time.sleep(1)
680
+ with chat_output:
681
+ command_input.description = "🤔"
682
+ continue
683
+ except (
684
+ google.api_core.exceptions.TooManyRequests,
685
+ google.api_core.exceptions.DeadlineExceeded,
686
+ ):
687
+ with debug_output:
688
+ command_input.description = "💤"
689
+ time.sleep(10)
690
+ continue
691
+ try:
692
+ return response.text
693
+ except ValueError as e:
694
+ with debug_output:
695
+ print(f"Response {response} led to the error {e}")
696
+
697
+ model = Gemini(system_prompt, gemini_tools, model_name=gemini_model)
698
+ analysis_model = Gemini(scoring_system_prompt, model_name=gemini_model)
699
+
700
+ # UI functions
701
+
702
+ def set_cursor_waiting():
703
+ js_code = """
704
+ document.querySelector('body').style.cursor = 'wait';
705
+ """
706
+ display(HTML(f"<script>{js_code}</script>"))
707
+
708
+ def set_cursor_default():
709
+ js_code = """
710
+ document.querySelector('body').style.cursor = 'default';
711
+ """
712
+ display(HTML(f"<script>{js_code}</script>"))
713
+
714
+ def on_submit(widget):
715
+ # global map_dirty
716
+ self.map_dirty = False
717
+ command_input.description = "❓"
718
+ command = widget.value
719
+ if not command:
720
+ command = "go on"
721
+ with chat_output:
722
+ print("> " + command + "\n")
723
+ if command != "go on":
724
+ with debug_output:
725
+ print("> " + command + "\n")
726
+ widget.value = ""
727
+ set_cursor_waiting()
728
+ command_input.description = "🤔"
729
+ response = model.chat(command, temperature=0)
730
+ if self.map_dirty:
731
+ command_input.description = "🙏"
732
+ else:
733
+ command_input.description = "❓"
734
+ set_cursor_default()
735
+ response = response.strip()
736
+ if not response:
737
+ response = "<EMPTY RESPONSE, HIT ENTER>"
738
+ with chat_output:
739
+ print(response + "\n")
740
+ command_input.value = ""
741
+
742
+ command_input.on_submit(on_submit)
743
+
744
+ # UI layout
745
+
746
+ # Arrange the chat history and input in a vertical box
747
+ chat_ui = widgets.VBox(
748
+ [image_widget, chat_output],
749
+ layout=widgets.Layout(width="420px", height=widget_height),
750
+ )
751
+
752
+ chat_output.layout = widgets.Layout(
753
+ width="400px"
754
+ ) # Fixed width for the left control
755
+ m.layout = widgets.Layout(flex="1 1 auto", height=widget_height)
756
+
757
+ table = widgets.HBox(
758
+ [chat_ui, debug_output, m], layout=widgets.Layout(align_items="flex-start")
759
+ )
760
+
761
+ message_widget = widgets.Output()
762
+ with message_widget:
763
+ print("❓ = waiting for user input")
764
+ print("🙏 = waiting for user to hit enter after calling set_center()")
765
+ print("🤔 = thinking")
766
+ print("💤 = sleeping due to retries")
767
+ print("🆁 = Gemini recitation error")
768
+
769
+ super().__init__(
770
+ [table, command_input, message_widget], layout={"overflow": "hidden"}
771
+ )
772
+
773
+
774
+ def matches_interval(
775
+ collection_interval: Tuple[datetime.datetime, datetime.datetime],
776
+ query_interval: Tuple[datetime.datetime, datetime.datetime],
777
+ ) -> bool:
778
+ """Checks if the collection's datetime interval matches the query datetime interval.
779
+
780
+ Args:
781
+ collection_interval (Tuple[datetime.datetime, datetime.datetime]):
782
+ Temporal interval of the collection.
783
+ query_interval (Tuple[datetime.datetime, datetime.datetime]): A tuple
784
+ with the query interval start and end.
785
+
786
+ Returns:
787
+ bool: True if the datetime interval matches, False otherwise.
788
+ """
789
+ start_query, end_query = query_interval
790
+ start_collection, end_collection = collection_interval
791
+ if end_collection is None:
792
+ # End date should always be set in STAC JSON files, but just in case...
793
+ end_collection = datetime.datetime.now(tz=datetime.UTC)
794
+ return end_query > start_collection and start_query <= end_collection
795
+
796
+
797
+ def matches_datetime(
798
+ collection_interval: Tuple[datetime.datetime, Optional[datetime.datetime]],
799
+ query_datetime: datetime.datetime,
800
+ ) -> bool:
801
+ """Checks if the collection's datetime interval matches the query datetime.
802
+
803
+ Args:
804
+ collection_interval (Tuple[datetime.datetime, Optional[datetime.datetime]]):
805
+ Temporal interval of the collection.
806
+ query_datetime (datetime.datetime): A datetime coming from a query.
807
+
808
+ Returns:
809
+ bool: True if the datetime interval matches, False otherwise.
810
+ """
811
+ if collection_interval[1] is None:
812
+ # End date should always be set in STAC JSON files, but just in case...
813
+ end_date = datetime.datetime.now(tz=datetime.UTC)
814
+ else:
815
+ end_date = collection_interval[1]
816
+ return collection_interval[0] <= query_datetime <= end_date
817
+
818
+
819
+ @tenacity.retry(
820
+ stop=tenacity.stop_after_attempt(3),
821
+ wait=tenacity.wait_fixed(1),
822
+ retry=tenacity.retry_if_exception_type(LayerException),
823
+ # before_sleep=lambda retry_state: print(f"LayerException occurred. Retrying in 1 seconds... (Attempt {retry_state.attempt_number}/3)")
824
+ )
825
+ def run_ee_code(code: str, ee: Any, geemap_instance: Map) -> None:
826
+ """Executes Earth Engine Python code within the context of a le_map_tools instance.
827
+
828
+ Args:
829
+ code (str): The Earth Engine Python code to execute.
830
+ ee (Any): The Earth Engine module.
831
+ geemap_instance (Map): The le_map_tools instance.
832
+
833
+ Raises:
834
+ Exception: Re-raises any exception encountered during code execution.
835
+ """
836
+ try:
837
+ # le_map_tools appears to have some stray print statements.
838
+ _ = io.StringIO()
839
+ with redirect_stdout(_):
840
+ # Note that sometimes the le_map_tools code uses both 'Map' and 'm' to refer to a map instance.
841
+ exec(code, {"ee": ee, "Map": geemap_instance, "m": geemap_instance})
842
+ except Exception:
843
+ # Re-raise the exception with the original traceback
844
+ exc_type, exc_value, exc_traceback = sys.exc_info()
845
+ raise exc_value.with_traceback(exc_traceback)
846
+
847
+
848
+ @dataclasses.dataclass
849
+ class BBox:
850
+ """Class representing a lat/lon bounding box."""
851
+
852
+ west: float
853
+ south: float
854
+ east: float
855
+ north: float
856
+
857
+ def is_global(self) -> bool:
858
+ """Checks if the bounding box is global.
859
+
860
+ Returns:
861
+ bool: True if the bounding box is global, False otherwise.
862
+ """
863
+ return (
864
+ self.west == -180
865
+ and self.south == -90
866
+ and self.east == 180
867
+ and self.north == 90
868
+ )
869
+
870
+ @classmethod
871
+ def from_list(cls, bbox_list: List[float]) -> "BBox":
872
+ """Constructs a BBox from a list of four numbers [west, south, east, north].
873
+
874
+ Args:
875
+ bbox_list (List[float]): List of four numbers representing the bounding box.
876
+
877
+ Returns:
878
+ BBox: The constructed BBox object.
879
+
880
+ Raises:
881
+ ValueError: If the coordinates are not in the correct order.
882
+ """
883
+ if bbox_list[0] > bbox_list[2]:
884
+ raise ValueError(
885
+ "The smaller (west) coordinate must be listed first in a bounding box"
886
+ f" corner list. Found {bbox_list}"
887
+ )
888
+ if bbox_list[1] > bbox_list[3]:
889
+ raise ValueError(
890
+ "The smaller (south) coordinate must be listed first in a bounding"
891
+ f" box corner list. Found {bbox_list}"
892
+ )
893
+ return cls(bbox_list[0], bbox_list[1], bbox_list[2], bbox_list[3])
894
+
895
+ def to_list(self) -> List[float]:
896
+ """Converts the BBox to a list of four numbers [west, south, east, north].
897
+
898
+ Returns:
899
+ List[float]: List of four numbers representing the bounding box.
900
+ """
901
+ return [self.west, self.south, self.east, self.north]
902
+
903
+ def intersects(self, query_bbox: "BBox") -> bool:
904
+ """Checks if this bbox intersects with the query bbox.
905
+
906
+ Doesn't handle bboxes extending past the antimeridian.
907
+
908
+ Args:
909
+ query_bbox (BBox): Bounding box from the query.
910
+
911
+ Returns:
912
+ bool: True if the two bounding boxes intersect, False otherwise.
913
+ """
914
+ return (
915
+ query_bbox.west < self.east
916
+ and query_bbox.east > self.west
917
+ and query_bbox.south < self.north
918
+ and query_bbox.north > self.south
919
+ )
920
+
921
+
922
+ class Collection:
923
+ """A simple wrapper for a STAC Collection.."""
924
+
925
+ stac_json: dict[str, Any]
926
+
927
+ def __init__(self, stac_json: Dict[str, Any]) -> None:
928
+ """Initializes the Collection.
929
+
930
+ Args:
931
+ stac_json (Dict[str, Any]): The STAC JSON of the collection.
932
+ """
933
+ self.stac_json = stac_json
934
+ if stac_json.get("gee:status") == "deprecated":
935
+ # Set the STAC 'deprecated' field that we don't set in the jsonnet files
936
+ stac_json["deprecated"] = True
937
+
938
+ def __getitem__(self, item: str) -> Any:
939
+ """Gets an item from the STAC JSON.
940
+
941
+ Args:
942
+ item (str): The key of the item to get.
943
+
944
+ Returns:
945
+ Any: The value of the item.
946
+ """
947
+ return self.stac_json[item]
948
+
949
+ def get(self, item: str, default: Optional[Any] = None) -> Optional[Any]:
950
+ """Matches dict's get by returning None if there is no item.
951
+
952
+ Args:
953
+ item (str): The key of the item to get.
954
+ default (Optional[Any]): The default value to return if the item is not found. Defaults to None.
955
+
956
+ Returns:
957
+ Optional[Any]: The value of the item or the default value.
958
+ """
959
+ return self.stac_json.get(item, default)
960
+
961
+ def public_id(self) -> str:
962
+ """Gets the public ID of the collection.
963
+
964
+ Returns:
965
+ str: The public ID of the collection.
966
+ """
967
+ return self["id"]
968
+
969
+ def hyphen_id(self) -> str:
970
+ """Gets the hyphenated ID of the collection.
971
+
972
+ Returns:
973
+ str: The hyphenated ID of the collection.
974
+ """
975
+ return self["id"].replace("/", "_")
976
+
977
+ def get_dataset_type(self) -> str:
978
+ """Gets the dataset type of the collection.
979
+
980
+ Returns:
981
+ str: The dataset type of the collection.
982
+ """
983
+ return self["gee:type"]
984
+
985
+ def is_deprecated(self) -> bool:
986
+ """Checks if the collection is deprecated or has a successor.
987
+
988
+ Returns:
989
+ bool: True if the collection is deprecated or has a successor, False otherwise.
990
+ """
991
+ if self.get("deprecated", False):
992
+ logging.info("Skipping deprecated collection: %s", self.public_id())
993
+ return True
994
+
995
+ def datetime_interval(
996
+ self,
997
+ ) -> Iterable[Tuple[datetime.datetime, Optional[datetime.datetime]]]:
998
+ """Returns datetime objects representing temporal extents.
999
+
1000
+ Returns:
1001
+ Iterable[Tuple[datetime.datetime, Optional[datetime.datetime]]]:
1002
+ An iterable of tuples representing temporal extents.
1003
+
1004
+ Raises:
1005
+ ValueError: If the temporal interval start is not found.
1006
+ """
1007
+ for stac_interval in self.stac_json["extent"]["temporal"]["interval"]:
1008
+ if not stac_interval[0]:
1009
+ raise ValueError(
1010
+ "Expected a non-empty temporal interval start for "
1011
+ + self.public_id()
1012
+ )
1013
+ start_date = iso8601.parse_date(stac_interval[0])
1014
+ if stac_interval[1] is not None:
1015
+ end_date = iso8601.parse_date(stac_interval[1])
1016
+ else:
1017
+ end_date = None
1018
+ yield (start_date, end_date)
1019
+
1020
+ def start(self) -> datetime.datetime:
1021
+ """Gets the start datetime of the collection.
1022
+
1023
+ Returns:
1024
+ datetime.datetime: The start datetime of the collection.
1025
+ """
1026
+ return list(self.datetime_interval())[0][0]
1027
+
1028
+ def start_str(self) -> str:
1029
+ """Gets the start datetime of the collection as a string.
1030
+
1031
+ Returns:
1032
+ str: The start datetime of the collection as a string.
1033
+ """
1034
+ if not self.start():
1035
+ return ""
1036
+ return self.start().strftime("%Y-%m-%d")
1037
+
1038
+ def end(self) -> Optional[datetime.datetime]:
1039
+ """Gets the end datetime of the collection.
1040
+
1041
+ Returns:
1042
+ Optional[datetime.datetime]: The end datetime of the collection.
1043
+ """
1044
+ return list(self.datetime_interval())[0][1]
1045
+
1046
+ def end_str(self) -> str:
1047
+ """Gets the end datetime of the collection as a string.
1048
+
1049
+ Returns:
1050
+ str: The end datetime of the collection as a string.
1051
+ """
1052
+ if not self.end():
1053
+ return ""
1054
+ return self.end().strftime("%Y-%m-%d")
1055
+
1056
+ def bbox_list(self) -> Sequence[BBox]:
1057
+ """Gets the bounding boxes of the collection.
1058
+
1059
+ Returns:
1060
+ Sequence[BBox]: A sequence of bounding boxes.
1061
+ """
1062
+ if "extent" not in self.stac_json:
1063
+ # Assume global if nothing listed.
1064
+ return (BBox(-180, -90, 180, 90),)
1065
+ return tuple(
1066
+ [BBox.from_list(x) for x in self.stac_json["extent"]["spatial"]["bbox"]]
1067
+ )
1068
+
1069
+ def bands(self) -> List[Dict[str, Any]]:
1070
+ """Gets the bands of the collection.
1071
+
1072
+ Returns:
1073
+ List[Dict[str, Any]]: A list of dictionaries representing the bands.
1074
+ """
1075
+ summaries = self.stac_json.get("summaries")
1076
+ if not summaries:
1077
+ return []
1078
+ return summaries.get("eo:bands", [])
1079
+
1080
+ def spatial_resolution_m(self) -> float:
1081
+ """Gets the spatial resolution of the collection in meters.
1082
+
1083
+ Returns:
1084
+ float: The spatial resolution of the collection in meters.
1085
+ """
1086
+ summaries = self.stac_json.get("summaries")
1087
+ if not summaries:
1088
+ return -1
1089
+ if summaries.get("gsd"):
1090
+ return summaries.get("gsd")[0]
1091
+
1092
+ # Fallback for cases where the stac does not follow convention.
1093
+ gsd_lst = re.findall(r'"gsd": (\d+)', json.dumps(self.stac_json))
1094
+
1095
+ if len(gsd_lst) > 0:
1096
+ return float(gsd_lst[0])
1097
+
1098
+ return -1
1099
+
1100
+ def temporal_resolution_str(self) -> str:
1101
+ """Gets the temporal resolution of the collection as a string.
1102
+
1103
+ Returns:
1104
+ str: The temporal resolution of the collection as a string.
1105
+ """
1106
+ interval_dict = self.stac_json.get("gee:interval")
1107
+ if not interval_dict:
1108
+ return ""
1109
+ return f"{interval_dict['interval']} {interval_dict['unit']}"
1110
+
1111
+ def python_code(self) -> str:
1112
+ """Gets the Python code sample for the collection.
1113
+
1114
+ Returns:
1115
+ str: The Python code sample for the collection.
1116
+ """
1117
+ code = self.stac_json.get("code")
1118
+ if not code:
1119
+ return ""
1120
+
1121
+ return code.get("py_code")
1122
+
1123
+ def set_python_code(self, code: str) -> None:
1124
+ """Sets the Python code sample for the collection.
1125
+
1126
+ Args:
1127
+ code (str): The Python code sample to set.
1128
+ """
1129
+ if not code:
1130
+ self.stac_json["code"] = {"js_code": "", "py_code": code}
1131
+
1132
+ self.stac_json["code"]["py_code"] = code
1133
+
1134
+ def set_js_code(self, code: str) -> None:
1135
+ """Sets the JavaScript code sample for the collection.
1136
+
1137
+ Args:
1138
+ code (str): The JavaScript code sample to set.
1139
+ """
1140
+ if not code:
1141
+ return ""
1142
+ js_code = self.stac_json.get("code").get("js_code")
1143
+ self.stac_json["code"] = {"js_code": "", "py_code": code}
1144
+
1145
+ def image_preview_url(self) -> str:
1146
+ """Gets the URL of the preview image for the collection.
1147
+
1148
+ Returns:
1149
+ str: The URL of the preview image for the collection.
1150
+
1151
+ Raises:
1152
+ ValueError: If no preview image is found.
1153
+ """
1154
+ for link in self.stac_json["links"]:
1155
+ if (
1156
+ "rel" in link
1157
+ and link["rel"] == "preview"
1158
+ and link["type"] == "image/png"
1159
+ ):
1160
+ return link["href"]
1161
+ raise ValueError(f"No preview image found for {id}")
1162
+
1163
+ def catalog_url(self) -> str:
1164
+ """Gets the URL of the catalog for the collection.
1165
+
1166
+ Returns:
1167
+ str: The URL of the catalog for the collection.
1168
+ """
1169
+ links = self.stac_json["links"]
1170
+ for link in links:
1171
+ if "rel" in link and link["rel"] == "catalog":
1172
+ return link["href"]
1173
+
1174
+ # Ideally there would be a 'catalog' link but sometimes there isn't.
1175
+ base_url = "https://developers.google.com/earth-engine/datasets/catalog/"
1176
+ if link["href"].startswith(base_url):
1177
+ return link["href"].split("#")[0]
1178
+
1179
+ logging.warning(f"No catalog link found for {self.public_id()}")
1180
+ return ""
1181
+
1182
+
1183
+ # @title class CollectionList()
1184
+ class CollectionList(Sequence[Collection]):
1185
+ """List of stac.Collections; can be filtered to return a smaller sublist."""
1186
+
1187
+ _collections = Sequence[Collection]
1188
+
1189
+ def __init__(self, collections: Sequence[Collection]):
1190
+ self._collections = tuple(collections)
1191
+
1192
+ def __iter__(self):
1193
+ return iter(self._collections)
1194
+
1195
+ def __getitem__(self, index):
1196
+ return self._collections[index]
1197
+
1198
+ def __len__(self):
1199
+ return len(self._collections)
1200
+
1201
+ def __eq__(self, other: object) -> bool:
1202
+ if isinstance(other, CollectionList):
1203
+ return self._collections == other._collections
1204
+ return False
1205
+
1206
+ def __hash__(self) -> int:
1207
+ return hash(self._collections)
1208
+
1209
+ def filter_by_ids(self, ids: Iterable[str]):
1210
+ """Returns a sublist with only the collections matching the given ids."""
1211
+ return self.__class__([c for c in self._collections if c.public_id() in ids])
1212
+
1213
+ def filter_by_datetime(
1214
+ self,
1215
+ query_datetime: datetime.datetime,
1216
+ ):
1217
+ """Returns a sublist with the time interval matching the given time."""
1218
+ result = []
1219
+ for collection in self._collections:
1220
+ for datetime_interval in collection.datetime_interval():
1221
+ if matches_datetime(datetime_interval, query_datetime):
1222
+ result.append(collection)
1223
+ break
1224
+ return self.__class__(result)
1225
+
1226
+ def filter_by_interval(
1227
+ self,
1228
+ query_interval: tuple[datetime.datetime, datetime.datetime],
1229
+ ):
1230
+ """Returns a sublist with the time interval matching the given interval."""
1231
+ result = []
1232
+ for collection in self._collections:
1233
+ for datetime_interval in collection.datetime_interval():
1234
+ if matches_interval(datetime_interval, query_interval):
1235
+ result.append(collection)
1236
+ break
1237
+ return self.__class__(result)
1238
+
1239
+ def filter_by_bounding_box_list(self, query_bbox: BBox):
1240
+ """Returns a sublist with the bbox matching the given bbox."""
1241
+ result = []
1242
+ for collection in self._collections:
1243
+ for collection_bbox in collection.bbox_list():
1244
+ if collection_bbox.intersects(query_bbox):
1245
+ result.append(collection)
1246
+ break
1247
+ return self.__class__(result)
1248
+
1249
+ def filter_by_bounding_box(self, query_bbox: BBox):
1250
+ """Returns a sublist with the bbox matching the given bbox."""
1251
+ result = []
1252
+ for collection in self._collections:
1253
+ for collection_bbox in collection.bbox_list():
1254
+ if collection_bbox.intersects(query_bbox):
1255
+ result.append(collection)
1256
+ break
1257
+ return self.__class__(result)
1258
+
1259
+ def start_str(self) -> datetime.datetime:
1260
+ return self.start().strftime("%Y-%m-%d")
1261
+
1262
+ def sort_by_spatial_resolution(self, reverse=False):
1263
+ """
1264
+ Sorts the collections based on their spatial resolution.
1265
+ Collections with spatial_resolution_m() == -1 are pushed to the end.
1266
+
1267
+ Args:
1268
+ reverse (bool): If True, sort in descending order (highest resolution first).
1269
+ If False (default), sort in ascending order (lowest resolution first).
1270
+
1271
+ Returns:
1272
+ CollectionList: A new CollectionList instance with sorted collections.
1273
+ """
1274
+
1275
+ def sort_key(collection):
1276
+ resolution = collection.spatial_resolution_m()
1277
+ if resolution == -1:
1278
+ return float("inf") if not reverse else float("-inf")
1279
+ return resolution
1280
+
1281
+ sorted_collections = sorted(self._collections, key=sort_key, reverse=reverse)
1282
+ return self.__class__(sorted_collections)
1283
+
1284
+ def limit(self, n: int):
1285
+ """
1286
+ Returns a new CollectionList containing the first n entries.
1287
+
1288
+ Args:
1289
+ n (int): The number of entries to include in the new list.
1290
+
1291
+ Returns:
1292
+ CollectionList: A new CollectionList instance with at most n collections.
1293
+ """
1294
+ return self.__class__(self._collections[:n])
1295
+
1296
+ def to_df(self):
1297
+ """Converts a collection list to a dataframe with a select set of fields."""
1298
+
1299
+ rows = []
1300
+ for col in self._collections:
1301
+ # Remove text in parens in dataset name.
1302
+ short_title = re.sub(r"\([^)]*\)", "", col.get("title")).strip()
1303
+
1304
+ row = {
1305
+ "id": col.public_id(),
1306
+ "name": short_title,
1307
+ "temp_res": col.temporal_resolution_str(),
1308
+ "spatial_res_m": col.spatial_resolution_m(),
1309
+ "earliest": col.start_str(),
1310
+ "latest": col.end_str(),
1311
+ "url": col.catalog_url(),
1312
+ }
1313
+ rows.append(row)
1314
+ return pd.DataFrame(rows)
1315
+
1316
+
1317
+ class Catalog:
1318
+ """Class containing all collections in the EE STAC catalog."""
1319
+
1320
+ collections: CollectionList
1321
+
1322
+ def __init__(self, storage_client: storage.Client) -> None:
1323
+ """Initializes the Catalog with collections loaded from Google Cloud Storage.
1324
+
1325
+ Args:
1326
+ storage_client (storage.Client): The Google Cloud Storage client.
1327
+ """
1328
+ self.collections = CollectionList(self._load_collections(storage_client))
1329
+
1330
+ def get_collection(self, id: str) -> Collection:
1331
+ """Returns the collection with the given id.
1332
+
1333
+ Args:
1334
+ id (str): The ID of the collection.
1335
+
1336
+ Returns:
1337
+ Collection: The collection with the given ID.
1338
+
1339
+ Raises:
1340
+ ValueError: If no collection with the given ID is found.
1341
+ """
1342
+ col = self.collections.filter_by_ids([id])
1343
+ if len(col) == 0:
1344
+ raise ValueError(f"No collection with id {id}")
1345
+ return col[0]
1346
+
1347
+ @tenacity.retry(
1348
+ stop=tenacity.stop_after_attempt(5),
1349
+ wait=tenacity.wait_exponential(multiplier=1, min=4, max=10),
1350
+ retry=tenacity.retry_if_exception_type(
1351
+ (
1352
+ google_exceptions.GoogleAPICallError,
1353
+ google_exceptions.RetryError,
1354
+ ConnectionError,
1355
+ )
1356
+ ),
1357
+ before_sleep=lambda retry_state: print(
1358
+ f"Error occurred: {str(retry_state.outcome.exception())}\n"
1359
+ f"Retrying in {retry_state.next_action.sleep} seconds... "
1360
+ f"(Attempt {retry_state.attempt_number}/3)"
1361
+ ),
1362
+ )
1363
+ def _read_file(self, file_blob: storage.Blob) -> Collection:
1364
+ """Reads the contents of a file from the specified bucket.
1365
+
1366
+ Args:
1367
+ file_blob (storage.Blob): The blob representing the file.
1368
+
1369
+ Returns:
1370
+ Collection: The collection created from the file contents.
1371
+ """
1372
+ file_contents = file_blob.download_as_string().decode()
1373
+ return Collection(json.loads(file_contents))
1374
+
1375
+ def _read_files(self, file_blobs: List[storage.Blob]) -> List[Collection]:
1376
+ """Processes files in parallel.
1377
+
1378
+ Args:
1379
+ file_blobs (List[storage.Blob]): The list of file blobs.
1380
+
1381
+ Returns:
1382
+ List[Collection]: The list of collections created from the file contents.
1383
+ """
1384
+ collections = []
1385
+ with futures.ThreadPoolExecutor(max_workers=10) as executor:
1386
+ file_futures = [
1387
+ executor.submit(self._read_file, file_blob) for file_blob in file_blobs
1388
+ ]
1389
+ for future in file_futures:
1390
+ collections.append(future.result())
1391
+ return collections
1392
+
1393
+ def _load_collections(self, storage_client: storage.Client) -> Sequence[Collection]:
1394
+ """Loads all EE STAC JSON files from GCS, with datetimes as objects.
1395
+
1396
+ Args:
1397
+ storage_client (storage.Client): The Google Cloud Storage client.
1398
+
1399
+ Returns:
1400
+ Sequence[Collection]: A tuple of collections loaded from the files.
1401
+ """
1402
+ bucket = storage_client.get_bucket("earthengine-stac")
1403
+ files = [
1404
+ x
1405
+ for x in bucket.list_blobs(prefix="catalog/")
1406
+ if x.name.endswith(".json")
1407
+ and not x.name.endswith("/catalog.json")
1408
+ and not x.name.endswith("/units.json")
1409
+ ]
1410
+ logging.warning("Found %d files, loading...", len(files))
1411
+ collections = self._read_files(files)
1412
+
1413
+ code_samples_dict = self._load_all_code_samples(storage_client)
1414
+
1415
+ res = []
1416
+ for c in collections:
1417
+ if c.is_deprecated():
1418
+ continue
1419
+ c.stac_json["code"] = code_samples_dict.get(c.hyphen_id())
1420
+ res.append(c)
1421
+ logging.warning("Loaded %d collections (skipping deprecated ones)", len(res))
1422
+ # Returning a tuple for immutability.
1423
+ return tuple(res)
1424
+
1425
+ def _load_all_code_samples(
1426
+ self, storage_client: storage.Client
1427
+ ) -> Dict[str, Dict[str, str]]:
1428
+ """Loads js + py example scripts from GCS into dict keyed by dataset ID.
1429
+
1430
+ Args:
1431
+ storage_client (storage.Client): The Google Cloud Storage client.
1432
+
1433
+ Returns:
1434
+ Dict[str, Dict[str, str]]: A dictionary mapping dataset IDs to their code samples.
1435
+ """
1436
+
1437
+ # Get json file from GCS bucket
1438
+ # 'gs://earthengine-catalog/catalog/example_scripts.json'
1439
+ bucket = storage_client.get_bucket("earthengine-catalog")
1440
+ blob = bucket.blob("catalog/example_scripts.json")
1441
+ file_contents = blob.download_as_string().decode()
1442
+ data = json.loads(file_contents)
1443
+
1444
+ # Flatten json to get a map from ID (using '_' rather than '/') to code
1445
+ # sample.
1446
+ all_datasets_by_provider = data[0]["contents"]
1447
+ code_samples_dict = {}
1448
+ for provider in all_datasets_by_provider:
1449
+ for dataset in provider["contents"]:
1450
+ js_code = dataset["code"]
1451
+ py_code = self._make_python_code_sample(js_code)
1452
+
1453
+ code_samples_dict[dataset["name"]] = {
1454
+ "js_code": js_code,
1455
+ "py_code": py_code,
1456
+ }
1457
+
1458
+ return code_samples_dict
1459
+
1460
+ def _make_python_code_sample(self, js_code: str) -> str:
1461
+ """Converts EE JS code into python.
1462
+
1463
+ Args:
1464
+ js_code (str): The JavaScript code to convert.
1465
+
1466
+ Returns:
1467
+ str: The converted Python code.
1468
+ """
1469
+
1470
+ # le_map_tools appears to have some stray print statements.
1471
+ _ = io.StringIO()
1472
+ with redirect_stdout(_):
1473
+ code_list = js_snippet_to_py(
1474
+ js_code,
1475
+ add_new_cell=False,
1476
+ import_ee=False,
1477
+ import_geemap=False,
1478
+ show_map=False,
1479
+ )
1480
+ return "".join(code_list)
1481
+
1482
+
1483
+ # @title Embeddings classes and helper methods
1484
+
1485
+
1486
+ class PrecomputedEmbeddings(Embeddings):
1487
+ """Class for handling precomputed embeddings."""
1488
+
1489
+ def __init__(self, embeddings_dict: Dict[str, List[float]]) -> None:
1490
+ """Initializes the PrecomputedEmbeddings.
1491
+
1492
+ Args:
1493
+ embeddings_dict (Dict[str, List[float]]): A dictionary mapping texts to their embeddings.
1494
+ """
1495
+ self.embeddings_dict = embeddings_dict
1496
+ self.model = TextEmbeddingModel.from_pretrained("google/text-embedding-004")
1497
+
1498
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
1499
+ """Embeds a list of documents.
1500
+
1501
+ Args:
1502
+ texts (List[str]): The list of texts to embed.
1503
+
1504
+ Returns:
1505
+ List[List[float]]: The list of embeddings.
1506
+ """
1507
+ return [self.embeddings_dict[text] for text in texts]
1508
+
1509
+ def embed_query(self, text: str) -> List[float]:
1510
+ """Embeds a query text.
1511
+
1512
+ Args:
1513
+ text (str): The query text to embed.
1514
+
1515
+ Returns:
1516
+ List[float]: The embedding of the query text.
1517
+ """
1518
+ embeddings = self.model.get_embeddings([text])
1519
+ return embeddings[0].values
1520
+
1521
+
1522
+ def make_langchain_index(embeddings_df: pd.DataFrame) -> VectorStoreIndexWrapper:
1523
+ """Creates an index from a dataframe of precomputed embeddings.
1524
+
1525
+ Args:
1526
+ embeddings_df (pd.DataFrame): The dataframe containing precomputed embeddings.
1527
+
1528
+ Returns:
1529
+ VectorStoreIndexWrapper: The vector store index wrapper.
1530
+ """
1531
+ # Create a dictionary mapping texts to their embeddings
1532
+ embeddings_dict = dict(zip(embeddings_df["id"], embeddings_df["embedding"]))
1533
+
1534
+ # Create our custom embeddings class
1535
+ precomputed_embeddings = PrecomputedEmbeddings(embeddings_dict)
1536
+
1537
+ # Create Langchain Document objects
1538
+ documents = []
1539
+ for index, row in embeddings_df.iterrows():
1540
+ page_content = row["id"]
1541
+ metadata = {"summary": row["summary"], "name": row["name"]}
1542
+ documents.append(Document(page_content=page_content, metadata=metadata))
1543
+
1544
+ # Create the VectorstoreIndexCreator
1545
+ index_creator = VectorstoreIndexCreator(embedding=precomputed_embeddings)
1546
+
1547
+ # Create the index
1548
+ return index_creator.from_documents(documents)
1549
+
1550
+
1551
+ # Wrap Langchain embeddings in our own EE dataset wrapper
1552
+ class EarthEngineDatasetIndex:
1553
+ """Class for indexing and searching Earth Engine datasets."""
1554
+
1555
+ index: VectorStoreIndexWrapper
1556
+ vectorstore: VectorStore
1557
+ data_catalog: Catalog
1558
+ llm: BaseLanguageModel
1559
+
1560
+ def __init__(self, data_catalog, index, llm):
1561
+ """Initializes the EarthEngineDatasetIndex.
1562
+
1563
+ Args:
1564
+ data_catalog (Catalog): The data catalog containing the datasets.
1565
+ index (VectorStoreIndexWrapper): The vector store index wrapper.
1566
+ llm (BaseLanguageModel): The language model for query processing.
1567
+ """
1568
+ self.index = index
1569
+ self.data_catalog = data_catalog
1570
+ self.vectorstore = index.vectorstore
1571
+ self.llm = llm
1572
+
1573
+ @tenacity.retry(
1574
+ stop=stop_after_attempt(3),
1575
+ wait=wait_exponential(multiplier=1, min=4, max=10),
1576
+ retry=retry_if_exception_type(
1577
+ (requests.exceptions.RequestException, ConnectionError)
1578
+ ),
1579
+ )
1580
+ def find_top_matches(
1581
+ self,
1582
+ query: str,
1583
+ results: int = 10,
1584
+ threshold: float = 0.7,
1585
+ bounding_box: Optional[List[float]] = None,
1586
+ temporal_interval: Optional[Tuple[datetime.datetime, datetime.datetime]] = None,
1587
+ ) -> CollectionList:
1588
+ """Retrieve relevant datasets from the Earth Engine data catalog.
1589
+
1590
+ Args:
1591
+ query (str): The kind of data being searched for, e.g., 'population'.
1592
+ results (int): The number of datasets to return. Defaults to 10.
1593
+ threshold (float): The maximum dot product between the query and catalog embeddings.
1594
+ Defaults to 0.7.
1595
+ bounding_box (Optional[List[float]]): The spatial bounding box for the query,
1596
+ in the format [lon1, lat1, lon2, lon2]. Defaults to None.
1597
+ temporal_interval (Optional[Tuple[datetime.datetime, datetime.datetime]]):
1598
+ Temporal constraints as a tuple of datetime objects. Defaults to None.
1599
+
1600
+ Returns:
1601
+ CollectionList: A list of collections that match the query.
1602
+ """
1603
+ similar_docs = self.index.vectorstore.similarity_search_with_score(
1604
+ query, llm=self.llm, k=results
1605
+ )
1606
+ dataset_ids = [doc[0].page_content for doc in similar_docs]
1607
+ datasets = self.data_catalog.collections.filter_by_ids(dataset_ids)
1608
+ return datasets
1609
+
1610
+ @tenacity.retry(
1611
+ stop=stop_after_attempt(3),
1612
+ wait=wait_exponential(multiplier=1, min=4, max=10),
1613
+ retry=retry_if_exception_type(
1614
+ (requests.exceptions.RequestException, ConnectionError)
1615
+ ),
1616
+ )
1617
+ def find_top_matches_with_score_df(
1618
+ self,
1619
+ query: str,
1620
+ results: int = 20,
1621
+ threshold: float = 0.7,
1622
+ bounding_box: Optional[List[float]] = None,
1623
+ temporal_interval: Optional[Tuple[datetime.datetime, datetime.datetime]] = None,
1624
+ ) -> pd.DataFrame:
1625
+ """Retrieve relevant datasets and their match scores as a DataFrame.
1626
+
1627
+ Args:
1628
+ query (str): The kind of data being searched for, e.g., 'population'.
1629
+ results (int): The number of datasets to return. Defaults to 20.
1630
+ threshold (float): The maximum dot product between the query and catalog embeddings.
1631
+ Defaults to 0.7.
1632
+ bounding_box (Optional[List[float]]): The spatial bounding box for the query,
1633
+ in the format [lon1, lat1, lon2, lon2]. Defaults to None.
1634
+ temporal_interval (Optional[Tuple[datetime.datetime, datetime.datetime]]):
1635
+ Temporal constraints as a tuple of datetime objects. Defaults to None.
1636
+
1637
+ Returns:
1638
+ pd.DataFrame: A DataFrame containing the dataset IDs and their match scores.
1639
+ """
1640
+ scores_df = self.ids_to_match_scores_df(
1641
+ query, results, bounding_box, temporal_interval
1642
+ )
1643
+ dataset_ids = scores_df["id"].tolist()
1644
+ col_list = self.data_catalog.collections.filter_by_ids(dataset_ids)
1645
+ collection_df = col_list.to_df()
1646
+ df = pd.merge(collection_df, scores_df, on="id", how="inner")
1647
+ return df.sort_values(by="match_score", ascending=False)
1648
+
1649
+ def ids_to_match_scores_df(
1650
+ self,
1651
+ query: str,
1652
+ results: int,
1653
+ bounding_box: Optional[List[float]] = None,
1654
+ temporal_interval: Optional[Tuple[datetime.datetime, datetime.datetime]] = None,
1655
+ ) -> pd.DataFrame:
1656
+ """Convert dataset IDs and match scores to a DataFrame.
1657
+
1658
+ Args:
1659
+ query (str): The kind of data being searched for, e.g., 'population'.
1660
+ results (int): The number of datasets to return.
1661
+ bounding_box (Optional[List[float]]): The spatial bounding box for the query,
1662
+ in the format [lon1, lat1, lon2, lon2]. Defaults to None.
1663
+ temporal_interval (Optional[Tuple[datetime.datetime, datetime.datetime]]):
1664
+ Temporal constraints as a tuple of datetime objects. Defaults to None.
1665
+
1666
+ Returns:
1667
+ pd.DataFrame: A DataFrame containing the dataset IDs and their match scores.
1668
+ """
1669
+ similar_docs = self.index.vectorstore.similarity_search_with_score(
1670
+ query, llm=self.llm, k=results
1671
+ )
1672
+ dataset_ids, scores = zip(
1673
+ *[(doc[0].page_content, doc[1]) for doc in similar_docs]
1674
+ )
1675
+
1676
+ return pd.DataFrame({"id": dataset_ids, "match_score": scores})
1677
+
1678
+
1679
+ def explain_relevance(
1680
+ query: str,
1681
+ dataset_id: str,
1682
+ catalog: Catalog,
1683
+ model_name: str = "gemini-1.5-pro-latest",
1684
+ stream: bool = False,
1685
+ ) -> str:
1686
+ """Prompts LLM to explain the relevance of a dataset to a query.
1687
+
1688
+ Args:
1689
+ query (str): The user's query.
1690
+ dataset_id (str): The ID of the dataset.
1691
+ catalog (Catalog): The catalog containing the dataset.
1692
+ model_name (str): The name of the model to use. Defaults to "gemini-1.5-pro-latest".
1693
+ stream (bool): Whether to stream the response. Defaults to False.
1694
+
1695
+ Returns:
1696
+ str: The explanation of the dataset's relevance to the query.
1697
+ """
1698
+
1699
+ stac_json = catalog.get_collection(dataset_id).stac_json
1700
+ return explain_relevance_from_stac_json(query, stac_json, model_name, stream)
1701
+
1702
+
1703
+ @retry(
1704
+ stop=stop_after_attempt(3),
1705
+ wait=wait_exponential(multiplier=1, min=4, max=10),
1706
+ retry=retry_if_exception_type(
1707
+ (requests.exceptions.RequestException, ConnectionError)
1708
+ ),
1709
+ )
1710
+ def explain_relevance_from_stac_json(
1711
+ query: str,
1712
+ stac_json: Dict[str, Any],
1713
+ model_name: str = "gemini-1.5-pro-latest",
1714
+ stream: bool = False,
1715
+ ) -> str:
1716
+ """Prompts LLM to explain the relevance of a dataset to a query using its STAC JSON.
1717
+
1718
+ Args:
1719
+ query (str): The user's query.
1720
+ stac_json (Dict[str, Any]): The STAC JSON of the dataset.
1721
+ model_name (str): The name of the model to use. Defaults to "gemini-1.5-pro-latest".
1722
+ stream (bool): Whether to stream the response. Defaults to False.
1723
+
1724
+ Returns:
1725
+ str: The explanation of the dataset's relevance to the query.
1726
+ """
1727
+ stac_json_str = json.dumps(stac_json)
1728
+
1729
+ prompt = f"""
1730
+ I am an Earth Engine user contemplating using a dataset to support
1731
+ my investigation of the following query. Provide a concise, paragraph-long
1732
+ summary explaining why this dataset may be a good fit for my use case.
1733
+ If it does not seem like an appropriate dataset, say so.
1734
+ If relevant, call attention to a max of 3 bands that may be of particular interest.
1735
+ Weigh the tradeoffs between temporal and spatial resolution, particularly
1736
+ if the original query specifies regions of interest, time periods, or
1737
+ frequency of data collection. If I have not specified any
1738
+ spatial constraints, do your best based on the nature of their query. For example,
1739
+ if I'm wanting to study something small, like buildings, I will likely need good spatial resolution.
1740
+
1741
+ Here is the original query:
1742
+ {query}
1743
+
1744
+ Here is the stac json metadata for the dataset:
1745
+ {stac_json_str}
1746
+ """
1747
+ model = genai.GenerativeModel(model_name)
1748
+ response = model.generate_content(prompt, stream=stream)
1749
+ if stream:
1750
+ return response
1751
+ return response.text
1752
+
1753
+
1754
+ @retry(
1755
+ stop=stop_after_attempt(3),
1756
+ wait=wait_exponential(multiplier=1, min=4, max=10),
1757
+ retry=retry_if_exception_type(
1758
+ (requests.exceptions.RequestException, ConnectionError)
1759
+ ),
1760
+ )
1761
+ def is_valid_question(question: str, model_name: str = "gemini-1.5-pro-latest") -> bool:
1762
+ """Filters out questions that cannot be answered by a dataset search tool.
1763
+
1764
+ Args:
1765
+ question (str): The user's question.
1766
+ model_name (str): The name of the model to use. Defaults to "gemini-1.5-pro-latest".
1767
+
1768
+ Returns:
1769
+ bool: True if the question is valid, False otherwise.
1770
+ """
1771
+
1772
+ prompt = f"""
1773
+ You are a tool whose job is to determine whether or not the following question
1774
+ relates even in a small way to geospatial datasets. Please provide a single
1775
+ word answer either True or False.
1776
+
1777
+ For example, if the original query is "hello" - you should answer False. If
1778
+ the original query is "cheese futures" you should still answer True because
1779
+ the user could be interested in cheese production, and therefore agricultural
1780
+ land where cattle might be raised.
1781
+
1782
+ Here is the original query:
1783
+ {question}
1784
+ """
1785
+ model = genai.GenerativeModel(model_name)
1786
+ response = model.generate_content(prompt)
1787
+ # Err on the side of returning True
1788
+ return response.text.lower().strip() != "false"
1789
+
1790
+
1791
+ class CodeThoughts(typing_extensions.TypedDict):
1792
+ code: str
1793
+ thoughts: str
1794
+
1795
+
1796
+ @retry(
1797
+ stop=stop_after_attempt(3),
1798
+ wait=wait_exponential(multiplier=1, min=4, max=10),
1799
+ retry=retry_if_exception_type(
1800
+ (requests.exceptions.RequestException, ConnectionError)
1801
+ ),
1802
+ )
1803
+ def fix_ee_python_code(
1804
+ code: str, ee: Any, geemap_instance: Map, model_name: str = "gemini-1.5-pro-latest"
1805
+ ) -> str:
1806
+ """Asks a model to do ee python code correction in the event of error.
1807
+
1808
+ Args:
1809
+ code (str): The Earth Engine Python code to fix.
1810
+ ee (Any): The Earth Engine module.
1811
+ geemap_instance (Map): The le_map_tools instance.
1812
+ model_name (str): The name of the model to use. Defaults to "gemini-1.5-pro-latest".
1813
+
1814
+ Returns:
1815
+ str: The corrected Earth Engine Python code.
1816
+ """
1817
+
1818
+ def create_error_prompt(code: str, error_msg: str) -> str:
1819
+ return f"""
1820
+ You are an extremely laconic code correction robot.
1821
+ I am attempting to execute the following snippet of python Earth Engine code,
1822
+ using a le_map_tools instance:
1823
+
1824
+ ```
1825
+ {code}
1826
+ ```
1827
+
1828
+ I have encountered the following error, please fix it. In 1-2 sentences,
1829
+ explain your debugging thought process in the 'thoughts' field. Note that
1830
+ the setOptions method exists only in the ee javascript library. Code
1831
+ referencing that method can be removed.
1832
+
1833
+ Include the complete revised code snippet in the code field.
1834
+ Do not provide any other comentary in the code field. Do not add any new
1835
+ imports to the code snippet.
1836
+
1837
+ {error_msg}
1838
+ """
1839
+
1840
+ generation_config = {
1841
+ "response_mime_type": "application/json",
1842
+ "response_schema": CodeThoughts,
1843
+ }
1844
+
1845
+ model = genai.GenerativeModel(model_name, generation_config=generation_config)
1846
+
1847
+ max_attempts = 5
1848
+ total_attempts = 0
1849
+ broken = True
1850
+ while total_attempts < max_attempts and broken:
1851
+ try:
1852
+ run_ee_code(code, ee, geemap_instance)
1853
+ # logging.warning(f'Code success! after {total_attempts} try.')
1854
+ return code
1855
+ except Exception as e:
1856
+ logging.warning("Code execution error, asking Gemini for help.")
1857
+
1858
+ gemini_json_fail = True
1859
+ while gemini_json_fail:
1860
+ response = model.generate_content(create_error_prompt(code, str(e)))
1861
+ try:
1862
+ code_thoughts = json.loads(response.text)
1863
+ gemini_json_fail = False
1864
+ except json.JSONDecodeError:
1865
+ pass
1866
+
1867
+ total_attempts += 1
1868
+
1869
+ code = code_thoughts["code"]
1870
+ thoughts = code_thoughts["thoughts"]
1871
+ logging.warning(f"Gemini thoughts: \n{thoughts}")
1872
+ # logging.warning(f'Gemini new code: {code}')
1873
+ if total_attempts == max_attempts:
1874
+ raise Exception(e)
1875
+ logging.warning(f"Failed to fix code after {max_attempts} attempts.")
1876
+
1877
+
1878
+ class DatasetSearchInterface:
1879
+ """Interface for searching and displaying Earth Engine datasets."""
1880
+
1881
+ collections: CollectionList
1882
+ query: str
1883
+ dataset_table: widgets.Widget
1884
+ code_output: widgets.Widget
1885
+ details_output: widgets.Widget
1886
+ map_output: widgets.Widget
1887
+ geemap_instance: Map
1888
+
1889
+ # Parent containers for controlling widget visibility.
1890
+ details_code_box: widgets.Widget
1891
+ map_widget: widgets.Widget
1892
+
1893
+ def __init__(self, query: str, collections: CollectionList) -> None:
1894
+ """Initializes the DatasetSearchInterface.
1895
+
1896
+ Args:
1897
+ query (str): The search query string.
1898
+ collections (CollectionList): The list of dataset collections.
1899
+ """
1900
+
1901
+ self.query = query
1902
+ self.collections = collections
1903
+
1904
+ # Create the output widgets
1905
+ self.code_output = widgets.Output(layout=widgets.Layout(width="50%"))
1906
+ self.details_output = widgets.Output(
1907
+ layout=widgets.Layout(height="300px", width="100%")
1908
+ )
1909
+
1910
+ # Initialize dataset table
1911
+ table_html = self._build_table_html(collections)
1912
+ self.dataset_table = widgets.HTML(value=table_html)
1913
+
1914
+ _callback_id = "dataset-select" + str(uuid.uuid4())
1915
+ output.register_callback(_callback_id, self.update_outputs)
1916
+ self._dataset_select_js_code = self._dataset_select_js_code(_callback_id)
1917
+ # self._dataset_select_js_code(_callback_id)
1918
+
1919
+ # Initialize map
1920
+ self.map_output = widgets.Output(layout=widgets.Layout(width="100%"))
1921
+ self.geemap_instance = Map(height="600px", width="100%")
1922
+
1923
+ def display(self):
1924
+ """Display the UI in the cell."""
1925
+ # Create title and description with Material Design styling
1926
+ # title = widgets.HTML(value='<h2 class="main-title">Earth Engine Dataset Explorer</h2>')
1927
+
1928
+ # Wrap outputs in a widget box for border styling
1929
+ details_widget = widgets.Box(
1930
+ [self.details_output],
1931
+ layout=widgets.Layout(
1932
+ border="1px solid #E0E0E0", padding="10px", margin="5px", width="100%"
1933
+ ),
1934
+ )
1935
+ code_widget = widgets.Box(
1936
+ [self.code_output],
1937
+ layout=widgets.Layout(
1938
+ border="1px solid #E0E0E0", padding="10px", margin="5px", width="100%"
1939
+ ),
1940
+ )
1941
+ self.map_widget = widgets.Box(
1942
+ [self.map_output],
1943
+ layout=widgets.Layout(
1944
+ border="1px solid #E0E0E0",
1945
+ padding="10px",
1946
+ margin="5px",
1947
+ width="100%",
1948
+ height="600x",
1949
+ ),
1950
+ )
1951
+
1952
+ # Create the vertical box for code and details
1953
+ self.details_code_box = widgets.VBox(
1954
+ [details_widget, code_widget],
1955
+ layout=widgets.Layout(width="50%", height="600px"),
1956
+ )
1957
+
1958
+ # Create a horizontal box for map and details/code
1959
+ map_details_code_box = widgets.HBox(
1960
+ [self.map_widget, self.details_code_box],
1961
+ layout=widgets.Layout(
1962
+ border="1px solid #E0E0E0", padding="10px", margin="5px"
1963
+ ),
1964
+ )
1965
+
1966
+ # Create the main layout with Material Design styling
1967
+ main_content = widgets.VBox(
1968
+ [self.dataset_table, map_details_code_box],
1969
+ layout=widgets.Layout(
1970
+ width="100%", border="1px solid #E0E0E0", padding="10px", margin="5px"
1971
+ ),
1972
+ )
1973
+
1974
+ # Add debug panel to the main layout
1975
+ main_layout = widgets.VBox(
1976
+ [
1977
+ # title,
1978
+ main_content,
1979
+ ],
1980
+ layout=widgets.Layout(height="1500px", width="100%", padding="24px"),
1981
+ )
1982
+
1983
+ # @title CSS
1984
+ # Custom CSS for Material Design styling with enhanced table styling, chat panel, and debug panel
1985
+ CSS = syntax.css(
1986
+ """
1987
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap');
1988
+
1989
+ body {
1990
+ font-family: 'Roboto', sans-serif;
1991
+ margin: 0;
1992
+ padding: 0;
1993
+ }
1994
+
1995
+ .main-title {
1996
+ font-size: 24px;
1997
+ font-weight: 500;
1998
+ color: #212121;
1999
+ margin-bottom: 16px;
2000
+ }
2001
+
2002
+ .custom-title {
2003
+ font-size: 18px;
2004
+ font-weight: 500;
2005
+ color: #212121;
2006
+ margin-bottom: 12px;
2007
+ }
2008
+
2009
+ .details-text {
2010
+ font-size: 14px;
2011
+ color: #616161;
2012
+ line-height: 1.5;
2013
+ }
2014
+
2015
+ .custom-table {
2016
+ width: 100%;
2017
+ border-collapse: collapse;
2018
+ margin-bottom: 24px;
2019
+ font-family: 'Roboto', sans-serif;
2020
+ }
2021
+ .custom-table th, .custom-table td {
2022
+ text-align: left;
2023
+ padding: 12px;
2024
+ border-bottom: 1px solid #E0E0E0;
2025
+ }
2026
+ .custom-table th {
2027
+ background-color: #F5F5F5;
2028
+ font-weight: 500;
2029
+ color: #212121;
2030
+ }
2031
+ .custom-table tr:hover {
2032
+ background-color: #E3F2FD;
2033
+ }
2034
+ .custom-table tr.selected {
2035
+ background-color: #BBDEFB;
2036
+ }
2037
+
2038
+ /* Ensure borders are visible */
2039
+ .jupyter-widgets.widget-box {
2040
+ border: 1px solid #E0E0E0 !important;
2041
+ overflow: auto;
2042
+ }
2043
+
2044
+ /* Make the map span full width */
2045
+ .le_map_tools-container {
2046
+ width: 100% !important;
2047
+ height: 600px !important;
2048
+ }
2049
+
2050
+ # Disable table clicks while things are loading
2051
+ .disabled {
2052
+ pointer-events: none;
2053
+ /* You might also want to visually indicate the disabled state */
2054
+ opacity: 0.5;
2055
+ cursor: default;
2056
+ }
2057
+ """
2058
+ )
2059
+
2060
+ # Display the widget
2061
+ display(HTML(f"<style>{CSS}</style>"))
2062
+ display(main_layout)
2063
+ display(Javascript(self._dataset_select_js_code))
2064
+
2065
+ def _build_table_html(self, collections: CollectionList) -> str:
2066
+ """Builds the HTML for the dataset table.
2067
+
2068
+ Args:
2069
+ collections (CollectionList): The list of dataset collections.
2070
+
2071
+ Returns:
2072
+ str: The HTML string for the dataset table.
2073
+ """
2074
+ table_html = """
2075
+ <table class="custom-table">
2076
+ <tr>
2077
+ <th>Dataset ID</th>
2078
+ <th> Name </th>
2079
+ <th>Temporal Resolution</th>
2080
+ <th>Spatial Resolution (m)</th>
2081
+ <th>Earliest</th>
2082
+ <th>Latest</th>
2083
+ </tr>
2084
+ """
2085
+ for dataset in collections:
2086
+ table_html += f"""
2087
+ <tr data-dataset="{dataset.public_id()}">
2088
+ <td>{dataset.public_id()}</td>
2089
+ <td>{dataset.get('title')}</td>
2090
+ <td>{dataset.temporal_resolution_str()}</td>
2091
+ <td>{dataset.spatial_resolution_m()}</td>
2092
+ <td>{dataset.start_str()}</td>
2093
+ <td>{dataset.end_str()}</td>
2094
+ </tr>
2095
+ """
2096
+
2097
+ table_html += "</table>"
2098
+ return table_html
2099
+
2100
+ def update_outputs(self, selected_dataset: str) -> None:
2101
+ """Updates the output widgets based on the selected dataset.
2102
+
2103
+ Args:
2104
+ selected_dataset (str): The ID of the selected dataset.
2105
+ """
2106
+ collection = self.collections.filter_by_ids([selected_dataset])
2107
+
2108
+ if not collection:
2109
+ self.details_code_box.layout.visibility = "hidden"
2110
+ self.map_widget.layout.visibility = "hidden"
2111
+ return
2112
+
2113
+ dataset = collection[0]
2114
+
2115
+ # Clear everything when a new dataset is selected.
2116
+ self.map_output.clear_output()
2117
+ self.code_output.clear_output()
2118
+ self.details_output.clear_output()
2119
+ # Clear previous layers. Keep only the base layer
2120
+ self.geemap_instance.layers = self.geemap_instance.layers[:1]
2121
+
2122
+ with self.map_output:
2123
+ display(HTML("<h3>Loading...</h3>"))
2124
+ code = fix_ee_python_code(dataset.python_code(), le, self.geemap_instance)
2125
+ llm_thoughts = explain_relevance_from_stac_json(
2126
+ self.query, dataset.stac_json
2127
+ )
2128
+
2129
+ # Code and LLM thought content is now fully loaded.
2130
+ # We ought to make this asynchronous in another version
2131
+ self.map_output.clear_output()
2132
+
2133
+ with self.code_output:
2134
+ display(HTML('<div class="custom-title">Earth Engine Code</div>'))
2135
+ print(code)
2136
+
2137
+ with self.details_output:
2138
+ # display(HTML('<h3>Thinking...</h3>'))
2139
+ # self.details_output.clear_output()
2140
+ display(HTML('<div class="custom-title">Thoughts with Gemini</div>'))
2141
+ print(llm_thoughts)
2142
+
2143
+ with self.map_output:
2144
+ display(self.geemap_instance)
2145
+
2146
+ self.details_code_box.layout.visibility = "visible"
2147
+ self.map_widget.layout.visibility = "visible"
2148
+
2149
+ def _dataset_select_js_code(self, callback_id: str) -> str:
2150
+ """Generates JavaScript code for handling dataset selection.
2151
+
2152
+ Args:
2153
+ callback_id (str): The callback ID for the dataset selection.
2154
+
2155
+ Returns:
2156
+ str: The JavaScript code as a string.
2157
+ """
2158
+ return Template(
2159
+ syntax.javascript(
2160
+ """
2161
+ function initializeTableInteraction() {
2162
+ const table = document.querySelector('.custom-table');
2163
+ if (!table) {
2164
+ console.error('Table not found');
2165
+ return;
2166
+ }
2167
+
2168
+ function selectRow(row) {
2169
+ // Remove selection from previously selected row
2170
+ const prevSelected = table.querySelector('tr.selected');
2171
+ if (prevSelected) prevSelected.classList.remove('selected');
2172
+
2173
+ // Add selection to the new row
2174
+ row.classList.add('selected');
2175
+ const selectedDataset = row.dataset.dataset;
2176
+ console.log('Selected dataset:', selectedDataset);
2177
+ google.colab.kernel.invokeFunction('{{callback_id}}', [selectedDataset], {});
2178
+
2179
+ }
2180
+
2181
+ table.addEventListener('click', (event) => {
2182
+ const row = event.target.closest('tr');
2183
+ if (!row || !row.dataset.dataset) return;
2184
+ selectRow(row);
2185
+ });
2186
+
2187
+ // Select the first row by default
2188
+ const firstRow = table.querySelector('tr[data-dataset]');
2189
+ if (firstRow) {
2190
+ selectRow(firstRow);
2191
+ }
2192
+ }
2193
+
2194
+ // Run the initialization function after a short delay to ensure the DOM is ready
2195
+ setTimeout(initializeTableInteraction, 1000);
2196
+ """
2197
+ )
2198
+ ).render(callback_id=callback_id)
2199
+
2200
+
2201
+ class DatasetExplorer:
2202
+ """A widget for exploring Earth Engine datasets.
2203
+ The DataExplorer class source code is adapted from <https://bit.ly/48cE24D>.
2204
+ Credit to the original author Renee Johnston (<https://github.com/raj02006>)
2205
+ """
2206
+
2207
+ def __init__(
2208
+ self,
2209
+ project_id: str = "GOOGLE_PROJECT_ID",
2210
+ google_api_key: str = "GOOGLE_API_KEY",
2211
+ vertex_ai_zone: str = "us-central1",
2212
+ model: str = "gemini-1.5-pro",
2213
+ embeddings_cloud_path: str = "gs://earthengine-catalog/embeddings/catalog_embeddings.jsonl",
2214
+ ) -> None:
2215
+ """Initializes the DatasetExplorer.
2216
+
2217
+ Args:
2218
+ project_id (str): Google Cloud project ID. Defaults to "GOOGLE_PROJECT_ID".
2219
+ google_api_key (str): Google API key. Defaults to "GOOGLE_API_KEY".
2220
+ vertex_ai_zone (str): Vertex AI zone. Defaults to "us-central1".
2221
+ model (str): Model name for ChatGoogleGenerativeAI. Defaults to "gemini-1.5-pro".
2222
+ embeddings_cloud_path (str): Cloud path to the embeddings file.
2223
+ Defaults to "gs://earthengine-catalog/embeddings/catalog_embeddings.jsonl".
2224
+ """
2225
+
2226
+ # @title Setup
2227
+ project_name = get_env_var(project_id)
2228
+ if project_name is None:
2229
+ project_name = get_env_var("EE_PROJECT_ID")
2230
+ if project_name is None:
2231
+ raise ValueError("Please provide a Google Cloud project ID.")
2232
+
2233
+ genai.configure(api_key=get_env_var(google_api_key))
2234
+
2235
+ le.Authenticate()
2236
+ le.Initialize(project=project_name)
2237
+ storage_client = storage.Client(project=project_name)
2238
+ vertexai.init(project=project_name, location=vertex_ai_zone)
2239
+
2240
+ # Make sure le_map_tools initialized correctly.
2241
+ ee_initialize(project=project_name)
2242
+ m = Map(draw_ctrl=False)
2243
+ m.add("layer_manager")
2244
+
2245
+ catalog = Catalog(storage_client)
2246
+
2247
+ # Pre-built embeddings.
2248
+ EMBEDDINGS_CLOUD_PATH = embeddings_cloud_path
2249
+
2250
+ # Copy embeddings from GCS bucket to a local file
2251
+ EMBEDDINGS_LOCAL_PATH = "catalog_embeddings.jsonl"
2252
+
2253
+ def load_embeddings(
2254
+ gcs_path=EMBEDDINGS_CLOUD_PATH, local_path=EMBEDDINGS_LOCAL_PATH
2255
+ ):
2256
+ parts = gcs_path.split("/")
2257
+ bucket_name = parts[2]
2258
+ blob_path = "/".join(parts[3:])
2259
+ bucket = storage_client.get_bucket(bucket_name)
2260
+ blob = bucket.blob(blob_path)
2261
+ blob.download_to_filename(local_path)
2262
+ return local_path
2263
+
2264
+ # Load our embeddings data into a dataframe:
2265
+ local_path = load_embeddings(EMBEDDINGS_CLOUD_PATH, EMBEDDINGS_LOCAL_PATH)
2266
+ embeddings_df = pd.read_json(local_path, lines=True)
2267
+
2268
+ llm = ChatGoogleGenerativeAI(
2269
+ model=model, google_api_key=get_env_var(google_api_key)
2270
+ )
2271
+
2272
+ local_path = load_embeddings(EMBEDDINGS_CLOUD_PATH, EMBEDDINGS_LOCAL_PATH)
2273
+ embeddings_df = pd.read_json(local_path, lines=True)
2274
+ langchain_index = make_langchain_index(embeddings_df)
2275
+
2276
+ self.ee_index = EarthEngineDatasetIndex(catalog, langchain_index, llm)
2277
+
2278
+ def show(self, query: Optional[str] = None, **kwargs: Any) -> widgets.VBox:
2279
+ """Displays a query interface for searching datasets.
2280
+
2281
+ Args:
2282
+ query (Optional[str]): The initial query string. Defaults to None.
2283
+ **kwargs (Any): Additional keyword arguments for widget styling.
2284
+
2285
+ Returns:
2286
+ widgets.VBox: A VBox containing the query input and output display.
2287
+ """
2288
+
2289
+ output.no_vertical_scroll()
2290
+
2291
+ if "style" not in kwargs:
2292
+ kwargs["style"] = {"description_width": "initial"}
2293
+ if "layout" not in kwargs:
2294
+ kwargs["layout"] = widgets.Layout(width="98%")
2295
+
2296
+ def Question(query: str) -> None:
2297
+ """Handles the query and displays the dataset search results.
2298
+
2299
+ Args:
2300
+ query (str): The query string.
2301
+ """
2302
+ if not is_valid_question(query):
2303
+ print("Invalid question. Please try again.")
2304
+ return
2305
+
2306
+ datasets = self.ee_index.find_top_matches(query)
2307
+ # datasets = datasets.sort_by_spatial_resolution().limit(5)
2308
+ datasets = datasets.limit(7)
2309
+ dataset_search = DatasetSearchInterface(query, datasets)
2310
+ dataset_search.display()
2311
+
2312
+ if query is None:
2313
+ query = "How have global land surface temperatures changed over time?"
2314
+
2315
+ query_widget = widgets.Text(
2316
+ value=query,
2317
+ placeholder="Type your query here and press Enter",
2318
+ description="Query:",
2319
+ tooltip="Type your query here and press Enter",
2320
+ **kwargs,
2321
+ )
2322
+
2323
+ output_widget = widgets.Output()
2324
+
2325
+ display_widget = widgets.VBox([query_widget, output_widget])
2326
+
2327
+ def on_query_change(text: widgets.Text) -> None:
2328
+ """Handles the event when the query text is submitted.
2329
+
2330
+ Args:
2331
+ text (widgets.Text): The text widget containing the query.
2332
+ """
2333
+ output_widget.clear_output()
2334
+ with output_widget:
2335
+ print("Loading ...")
2336
+ output_widget.clear_output(wait=True)
2337
+ Question(text.value)
2338
+
2339
+ query_widget.on_submit(on_query_change)
2340
+
2341
+ return display_widget