CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-geemap

A Python package for interactive geospatial analysis and visualization with Google Earth Engine

Pending
Overview
Eval results
Files

ai-ml.mddocs/

AI and Machine Learning

AI-powered features including the Genie assistant widget, machine learning utilities for Earth Engine classifiers, and advanced data analysis capabilities with precomputed embeddings and semantic search.

Capabilities

Genie AI Assistant

Interactive AI assistant widget for Earth Engine code generation and geospatial analysis guidance.

class Genie:
    """AI assistant widget for Earth Engine and geospatial analysis."""
    
    def __init__(
        self,
        project: Optional[str] = None,
        google_api_key: Optional[str] = None,
        gemini_model: str = "gemini-1.5-flash",
        target_score: float = 0.8,
        widget_height: str = "600px",
        initialize_ee: bool = True,
        **kwargs
    ) -> None:
        """
        Initialize Genie AI assistant.
        
        Args:
            project: Google Cloud project ID
            google_api_key: Google API key for authentication
            gemini_model: Gemini model to use for AI assistance
            target_score: Target confidence score for responses  
            widget_height: Height of the widget UI
            initialize_ee: Whether to initialize Earth Engine
            **kwargs: Additional configuration parameters
        """

Earth Engine Classifier Utilities

Tools for creating, training, and deploying machine learning classifiers using Earth Engine.

def fc_to_classifier(
    features: ee.FeatureCollection,
    classifier: str = "RandomForest",
    mode: str = "classification",
    **kwargs
) -> ee.Classifier:
    """
    Convert feature collection to Earth Engine classifier.
    
    Args:
        features: Training feature collection
        classifier: Classifier type ('RandomForest', 'SVM', 'NaiveBayes', 'DecisionTree')
        mode: Classification mode ('classification' or 'regression')
        **kwargs: Additional classifier parameters
        
    Returns:
        Trained Earth Engine classifier
    """

def strings_to_classifier(
    strings: List[str],
    classifier_type: str = "RandomForest",
    **kwargs
) -> ee.Classifier:
    """
    Convert decision tree strings to Earth Engine classifier.
    
    Args:
        strings: List of decision tree string representations
        classifier_type: Type of classifier to create
        **kwargs: Additional parameters
        
    Returns:
        Earth Engine classifier object
    """

def export_trees_to_fc(
    classifier: ee.Classifier,
    features: ee.FeatureCollection,
    **kwargs
) -> ee.FeatureCollection:
    """
    Export decision trees to feature collection.
    
    Args:
        classifier: Trained classifier
        features: Feature collection to export trees for
        **kwargs: Additional export parameters
        
    Returns:
        Feature collection containing tree representations
    """

Decision Tree Processing

Utilities for processing and converting decision tree models between different formats.

def tree_to_string(tree, **kwargs) -> str:
    """
    Convert decision tree to string representation.
    
    Args:
        tree: Decision tree object
        **kwargs: Conversion parameters
        
    Returns:
        String representation of decision tree
    """

def rf_to_strings(
    random_forest,
    **kwargs
) -> List[str]:
    """
    Convert random forest to list of tree strings.
    
    Args:
        random_forest: Random forest model
        **kwargs: Conversion parameters
        
    Returns:
        List of decision tree strings
    """

def trees_to_csv(
    trees: List[str],
    output_path: str,
    **kwargs
) -> None:
    """
    Export decision trees to CSV file.
    
    Args:
        trees: List of tree string representations
        output_path: Output CSV file path
        **kwargs: Export parameters
    """

def csv_to_classifier(
    csv_path: str,
    classifier_type: str = "RandomForest",
    **kwargs
) -> ee.Classifier:
    """
    Import classifier from CSV file.
    
    Args:
        csv_path: Path to CSV file containing tree data
        classifier_type: Type of classifier to create
        **kwargs: Additional parameters
        
    Returns:
        Earth Engine classifier
    """

Earth Engine Data Catalog Integration

AI-powered tools for searching and discovering Earth Engine datasets with semantic capabilities.

class Catalog:
    """Earth Engine data catalog with AI-powered search."""
    
    def __init__(self, **kwargs) -> None:
        """Initialize catalog interface."""
    
    def search(
        self,
        keywords: str = None,
        spatial_filter: ee.Geometry = None,
        temporal_filter: List[str] = None,
        **kwargs
    ) -> List[Dict]:
        """
        Search Earth Engine catalog with AI assistance.
        
        Args:
            keywords: Search keywords or natural language query
            spatial_filter: Geographic area of interest
            temporal_filter: Date range [start_date, end_date]
            **kwargs: Additional search parameters
            
        Returns:
            List of matching dataset information
        """

class Collection:
    """Earth Engine collection wrapper with AI capabilities."""
    
    def __init__(self, collection_id: str, **kwargs) -> None:
        """
        Initialize collection wrapper.
        
        Args:
            collection_id: Earth Engine collection ID
            **kwargs: Additional parameters
        """

class CollectionList:
    """List of Earth Engine collections with search capabilities."""
    
    def __init__(self, collections: List[Collection] = None, **kwargs) -> None:
        """
        Initialize collection list.
        
        Args:
            collections: List of collection objects
            **kwargs: Additional parameters
        """

Precomputed Embeddings

Manage and utilize precomputed embeddings for semantic search and analysis.

class PrecomputedEmbeddings:
    """Precomputed embeddings for semantic search."""
    
    def __init__(
        self,
        embeddings_path: str = None,
        **kwargs
    ) -> None:
        """
        Initialize precomputed embeddings.
        
        Args:
            embeddings_path: Path to embeddings file
            **kwargs: Additional parameters
        """
    
    def search(
        self,
        query: str,
        top_k: int = 10,
        **kwargs
    ) -> List[Dict]:
        """
        Search using semantic embeddings.
        
        Args:
            query: Search query text
            top_k: Number of top results to return
            **kwargs: Additional search parameters
            
        Returns:
            List of semantically similar results
        """

Bounding Box and Geometry

AI-enhanced geometry processing and bounding box operations.

class BBox:
    """Bounding box representation with AI utilities."""
    
    def __init__(
        self,
        bounds: List[float] = None,
        crs: str = "EPSG:4326",
        **kwargs
    ) -> None:
        """
        Initialize bounding box.
        
        Args:
            bounds: Bounding box coordinates [minx, miny, maxx, maxy]
            crs: Coordinate reference system
            **kwargs: Additional parameters
        """
    
    def to_ee_geometry(self) -> ee.Geometry:
        """
        Convert bounding box to Earth Engine geometry.
        
        Returns:
            Earth Engine geometry object
        """

Code Execution and Analysis

Execute and analyze Earth Engine code with AI assistance.

def run_ee_code(
    code: str,
    show_map: bool = True,
    **kwargs
) -> Any:
    """
    Execute Earth Engine code with AI assistance.
    
    Args:
        code: Earth Engine Python code to execute
        show_map: Whether to display map if created
        **kwargs: Additional execution parameters
        
    Returns:
        Execution result
    """

def make_langchain_index(
    docs: List[str],
    index_name: str = "geemap_index",
    **kwargs
) -> Any:
    """
    Create LangChain index for document search.
    
    Args:
        docs: List of documents to index
        index_name: Name for the index
        **kwargs: Index configuration parameters
        
    Returns:
        LangChain index object
    """

Utility Functions

Helper functions for AI and machine learning workflows.

def matches_interval(
    value: float,
    interval: List[float],
    **kwargs
) -> bool:
    """
    Check if value matches specified interval.
    
    Args:
        value: Value to check
        interval: Interval bounds [min, max]
        **kwargs: Additional parameters
        
    Returns:
        True if value is within interval
    """

def matches_datetime(
    date_str: str,
    pattern: str,
    **kwargs
) -> bool:
    """
    Check if datetime string matches pattern.
    
    Args:
        date_str: Date string to check
        pattern: Date pattern to match
        **kwargs: Additional parameters
        
    Returns:
        True if date matches pattern
    """

Usage Examples

Genie AI Assistant

import geemap

# Create Genie AI assistant
genie = geemap.Genie()

# Display the assistant widget
genie

# The Genie widget provides:
# - Natural language to Earth Engine code conversion
# - Interactive guidance for geospatial analysis
# - Code suggestions and optimization
# - Help with Earth Engine API usage

Machine Learning Classification

import ee

# Initialize Earth Engine
ee.Initialize()

# Prepare training data
training_points = ee.FeatureCollection('projects/google/ml_training_data')

# Create and train classifier
classifier = geemap.fc_to_classifier(
    training_points,
    classifier='RandomForest',
    mode='classification'
)

# Apply classifier to image
image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318')
classified = image.classify(classifier)

# Display results
m = geemap.Map()
m.addLayer(classified, {'min': 0, 'max': 3, 'palette': ['red', 'green', 'blue', 'yellow']}, 'Classified')
m

Decision Tree Export and Import

# Export trained classifier trees
trees_fc = geemap.export_trees_to_fc(classifier, training_points)

# Convert trees to strings
tree_strings = geemap.rf_to_strings(classifier)

# Export to CSV
geemap.trees_to_csv(tree_strings, 'classifier_trees.csv')

# Import classifier from CSV
imported_classifier = geemap.csv_to_classifier('classifier_trees.csv')

AI-Powered Dataset Search

# Create catalog interface
catalog = geemap.Catalog()

# Search with natural language
results = catalog.search(
    keywords="high resolution satellite imagery of forests",
    spatial_filter=ee.Geometry.Rectangle([-120, 35, -115, 40]),
    temporal_filter=['2020-01-01', '2020-12-31']
)

# Display results
for result in results[:5]:
    print(f"Dataset: {result['title']}")
    print(f"Description: {result['description']}")
    print(f"ID: {result['id']}")
    print("---")

Semantic Search with Embeddings

# Initialize precomputed embeddings
embeddings = geemap.PrecomputedEmbeddings('path/to/embeddings.pkl')

# Perform semantic search
results = embeddings.search(
    query="forest loss detection using machine learning",
    top_k=5
)

# Process results
for result in results:
    print(f"Similarity: {result['score']:.3f}")
    print(f"Content: {result['text']}")
    print("---")

Code Execution with AI

# Execute Earth Engine code with assistance
ee_code = """
var image = ee.Image('MODIS/006/MOD13A2/2020_01_01');
var ndvi = image.select('NDVI');
Map.addLayer(ndvi, {min: 0, max: 9000, palette: ['red', 'yellow', 'green']}, 'NDVI');
"""

result = geemap.run_ee_code(ee_code, show_map=True)

LangChain Integration

# Create document index for search
documents = [
    "Earth Engine provides access to satellite imagery",
    "MODIS data is useful for vegetation monitoring",
    "Landsat offers medium resolution multispectral data"
]

index = geemap.make_langchain_index(
    documents,
    index_name="earth_engine_docs"
)

# Use index for question answering
# (Additional LangChain code would go here)

Bounding Box Operations

# Create bounding box
bbox = geemap.BBox(bounds=[-122, 37, -121, 38])

# Convert to Earth Engine geometry
ee_geom = bbox.to_ee_geometry()

# Use in Earth Engine operations
image = ee.Image('LANDSAT/LC08/C02/T1_L2/LC08_044034_20140318')
clipped = image.clip(ee_geom)

Types

# Classifier types
ClassifierType = Literal["RandomForest", "SVM", "NaiveBayes", "DecisionTree"]

# Classification mode
ClassificationMode = Literal["classification", "regression"]

# Search results
SearchResult = Dict[str, Union[str, float, List]]

# Embedding vector
Embedding = List[float]

# Date interval
DateInterval = List[str]  # [start_date, end_date]

# Bounding box coordinates
BoundsCoords = List[float]  # [minx, miny, maxx, maxy]

# Tree representation
TreeString = str

# AI query response
AIResponse = Dict[str, Any]

Install with Tessl CLI

npx tessl i tessl/pypi-geemap

docs

ai-ml.md

data-conversion.md

data-export.md

earth-engine.md

index.md

interactive-mapping.md

visualization.md

widgets-tools.md

tile.json