o
    Vh%                     @   s  d dl Z d dlZd dlmZ d dlZd dlZd dlmZ d dl	m
Z
mZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZ d dlmZmZmZ d dlmZmZ d d	l m!Z! G d
d de
j"Z#G dd dZ$dd Z%d ddZ&d!ddZ'd"ddZ(dd Z)d#ddZ*dS )$    N)Path)Image)
dataloaderdistributed)GroundingDatasetYOLODatasetYOLOMultiModalDataset)LOADERSLoadImagesAndVideosLoadPilAndNumpyLoadScreenshotsLoadStreams
LoadTensorSourceTypesautocast_list)IMG_FORMATS
PIN_MEMORYVID_FORMATS)RANKcolorstr)
check_filec                       s@   e Zd ZdZ fddZdd Zdd Zdd	 Zd
d Z  Z	S )InfiniteDataLoadera  
    Dataloader that reuses workers.

    This dataloader extends the PyTorch DataLoader to provide infinite recycling of workers, which improves efficiency
    for training loops that need to iterate through the dataset multiple times.

    Attributes:
        batch_sampler (_RepeatSampler): A sampler that repeats indefinitely.
        iterator (Iterator): The iterator from the parent DataLoader.

    Methods:
        __len__: Returns the length of the batch sampler's sampler.
        __iter__: Creates a sampler that repeats indefinitely.
        __del__: Ensures workers are properly terminated.
        reset: Resets the iterator, useful when modifying dataset settings during training.
    c                    s6   t  j|i | t| dt| j t   | _dS )zHInitialize the InfiniteDataLoader with the same arguments as DataLoader.batch_samplerN)super__init__object__setattr___RepeatSamplerr   __iter__iterator)selfargskwargs	__class__ J/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/data/build.pyr   .   s   zInfiniteDataLoader.__init__c                 C   s   t | jjS )z1Return the length of the batch sampler's sampler.)lenr   samplerr    r%   r%   r&   __len__4   s   zInfiniteDataLoader.__len__c                 c   s$    t t| D ]}t| jV  qdS )zICreate an iterator that yields indefinitely from the underlying iterator.N)ranger'   nextr   )r    _r%   r%   r&   r   8   s   zInfiniteDataLoader.__iter__c                 C   sV   z t | jds
W dS | jjD ]
}| r|  q| j  W dS  ty*   Y dS w )zKEnsure that workers are properly terminated when the dataloader is deleted._workersN)hasattrr   r.   is_alive	terminate_shutdown_workers	Exception)r    wr%   r%   r&   __del__=   s   zInfiniteDataLoader.__del__c                 C   s   |   | _dS )zIReset the iterator to allow modifications to the dataset during training.N)_get_iteratorr   r)   r%   r%   r&   resetI   s   zInfiniteDataLoader.reset)
__name__
__module____qualname____doc__r   r*   r   r5   r7   __classcell__r%   r%   r#   r&   r      s    r   c                   @   s    e Zd ZdZdd Zdd ZdS )r   z
    Sampler that repeats forever.

    This sampler wraps another sampler and yields its contents indefinitely, allowing for infinite iteration
    over a dataset.

    Attributes:
        sampler (Dataset.sampler): The sampler to repeat.
    c                 C   s
   || _ dS )zDInitialize the _RepeatSampler with a sampler to repeat indefinitely.N)r(   )r    r(   r%   r%   r&   r   Y   s   
z_RepeatSampler.__init__c                 c   s    	 t | jE dH  q)z=Iterate over the sampler indefinitely, yielding its contents.TN)iterr(   r)   r%   r%   r&   r   ]   s   z_RepeatSampler.__iter__N)r8   r9   r:   r;   r   r   r%   r%   r%   r&   r   N   s    
r   c                 C   s&   t  d }tj| t| dS )zGSet dataloader worker seed for reproducibility across worker processes.l        N)torchinitial_seednprandomseed)	worker_idworker_seedr%   r%   r&   seed_workerc   s   rE   trainF    c           	      C   sz   |rt nt}||| j||dk| | jp|| jpd| jpdt||dkr$dndt| d| j| j	||dkr9| j
dS ddS )	zBBuild and return a YOLO dataset based on configuration parameters.rF   NF              ?:       ?)img_pathimgsz
batch_sizeaugmenthyprectcache
single_clsstridepadprefixtaskclassesdatafraction)r   r   rM   rQ   rR   rS   intr   rW   rX   rZ   )	cfgrL   batchrY   moderQ   rT   multi_modaldatasetr%   r%   r&   build_yolo_datasetj   s(   ra   c                 C   sn   t ||| j||dk| | jp|| jpd| jpdt||dkrdndt| d| j| j|dkr3| j	dS ddS )	zFBuild and return a GroundingDataset based on configuration parameters.rF   NFrH   rI   rJ   rK   )rL   	json_filerM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   rZ   )
r   rM   rQ   rR   rS   r[   r   rW   rX   rZ   )r\   rL   rb   r]   r^   rQ   rT   r%   r%   r&   build_grounding   s&   rc   Tc           	      C   s   t |t| }tj }t t t|d |}|dkrdntj	| |d}t
 }|dt  t| ||o8|du ||tt| ddt|d	S )a  
    Create and return an InfiniteDataLoader or DataLoader for training or validation.

    Args:
        dataset (Dataset): Dataset to load data from.
        batch (int): Batch size for the dataloader.
        workers (int): Number of worker threads for loading data.
        shuffle (bool): Whether to shuffle the dataset.
        rank (int): Process rank in distributed training. -1 for single-GPU training.

    Returns:
        (InfiniteDataLoader): A dataloader that can be used for training or validation.
       rd   N)shufflel   UU*UU* 
collate_fn)	r`   rN   rf   num_workersr(   
pin_memoryrg   worker_init_fn	generator)minr'   r>   cudadevice_countos	cpu_countmaxr   DistributedSampler	Generatormanual_seedr   r   r   getattrrE   )	r`   r]   workersrf   rankndnwr(   rk   r%   r%   r&   build_dataloader   s"   


rz   c                 C   s   d\}}}}}t | tttfrDt| } t| jdd ttB v }|  d}| 	 p4| 
dp4|o4| }|  dk}|rC|rCt| } n/t | trLd}n't | ttfrZt| } d}nt | tjtjfrfd}nt | tjrod}ntd| |||||fS )	a  
    Check the type of input source and return corresponding flag values.

    Args:
        source (str | int | Path | List | Tuple | np.ndarray | PIL.Image | torch.Tensor): The input source to check.

    Returns:
        source (str | int | Path | List | Tuple | np.ndarray | PIL.Image | torch.Tensor): The processed source.
        webcam (bool): Whether the source is a webcam.
        screenshot (bool): Whether the source is a screenshot.
        from_img (bool): Whether the source is an image or list of images.
        in_memory (bool): Whether the source is an in-memory object.
        tensor (bool): Whether the source is a torch.Tensor.

    Raises:
        TypeError: If the source type is unsupported.
    )FFFFFre   N)zhttps://zhttp://zrtsp://zrtmp://ztcp://z.streamsscreenTzZUnsupported image type. For supported types see https://docs.ultralytics.com/modes/predict)
isinstancestrr[   r   suffixr   r   lower
startswith	isnumericendswithr   r	   listtupler   r   r@   ndarrayr>   Tensor	TypeError)sourcewebcam
screenshotfrom_img	in_memorytensoris_fileis_urlr%   r%   r&   check_source   s*   
r   re   c                 C   s   t | \} }}}}}|r| jnt||||}	|rt| }
n$|r"| }
n|r,t| ||d}
n|r3t| }
n|r:t| }
nt| ||d}
t|
d|	 |
S )a  
    Load an inference source for object detection and apply necessary transformations.

    Args:
        source (str | Path | torch.Tensor | PIL.Image | np.ndarray, optional): The input source for inference.
        batch (int, optional): Batch size for dataloaders.
        vid_stride (int, optional): The frame interval for video sources.
        buffer (bool, optional): Whether stream frames will be buffered.

    Returns:
        (Dataset): A dataset object for the specified input source with attached source_type attribute.
    )
vid_stridebuffer)r]   r   source_type)	r   r   r   r   r   r   r   r
   setattr)r   r]   r   r   streamr   r   r   r   r   r`   r%   r%   r&   load_inference_source   s   


r   )rF   FrG   F)rF   FrG   )Trd   )Nre   re   F)+ro   rA   pathlibr   numpyr@   r>   PILr   torch.utils.datar   r   ultralytics.data.datasetr   r   r   ultralytics.data.loadersr	   r
   r   r   r   r   r   r   ultralytics.data.utilsr   r   r   ultralytics.utilsr   r   ultralytics.utils.checksr   
DataLoaderr   r   rE   ra   rc   rz   r   r   r%   r%   r%   r&   <module>   s(   (
2


!*