o
    Ďi                      @   sj  d Z dgZddlZddlmZ ddlmZ ddlm	Z	 ddl
Z
ddlZddlZddlmZmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z" ddl!m#Z# ddl!m$Z$ ddl!m%Z% ddl!m&Z& ddl!m'Z' ee(e	f Z)e*e(ee& f Z+e*e(e,e" f Z-e*e(ee& f Z.e/de e/de e/de G dd dej0Z1G dd dZ2dede(de
j3e+ d dfd!d"Z4	dMded#e
j3e+ d$e5d%ee
j3e-  d df
d&d'Z6d(ed%e
j3e- d)e
j3e. d dfd*d+Z7d(ed#e
j3e. d$e5d,e8d df
d-d.Z9de(d/ee( d0ee( d1ee: d2ee: d$e5d dfd3d4Z;		dNd5ed6e,e( d7e5e(e5f d8e5e(e5f d9e5e(e5f d:e5e(e5f d;ee) d<eej< d ee5 fd=d>Z=		dNd6e,e( d?e5e(e5f d:e5e(e5f d@ed;ee) d<eej< d ee5 fdAdBZ>dCed e*e1ej<f fdDdEZ?dFee1 d dfdGdHZ@dIeAd dfdJdKZBG dLd dZCdS )Oah  Multiprocessing utilities to run SpeciesNet.

Provides utilities for running the SpeciesNet model with various forms of
parallelization, including multi-threading and multiprocessing. It implements a main
`SpeciesNet` class, that serves as a high level interface to interact with the different
SpeciesNet components using different parallelization strategies.

SpeciesNet    N)SyncManager)
ThreadPool)Path)CallableLiteralOptionalUnion)logging)tqdm)SpeciesNetClassifier)Failure)SpeciesNetDetector)SpeciesNetEnsemble)#combine_predictions_for_single_itemfind_admin1_regionBBox)load_partial_predictions)load_rgb_image)prepare_instances_dict)PreprocessedImage)save_predictions
ClassifierDetectorEnsemblec                       sB   e Zd ZdZdededdf fddZddd	Zdd
dZ  Z	S )RepeatedActiona!  Repeated action to run regularly at a given interval.

    Implements a threading mechanism to execute a specific function repeatedly at set
    time intervals. It's commonly used for background tasks such as saving partial
    results periodically during long-running inference jobs.
    intervalfnreturnNc                    s0   t    || _|| _|| _|| _t | _dS )a  Initializes the repeated action.

        Args:
            interval:
                Number of seconds (can be fractional) to wait before repeating the
                action.
            fn:
                Callable representing the action to repeat.
            *fn_args:
                Arguments for the action to repeat.
            **fn_kwargs:
                Keyword arguments for the action to repeat.
        N)	super__init__	_interval_fn_fn_args
_fn_kwargs	threadingEvent_stopped)selfr   r   fn_args	fn_kwargs	__class__ V/home/jeff/fluffinator/venv/lib/python3.10/site-packages/speciesnet/multiprocessing.pyr"   I   s   
zRepeatedAction.__init__c                 C   sL   | j  s$| j | j | j  rdS | j| ji | j | j  rdS dS )zStarts the repeated action.N)r)   is_setwaitr#   r$   r%   r&   r*   r/   r/   r0   run_   s   

zRepeatedAction.runc                 C   s   | j   dS )zStops the repeated action.N)r)   setr3   r/   r/   r0   stoph   s   zRepeatedAction.stopr    N)
__name__
__module____qualname____doc__floatr   r"   r4   r6   __classcell__r/   r/   r-   r0   r   A   s
    
	r   c                   @   sd   e Zd ZdZ			ddee dee dee deej	 ddf
dd	Z
d
eddfddZdddZdS )Progressa  Progress tracker for different components of SpeciesNet.

    Provides a mechanism to track the progress of various tasks within the SpeciesNet
    inference process. It uses `tqdm` progress bars to visually show the status of each
    component, like detector preprocessing, detector prediction, classifier
    preprocessing, classifier prediction, and geolocation operations. It offers a way to
    update individual trackers as the inference progresses, and to stop tracking when
    inference is complete.
    Nenabledtotalbatchesrlockr    c                 C   s   dt _|r
t | i | _d|v rt d|ddd| jd< d|v r+t d|ddd| jd< d	|v r:t d
|ddd| jd	< d|v rKt d|pC|ddd| jd< d|v r\t d|ddd| jd< dS dS )a  Initializes the progress tracker.

        Args:
            enabled:
                List of enabled trackers from the following list:
                ["detector_preprocess", "detector_predict", "classifier_preprocess",
                "classifier_predict", "geolocation"].
            total:
                Number of expected iterations. Optional.
            batches:
                Number of expected batches. Optional.
            rlock:
                RLock object to use as the global tracking lock. Optional.
        r   detector_preprocesszDetector preprocess   z#029e73)descr@   minintervalcolourdetector_predictzDetector predict      z#ece133classifier_preprocesszClassifier preprocess z#d55e00classifier_predictzClassifier predict    z#0184cbgeolocationzGeolocation           z#01b2b2N)r   monitor_intervalset_lock_pbars)r*   r?   r@   rA   rB   r/   r/   r0   r"   y   sP   
zProgress.__init__namec                 C   s    || j v r| j |   dS dS )zUpdates individual tracker.

        Args:
            name:
                Name of the individual tracker to update.
        N)rM   update)r*   rN   r/   r/   r0   rO      s   
zProgress.updatec                 C   s   | j  D ]}|  qdS )zStops progress tracking.N)rM   valuesclose)r*   pbarr/   r/   r0   r6      s   
zProgress.stop)NNNr7   )r8   r9   r:   r;   liststrr   intr'   RLockr"   rO   r6   r/   r/   r/   r0   r>   n   s$    
?r>   detectorfilepathdetector_queuer    c                 C   s>   t |}z| |}|||f W dS    ||df  )aq  Prepares the input for detector inference.

    Responsible for loading and preprocessing an image in preparation for the detector.

    Args:
        detector:
            SpeciesNetDetector to use.
        filepath:
            Path to image to load and preprocess.
        detector_queue:
            Output queue for preprocessed images for detector inference.
    N)r   
preprocessput)rW   rX   rY   imgr/   r/   r0   _prepare_detector_input   s   
r]   input_queueresults_dictbboxes_queuec                 C   sP   |  \}}| ||}|||< |r&| dg }||dd |D f dS dS )a8  Runs detector inference.

    Takes a preprocessed image from the input queue and runs the detector model on it.
    The raw output of the detector is stored in `results_dict` and the list of bounding
    boxes is additionally stored in `bboxes_queue`.

    Args:
        detector:
            SpeciesNetDetector to run.
        input_queue:
            Input queue of preprocessed images.
        results_dict:
            Output dict for inference results.
        bboxes_queue:
            Output queue for bounding boxes identified during inference. Optional.
    
detectionsc                 S      g | ]}t |d   qS bboxr   .0detr/   r/   r0   
<listcomp>      z!_run_detector.<locals>.<listcomp>N)getpredictr[   )rW   r^   r_   r`   rX   r\   
predictionra   r/   r/   r0   _run_detector   s   rm   
classifierclassifier_queuec                 C   sN   |  \}}t|}z| j||d}|||f W dS    ||df  )an  Prepares the input for classifier inference.

    Takes bounding box information from `bboxes_queue` and uses it to load and
    preprocess the image for classifier inference. It first loads the image,
    preprocesses it by potentially cropping based on bboxes and finally outputs the
    image into `classifier_queue` to be used by the classifier model.

    Args:
        classifier:
            SpeciesNetClassifier to use.
        bboxes_queue:
            Input queue of bounding boxes from detector inference.
        classifier_queue:
            Output queue for preprocessed images for classifier inference.
    bboxesN)rj   r   rZ   r[   )rn   r`   ro   rX   rq   r\   r/   r/   r0   _prepare_classifier_input  s   rr   
batch_sizec           
         s^    fddt |D }dd |D }dd |D }| ||}t||D ]\}}	|	||< q$dS )a  Runs classifier inference.

    Takes a batch of preprocessed images from the input queue and runs the classifier
    model on it. The output of the classifier is stored in `results_dict`.

    Args:
        classifier:
            SpeciesNetClassifier to run.
        input_queue:
            Input queue of preprocessed images.
        results_dict:
            Output dict for inference results.
        batch_size:
            Batch size for inference.

    c                    s   g | ]}   qS r/   )rj   )rf   _r^   r/   r0   rh   :      z#_run_classifier.<locals>.<listcomp>c                 S      g | ]}|d  qS )r   r/   rf   tr/   r/   r0   rh   ;  rv   c                 S   rw   )   r/   rx   r/   r/   r0   rh   <  rv   N)rangebatch_predictzip)
rn   r^   r_   rs   input_tuples	filepathsimgspredictionsrX   rl   r/   ru   r0   _run_classifier#  s   
r   countryadmin1_regionlatitude	longitudec                 C   s$   t ||||}||||d|| < dS )a  Find the first-level administrative division for a given (lat, lon) location.

    This function uses the provided geographic information to find the first-level
    administrative division (e.g., state in the USA) using the `find_admin1_region()`
    function. The result is stored in the `results_dict`.

    Args:
        filepath:
            Image filepath.
        country:
            Country in ISO 3166-1 alpha-3 format. Optional.
        admin1_region:
            First-level administrative division in ISO 3166-2 format. Optional.
        latitude:
            Float value representing latitude. Optional.
        longitude:
            Float value representing longitude. Optional.
        results_dict:
            Output dict for geolocation results.
    r   r   r   r   Nr   )rX   r   r   r   r   r_   admin1_resultr/   r/   r0   _find_admin1_regionB  s   r   ensembler   classifier_resultsdetector_resultsgeolocation_resultspartial_predictionspredictions_json	save_lockc           
      C   sj   | j |||||d}d|i}	|r3|r,| t|	| W d   dS 1 s%w   Y  dS t|	| dS |	S )a  Combines inference results from multiple jobs that ran independently.

    Brings together results from the classifier, detector, and geolocation steps to
    create the final predictions. The SpeciesNet ensemble model is used to combine these
    results, which may be saved to a JSON file.

    Args:
        ensemble:
            SpeciesNetEnsemble to run.
        filepaths:
            List of filepaths to ensemble predictions for.
        classifier_results:
            Dict of classifier results, with keys given by the filepaths to ensemble
            predictions for.
        detector_results:
            Dict of detector results, with keys given by the filepaths to ensemble
            predictions for.
        geolocation_results:
            Dict of geolocation results, with keys given by the filepaths to ensemble
            predictions for.
        partial_predictions:
            Dict of partial predictions from previous ensemblings, with keys given by
            the filepaths for which predictions where already ensembled. Used to skip
            re-ensembling for the matching filepaths.
        predictions_json:
            Output filepath where to save the predictions dict in JSON format. If
            `None`, predictions are not saved to a file and are returned instead.
        save_lock:
            Threading lock used to avoid race conditions when saving predictions to a
            file. Only needed when `predictions_json` is not `None`, otherwise it is
            ignored.

    Returns:
        The predictions dict of ensembled inference results if `predictions_json` is set
        to `None`, otherwise return `None` since predictions are saved to a file.
    )r   r   r   r   r   r   N)combiner   )
r   r   r   r   r   r   r   r   ensemble_resultspredictions_dictr/   r/   r0   _combine_resultsh  s   /"r   new_predictionsfailure_typec           	      C   s   g }| D ]$}||v r| ||  q||v r| ||  q| ||jgd qd|i}|rR|rK| t|| W d   dS 1 sDw   Y  dS t|| dS |S )a	  Merges new inference results with partial predictions from previous runs.

    Args:
        filepaths:
            List of filepaths to merge predictions for.
        new_predictions:
            Dict of new inference results keyed by filepaths.
        partial_predictions:
            Dict of partial predictions from previous runs, keyed by filepaths.
        failure_type:
            Type of failure to report when a prediction is missing.
        predictions_json:
            Output filepath where to save the predictions dict in JSON format. If
            `None`, predictions are not saved to a file and are returned instead.
        save_lock:
            Threading lock used to avoid race conditions when saving predictions to a
            file. Only needed when `predictions_json` is not `None`, otherwise it is
            ignored.

    Returns:
        The predictions dict of merged inference results if `predictions_json` is set
        to `None`, otherwise return `None` since predictions are saved to a file.
    )rX   failuresr   N)appendrN   r   )	r   r   r   r   r   r   resultsrX   r   r/   r/   r0   _merge_results  s(    "r   r   c                 O   s.   t  }t|d| |d|}|  ||fS )aZ  Starts periodic results saving every 10 minutes.

    Initiates a background thread to save partial results periodically to avoid losing
    progress during longer inference jobs.

    Args:
        fn:
            Callable for saving results.
        *fn_args:
            Arguments for the callable that saves results.
        **fn_kwargs:
            Keyword arguments for the callable that saves results.

    Returns:
        A tuple made of: (a) a repeated action to save results periodically, and (b) a
        threading lock used to avoid race conditions when saving predictions to a file.
    iX  )r   r   r   )r'   Lockr   start)r   r+   r,   r   periodic_saverr/   r/   r0   _start_periodic_results_saving  s   r   r   c                 C   s   | r|    |   dS dS )zkStops periodic results saving.

    Args:
        periodic_saver:
            Repeated action to stop.
    N)r6   join)r   r/   r/   r0   _stop_periodic_results_saving	  s   r   ec              
   C   s&   t ddtt| | | j dS )zTError callback to log inference errors.

    Args:
        e: Exception to log.
    zUnexpected inference error:
%s N)r
   errorr   	tracebackformat_exceptiontype__traceback__)r   r/   r/   r0   _error_callback  s   r   c                   @   s&  e Zd ZdZdddedddeded	 d
edee de	deddfddZ
dLddZ		dMdededee dee fddZ								dNdedededee dee	 dee	 dee	 dee	 dee	 dee fdd Z			dOdedededee dee f
d!d"Z			dOdedededee dee f
d#d$Z								dPded%ee dededee dee	 dee	 dee	 dee	 dee fd&d'Z				dQded%ee dededee dee fd(d)Z				dQded%ee dededee dee fd*d+Z						dRdededee dee	 dee	 dee	 dee	 dee fd,d-Z		dMdededee dee fd.d/Z		dMdededee dee fd0d1Z				dSded2ee d%ee dedee dee fd3d4Zddddddddd5dddd6dee d7ee d8eee  d9ee d:eee  d;ee d<ee d=ee d>ed? dededee dee fd@dAZdddddddddd5ddddBdee d7ee d8eee  d9ee d:eee  d;ee d<ee d=ee d%ee d>edC dededee dee fdDdEZddddddddd5dddFdee d7ee d8eee  d9ee d:eee  d;ee d<ee d=ee d>edC dedee dee fdGdHZdddddddddddddIdee d7ee d8eee  d9ee d:eee  d;ee d<ee d=ee d2ee d%ee dedee dee fdJdKZdS )Tr   a  Main interface for running inference with SpeciesNet.

    Offers a high-level interface to run inference with the SpeciesNet model, supporting
    various input formats. It is designed to handle full predictions (with both detector
    and classifier), classification only, detection only, or ensembling only tasks. It
    can also be run on a single thread, with multiple threads, or with multiple
    processes.
    allTNF)
componentsgeofencetarget_species_txtcombine_predictions_fnmultiprocessing
model_namer   )r   rn   rW   r   r   r   r   r   r    c                C   s   |r5t  | _| j  |dv r| jj||d| _|dv r#| j|| _|dv r3| jj|||d| _dS dS d| _|dv rCt	||d| _|dv rLt
|| _|dv rZt|||d| _dS dS )a  Initializes the SpeciesNet model with specified settings.

        Args:
            model_name:
                String value identifying the model to be loaded.
            components:
                String representing which model components to load and run. One of
                ["all", "classifier", "detector", "ensemble"]. Defaults to "all".
            geofence:
                Whether to enable geofencing during ensemble prediction. Defaults to
                `True`.
            target_species_txt:
                Path to a text file containing the target species to always output
                classification scores for. Optional.
            combine_predictions_fn:
                Function to tell the ensemble how to combine predictions from the
                individual model components (e.g. classifications, detections etc.)
            multiprocessing:
                Whether to enable multiprocessing or not. Defaults to `False`.
        )r   rn   )r   )r   rW   )r   r   )r   prediction_combinerN)r   managerr   r   rn   r   rW   r   r   r   r   r   )r*   r   r   r   r   r   r   r/   r/   r0   r"   -  s<   

zSpeciesNet.__init__c                 C   s6   | j rtt  t| j dr| j   dS dS dS )zCleanup method.shutdownN)r   r   rL   r'   rV   hasattrr   r3   r/   r/   r0   __del__j  s   zSpeciesNet.__del__instances_dictprogress_barsr   c              
   C   s  |d }dd |D }i }i }i }t ||\}	}
t|
}|r.tt| j|||||	|d\}}nd}d}t|r9g dng |t d}|
D ]{}|d }|d	}|d
}|d}|d}t	|}| j
|}|d | j
||||< |d || dd}|rdd |D }ng }| jj||d}|d | j||||< |d t||||}||||d||< |d qC|  |rt| t| j|||||	||dS )a  Runs prediction using a single thread, processing each image one by one.

        This approach is useful for debugging or in environments where parallelization
        is not suitable. All the inference components run sequentially within the same
        thread.

        Args:
            instances_dict:
                 Instances dict to process.
            progress_bars:
                Whether to show progress bars.
            predictions_json:
                Path where to save the JSON output.

        Returns:
             The predictions dict of ensembled inference results if `predictions_json`
             is set to `None`, otherwise return `None` since predictions are saved to
             a file.
        	instancesc                 S   rw   rX   r/   rf   instancer/   r/   r0   rh     rv   z;SpeciesNet._predict_using_single_thread.<locals>.<listcomp>r   r   r   r   r   r   r   NrC   rG   rH   rI   rJ   r?   r@   rB   rX   r   r   r   r   rC   rG   ra   c                 S   rb   rc   r   re   r/   r/   r0   rh     ri   rp   rH   rI   r   rJ   r   r   r   r   r   r   r   r   )r   lenr   r   r   r>   r'   rV   rj   r   rW   rZ   rO   rk   rn   r   r6   r   )r*   r   r   r   r   r   r   r   r   r   instances_to_processnum_instances_to_processr   r   progressr   rX   r   r   r   r   r\   detector_inputra   rq   classifier_inputr   r/   r/   r0   _predict_using_single_threadr  s   	









z'SpeciesNet._predict_using_single_thread   rs   new_pool_fnnew_list_fnnew_dict_fnnew_queue_fnnew_rlock_fnc
              
      s  |dusJ |dusJ |dusJ |dusJ |	dusJ |d }
|dd |
D }| }| }| }t ||
\}}||}t|}|| t|| d }|| }|sV|}|rhtt| j||||||d\}}nd}d}t|rsg dng |||	 d | }|d}|d}|td	| d
}| }|td	| d
}|D ]G}|jt	| j
|d |f fddtd |jt| j||f fddtd |jt|d |d|d|d|d|f fddtd qt|D ]}|jt| j
|||f fddtd qt|D ]}|jt| j||||d k r|n|f fddtd q|  |  |  |  |  |     |rDt| t| j|||||||dS )ah  Runs prediction using worker pools (multi-threading or multiprocessing).

        This method uses worker pools to process images concurrently. This is an
        abstract method that accepts worker pools of different types.

        Args:
            instances_dict:
                Instances dict to process.
            batch_size:
                Batch size for inference.
            progress_bars:
                Whether to show progress bars.
            predictions_json:
                Path where to save the JSON output.
            new_pool_fn:
                Callable that returns a new pool.
            new_list_fn:
                Callable that returns a list.
            new_dict_fn:
                Callable that returns a dict.
            new_queue_fn:
                Callable that returns a queue.
             new_rlock_fn:
                Callable that returns a thread/process lock.

        Returns:
            The predictions dict of ensembled inference results if `predictions_json`
            is set to `None`, otherwise return `None` since predictions are saved to
            a file.
        Nr   c                 S   rw   r   r/   r   r/   r/   r0   rh   +  rv   z:SpeciesNet._predict_using_worker_pools.<locals>.<listcomp>rz   r   r   r?   r@   rA   rB      @   rX   c                    
     dS NrC   rO   rt   r   r/   r0   <lambda>w     
 z8SpeciesNet._predict_using_worker_pools.<locals>.<lambda>argscallbackerror_callbackc                    r   NrH   r   r   r   r/   r0   r     r   r   r   r   r   c                    r   )NrJ   r   r   r   r/   r0   r     r   c                    r   NrG   r   r   r   r/   r0   r     r   c                    r   NrI   r   r   r   r/   r0   r     r   r   )r   r   minr   r   r   r>   maxapply_asyncr]   rW   r   rr   rn   r   rj   r{   rm   r   rQ   r   r6   r   )r*   r   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   num_batcheslast_batch_sizer   r   common_pooldetector_poolclassifier_poolrY   r`   ro   r   rt   	batch_idxr/   r   r0   _predict_using_worker_pools  s   *	







z&SpeciesNet._predict_using_worker_poolsc                 C   s    | j ||||ttttjtjd	S N)rs   r   r   r   r   r   r   r   )r   r   rS   dictqueueQueuer'   rV   r*   r   rs   r   r   r/   r/   r0   _predict_using_thread_pools  s   z&SpeciesNet._predict_using_thread_poolsc                 C   s<   | j d usJ | j||||tj| j j| j j| j j| j jd	S r   )r   r   mpPoolrS   r   r   rV   r   r/   r/   r0   _predict_using_process_pools  s   z'SpeciesNet._predict_using_process_poolsdetections_dictc
              	      s  |d usJ |d usJ |d usJ |	d usJ |d }
dd |
D }|p&i }| }t ||
\}}||}t|}|| t|| d }|| }|sL|}|r\tt|||tj|d\}}nd }d }t|rgddgng |||	 d | }|d}| }|td	| d
}|D ]-}|d }|	|i 	dg }|
|dd |D f |jt| j||f fddtd qt|D ]}|jt| j||||d k r|n|f fddtd q|  |  |  |     |rt| t|||tj||dS )Nr   c                 S   rw   r   r/   r   r/   r/   r0   rh     rv   z;SpeciesNet._classify_using_worker_pools.<locals>.<listcomp>rz   r   r   r   r   r   rH   rI   r   r   r   rX   ra   c                 S   rb   rc   r   re   r/   r/   r0   rh   7  ri   c                    r   r   r   r   r   r/   r0   r   ;  r   z9SpeciesNet._classify_using_worker_pools.<locals>.<lambda>r   c                    r   r   r   r   r   r/   r0   r   I  r   r   r   r   r   r   r   )r   r   r   r   r   r   
CLASSIFIERr>   r   rj   r[   r   rr   rn   r   r{   r   rQ   r   r6   r   )r*   r   r   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r`   ro   r   rX   ra   r   r/   r   r0   _classify_using_worker_pools  s   	


z'SpeciesNet._classify_using_worker_poolsc                 C   s    | j |||||tttjtjd	S N)r   rs   r   r   r   r   r   r   )r   r   r   r   r   r'   rV   r*   r   r   rs   r   r   r/   r/   r0   _classify_using_thread_poolsd  s   z'SpeciesNet._classify_using_thread_poolsc                 C   s8   | j d usJ | j|||||tj| j j| j j| j jd	S r   )r   r   r   r   r   r   rV   r   r/   r/   r0   _classify_using_process_poolsx  s   z(SpeciesNet._classify_using_process_poolsc                    sn  |d usJ |d usJ |d usJ |d usJ |d }dd |D }	| }
t ||\}}||}t|}|rEtt|	|
|tj|d\}}nd }d }t|rPddgng || d | }|d}|d	}|D ]}|jt| j	|d
 |f fddt
d qdt|D ]}|jt| j	||
f fddt
d q~|  |  |  |     |rt| t|	|
|tj||dS )Nr   c                 S   rw   r   r/   r   r/   r/   r0   rh     rv   z9SpeciesNet._detect_using_worker_pools.<locals>.<listcomp>r   rC   rG   r   rz   r   rX   c                    r   r   r   r   r   r/   r0   r     r   z7SpeciesNet._detect_using_worker_pools.<locals>.<lambda>r   c                    r   r   r   r   r   r/   r0   r     r   r   )r   r   r   r   r   DETECTORr>   r   r]   rW   r   r{   rm   rQ   r   r6   r   )r*   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rY   r   rt   r/   r   r0   _detect_using_worker_pools  s~   
	



z%SpeciesNet._detect_using_worker_poolsc              	   C   s   | j |||tttjtjdS N)r   r   r   r   r   r   )r   r   r   r   r   r'   rV   r*   r   r   r   r/   r/   r0   _detect_using_thread_pools  s   z%SpeciesNet._detect_using_thread_poolsc              	   C   s4   | j d usJ | j|||tj| j j| j j| j jdS r   )r   r   r   r   r   r   rV   r   r/   r/   r0   _detect_using_process_pools  s   z&SpeciesNet._detect_using_process_poolsclassifications_dictc              
   C   s  |d }dd |D }|pi }|pi }	i }
t ||\}}t|}|r2tt| j|||	|
||d\}}nd }d }t|r<dgng |t d}|D ]/}|d }|d}|d	}|d
}|d}t	||||}||||d|
|< |
d qF|  |rt| t| j|||	|
|||dS )Nr   c                 S   rw   r   r/   r   r/   r/   r0   rh     rv   z<SpeciesNet._ensemble_using_single_thread.<locals>.<listcomp>r   rJ   r   rX   r   r   r   r   r   r   )r   r   r   r   r   r>   r'   rV   rj   r   rO   r6   r   )r*   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rX   r   r   r   r   r   r/   r/   r0   _ensemble_using_single_thread  sn   




z(SpeciesNet._ensemble_using_single_threadmulti_thread)r   instances_jsonr   filepaths_txtfoldersfolders_txtr   r   run_moders   r   r   r  r   r  r  r  r   r   r  )single_threadr  multi_processc             	   C   sr   t ||||||||}|	dkr| j|||dS |	dkr$| j||
||dS |	dkr1| j||
||dS td|	 d)Nr  r   r   r  )rs   r   r   r  Unknown run mode: ``)r   r   r   r   
ValueError)r*   r   r  r   r  r  r  r   r   r  rs   r   r   r/   r/   r0   rk   e  s>   
zSpeciesNet.predict)r   r  r   r  r  r  r   r   r   r  rs   r   r   )r  r  c             	   C   s^   t ||||||||}|
dkr| j||	|||dS |
dkr'| j||	|||dS td|
 d)Nr  )r   rs   r   r   r  r
  r  )r   r   r   r  )r*   r   r  r   r  r  r  r   r   r   r  rs   r   r   r/   r/   r0   classify  s6   
zSpeciesNet.classify)r   r  r   r  r  r  r   r   r  r   r   c             	   C   sV   t ||||||||}|	dkr| j||
|dS |	dkr#| j||
|dS td|	 d)Nr  r	  r  r
  r  )r   r   r   r  )r*   r   r  r   r  r  r  r   r   r  r   r   r/   r/   r0   detect  s.   
zSpeciesNet.detect)r   r  r   r  r  r  r   r   r   r   r   r   c             	   C   s*   t ||||||||}| j||	|
||dS )N)r   r   r   r   )r   r   )r*   r   r  r   r  r  r  r   r   r   r   r   r   r/   r/   r0   ensemble_from_past_runs  s"   
z"SpeciesNet.ensemble_from_past_runsr7   )FN)r   FNNNNNN)r   FN)Nr   FNNNNN)Nr   FN)FNNNNN)NNFN)r8   r9   r:   r;   r   rT   r   boolr   r   r"   r   r   StrPathr   rU   r   r   r   r   r   r   r   r   r   r   rS   rk   r  r  r  r/   r/   r/   r0   r   #  s   	

=
 	

 N

	

|

	
g


V

	

6

	

1

	

+

	
)N)NN)Dr;   __all__r   r   multiprocessing.managersr   multiprocessing.poolr   pathlibr   r   r'   r   typingr   r   r   r	   abslr
   r   speciesnet.classifierr   speciesnet.constantsr   speciesnet.detectorr   speciesnet.ensembler   'speciesnet.ensemble_prediction_combinerr   speciesnet.geolocationr   speciesnet.utilsr   r   r   r   r   r   rT   r  tupleDetectorInputrS   
BBoxOutputClassifierInputregisterThreadr   r>   r   r]   r   rm   rr   rU   r   r<   r   r   r   r   r   r   	Exceptionr   r   r/   r/   r/   r0   <module>   s  	-\




-



	
F


=
#