o
    Ďi'                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlmZ eZ	e
ZeZee	eef Zdedee dee d	ed
edefddZdee dee
 dee dee dee de
ded	ed
edee fddZdee dee
 dee dee ded	ed
edefddZdS )zGeofence-related utility functions.

Provides functions for checking geofencing rules and rolling up
classification labels based on geographic restrictions and taxonomic levels.
    )Optional)Classification)get_ancestor_at_level)get_full_class_stringlabelcountryadmin1_regiongeofence_mapenable_geofencereturnc           
      C   s   |sdS |sdS t | }||vrdS || d}|r/||vr!dS || }|r/|r/||vr/dS || d}|rL||v rL|| }	|	sDdS |rL||	v rLdS dS )a  Checks whether to geofence animal prediction in a country or admin1_region.

    Args:
        label:
            Animal label to check geofence rules for.
        country:
            Country (in ISO 3166-1 alpha-3 format) to check geofence rules for.
            Optional.
        admin1_region:
            First-level administrative division (in ISO 3166-2 format) to check
            geofence rules for. Optional.
        geofence_map:
            Dictionary mapping full class strings to geofence rules.
        enable_geofence:
            Whether geofencing is enabled.

    Returns:
        A boolean indicating whether to geofence given animal prediction.
    FallowTblock)r   get)
r   r   r   r	   r
   full_class_stringallow_countriesallow_admin1_regionsblock_countriesblock_admin1_regions r   U/home/jeff/fluffinator/venv/lib/python3.10/site-packages/speciesnet/geofence_utils.py%should_geofence_animal_classification"   s6   r   labelsscorestarget_taxonomy_levelsnon_blank_thresholdtaxonomy_mapc	                 C   s   h d}	t ||	}
|
rtd|
 d|	 d|D ]P}i }t| |D ]\}}t|||d}|r<||d| }|||< q#d}d}| D ]\}}||krYt|||||sY|}|}qE||krj|rj||d| f  S qdS )	a  Rolls up prediction labels to the first taxonomy level above given threshold.

    Args:
        labels:
            List of classification labels.
        scores:
            List of classification scores.
        country:
            Country (in ISO 3166-1 alpha-3 format) associated with prediction.
            Optional.
        admin1_region:
            First-level administrative division (in ISO 3166-2 format) associated
            with prediction. Optional.
        target_taxonomy_levels:
            Ordered list of taxonomy levels at which to roll up classification
            labels and check if the cumulative score passes the given threshold.
            Levels must be a subset of: "species", "genus", "family", "order",
            "class", "kingdom".
        non_blank_threshold:
            Min threshold at which the cumulative score is good enough to consider
            the rollup successful.
        taxonomy_map:
            Dictionary mapping taxa to labels.
        geofence_map:
            Dictionary mapping full class strings to geofence rules.
        enable_geofence:
            Whether geofencing is enabled.

    Returns:
        A tuple of <label, score, prediction_source> describing the first taxonomy
        level at which the cumulative score passes the given threshold. If no such
        level exists, return `None`.

    Raises:
        ValueError:
            If the taxonomy level if not one of: "species", "genus", "family",
            "order", "class", "kingdom".
    >   classgenusorderfamilykingdomspeciesz%Unexpected target taxonomy level(s): z%. Expected only levels from the set: .)r   taxonomy_levelr   g        Nzclassifier+rollup_to_)set
difference
ValueErrorzipr   r   itemsr   )r   r   r   r   r   r   r   r	   r
   expected_target_taxonomy_levelsunknown_target_taxonomy_levelsr#   accumulated_scoresr   scorerollup_label	new_scoremax_rollup_labelmax_rollup_scorerollup_scorer   r   r   &roll_up_labels_to_first_matching_levelj   sP   2
r2   c                 C   s   t | d ||||r9t| |||g d|d d |||d	}|r1|\}}	}
||	d|
tdd  fS tj|d dfS | d |d d	fS )
a  Geofences animal prediction in a country or admin1_region.

    Under the hood, this also rolls up the labels every time it encounters a
    geofenced label.

    Args:
        labels:
            List of classification labels.
        scores:
            List of classification scores.
        country:
            Country (in ISO 3166-1 alpha-3 format) associated with prediction.
            Optional.
        admin1_region:
            First-level administrative division (in ISO 3166-2 format) associated
            with prediction. Optional.
        taxonomy_map:
            Dictionary mapping taxa to labels.
        geofence_map:
            Dictionary mapping full class strings to geofence rules.
        enable_geofence:
            Whether geofencing is enabled.

    Returns:
        A tuple of <label, score, prediction_source> describing the result of the
        combined geofence and rollup operations.
    r   )r   r   r   r    g|=)	r   r   r   r   r   r   r   r	   r
   zclassifier+geofence+zclassifier+Nz!classifier+geofence+rollup_failed
classifier)r   r2   lenr   UNKNOWN)r   r   r   r   r   r	   r
   rollupr-   r1   rollup_sourcer   r   r   geofence_animal_classification   s2   &

r8   N)__doc__typingr   speciesnet.constantsr   speciesnet.taxonomy_utilsr   r   strPredictionLabelTypefloatPredictionScoreTypePredictionSourceTypetuplePredictionTypedictboolr   listr2   r8   r   r   r   r   <module>   sx   
H	

e	