a
    yf^                     @   s.  d dl Z d dlZd dlZd dlZd dlm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Zd dlmZ d dlmZmZmZ d dlmZmZmZmZ d d	lmZ eG d
d dZG dd dZG dd dZ G dd dZ!G dd dZ"G dd dZ#dd Z$dddZ%ee"e!e fZ&dS )    N)	dataclass)Path)Thread)urlparse)Image)FORMATS_HELP_MSGIMG_FORMATSVID_FORMATS)IS_COLAB	IS_KAGGLELOGGERops)check_requirementsc                   @   sB   e Zd ZU dZdZeed< dZeed< dZeed< dZ	eed< dS )SourceTypeszBClass to represent various types of input sources for predictions.Fstream
screenshotfrom_imgtensorN)
__name__
__module____qualname____doc__r   bool__annotations__r   r   r    r   r   T/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/data/loaders.pyr      s
   
r   c                   @   sB   e Zd ZdZdddZdd Zd	d
 Zdd Zdd Zdd Z	dS )LoadStreamsaQ  
    Stream Loader for various types of video streams, Supports RTSP, RTMP, HTTP, and TCP streams.

    Attributes:
        sources (str): The source input paths or URLs for the video streams.
        vid_stride (int): Video frame-rate stride, defaults to 1.
        buffer (bool): Whether to buffer input streams, defaults to False.
        running (bool): Flag to indicate if the streaming thread is running.
        mode (str): Set to 'stream' indicating real-time capture.
        imgs (list): List of image frames for each stream.
        fps (list): List of FPS for each stream.
        frames (list): List of total frames for each stream.
        threads (list): List of threads for each stream.
        shape (list): List of shapes for each stream.
        caps (list): List of cv2.VideoCapture objects for each stream.
        bs (int): Batch size for processing.

    Methods:
        __init__: Initialize the stream loader.
        update: Read stream frames in daemon thread.
        close: Close stream loader and release resources.
        __iter__: Returns an iterator object for the class.
        __next__: Returns source paths, transformed, and original images for processing.
        __len__: Return the length of the sources object.

    Example:
         ```bash
         yolo predict source='rtsp://example.com/media.mp4'
         ```
    file.streams   Fc                 C   s  dt jj_|| _d| _d| _|| _tj	
|r>t|  n|g}t|}|| _dg| | _dg| | _dg| | _dg| | _dd t|D | _dd t|D | _dd |D | _t|D ]\}}|d	  d
| d| d}t|jdv rt|}| rt|n|}|dkr0ts(tr0t dt!"|| j|< | j| # sbt$| d| t%| j| &t!j'}t%| j| &t!j(}	| j| &t!j)}
t*t%| j| &t!j+dpt,d| j|< t*t-.|
r|
ndd dpd| j|< | j| / \}}|r|du r*t$| d| | j| 0| |j| j|< t1| j2|| j| |gdd| j|< t34| d| j|  d| d|	 d| j| dd
 | j| 5  qt34d dS )zKInitialize instance variables and check for consistent input stream shapes.Tr   r   Nc                 S   s   g | ]}g qS r   r   .0_r   r   r   
<listcomp>P       z(LoadStreams.__init__.<locals>.<listcomp>c                 S   s   g | ]}g qS r   r   r   r   r   r   r"   Q   r#   c                 S   s   g | ]}t |qS r   )r   Z	clean_strr    xr   r   r   r"   R   r#   r   /: z... >   zwww.youtube.comzyoutube.comzyoutu.bezm'source=0' webcam not supported in Colab and Kaggle notebooks. Try running 'source=0' in a local environment.zFailed to open infd      zFailed to read images from )targetargsdaemonu   Success ✅ (z frames of shape r%   z at z.2fz FPS) )6torchbackendsZcudnnZ	benchmarkbufferrunningmode
vid_strideospathisfiler   	read_textrsplitlenbsfpsframesthreadscapsrangeimgsshapesources	enumerater   hostnameget_best_youtube_url	isnumericevalr
   r   NotImplementedErrorcv2VideoCaptureisOpenedConnectionErrorintgetZCAP_PROP_FRAME_WIDTHZCAP_PROP_FRAME_HEIGHTCAP_PROP_FPSmaxCAP_PROP_FRAME_COUNTfloatmathisfinitereadappendr   updater   infostart)selfrC   r4   r1   nisstwhr<   successimr   r   r   __init__A   sV    
" 
*"6zLoadStreams.__init__c                 C   s   d| j |  }}| jr| r||d k rt| j| dk r|d7 }|  || j dkr| \}}|stj	| j
| tjd}td || | jr| j| | q|g| j|< qtd qdS )z(Read stream `i` frames in daemon thread.r   r   r*   dtypeuQ   WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.g{Gz?N)r=   r2   rL   r:   rA   grabr4   retrievenpzerosrB   uint8r   warningopenr1   rW   timesleep)r[   r]   capr   r\   frb   rc   r   r   r   rX   t   s    

zLoadStreams.updatec                 C   s   d| _ | jD ]}| r|jdd q| jD ]F}z|  W q, typ } ztd|  W Y d}~q,d}~0 0 q,t	
  dS )z*Close stream loader and release resources.F   )timeoutu6   WARNING ⚠️ Could not release VideoCapture object: N)r2   r>   is_alivejoinr?   release	Exceptionr   rl   rJ   ZdestroyAllWindows)r[   threadrp   er   r   r   close   s    

(zLoadStreams.closec                 C   s
   d| _ | S )zCIterates through YOLO image feed and re-opens unresponsive streams.countr[   r   r   r   __iter__   s    zLoadStreams.__iter__c                 C   s   |  j d7  _ g }t| jD ]\}}|s| j|  rHtdtdkrT|   t	t
dt| j  | j| }|s$td|  q$| jr||d q||r|dntj| j| tjd |  q| j|dg| j fS )zEReturns source paths, transformed and original images for processing.r   qu"   WARNING ⚠️ Waiting for stream r   r{   re   r.   )r}   rD   rA   r>   rt   rJ   ZwaitKeyordrz   StopIterationrn   ro   minr<   r   rl   r1   rW   popri   rj   rB   rk   clearrC   r;   )r[   imagesr]   r%   r   r   r   __next__   s      
*
zLoadStreams.__next__c                 C   s   | j S )z(Return the length of the sources object.r;   r~   r   r   r   __len__   s    zLoadStreams.__len__N)r   r   F)
r   r   r   r   rd   rX   rz   r   r   r   r   r   r   r   r   !   s   
3r   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	LoadScreenshotsa  
    YOLOv8 screenshot dataloader.

    This class manages the loading of screenshot images for processing with YOLOv8.
    Suitable for use with `yolo predict source=screen`.

    Attributes:
        source (str): The source input indicating which screen to capture.
        screen (int): The screen number to capture.
        left (int): The left coordinate for screen capture area.
        top (int): The top coordinate for screen capture area.
        width (int): The width of the screen capture area.
        height (int): The height of the screen capture area.
        mode (str): Set to 'stream' indicating real-time capture.
        frame (int): Counter for captured frames.
        sct (mss.mss): Screen capture object from `mss` library.
        bs (int): Batch size, set to 1.
        monitor (dict): Monitor configuration details.

    Methods:
        __iter__: Returns an iterator object.
        __next__: Captures the next screenshot and returns it.
    c           	      C   s:  t d ddl}| ^}}d\| _}}}}t|dkrHt|d | _nJt|dkrldd |D \}}}}n&t|d	krd
d |D \| _}}}}d| _d| _| | _d| _	d| _
| jj| j }|du r|d n
|d | | _|du r|d n
|d | | _|p
|d | _|p|d | _| j| j| j| jd| _dS )z8Source = [screen_number left top width height] (pixels).mssr   N)r   NNNNr      c                 s   s   | ]}t |V  qd S NrN   r$   r   r   r   	<genexpr>   r#   z+LoadScreenshots.__init__.<locals>.<genexpr>rr   c                 s   s   | ]}t |V  qd S r   r   r$   r   r   r   r      r#   r   r*   topleftwidthheight)r   r   r   r   )r   r   splitscreenr:   rN   r3   framesctr;   r<   Zmonitorsr   r   r   r   monitor)	r[   sourcer   paramsr   r   r   r   r   r   r   r   rd      s*    
zLoadScreenshots.__init__c                 C   s   | S )z"Returns an iterator of the object.r   r~   r   r   r   r      s    zLoadScreenshots.__iter__c                 C   s|   t | j| jddddddf }d| j d| j d| j d| j d| j	 d}|  j
d7  _
t| jg|g|gfS )zHScreen capture with 'mss' to get raw pixels from the screen as np array.N   zscreen z	 (LTWH): ,r'   r   )ri   asarrayr   rg   r   r   r   r   r   r   r   str)r[   im0r^   r   r   r   r      s    *.zLoadScreenshots.__next__N)r   r   r   r   rd   r   r   r   r   r   r   r      s   r   c                   @   s:   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )LoadImagesAndVideosa  
    YOLOv8 image/video dataloader.

    This class manages the loading and pre-processing of image and video data for YOLOv8. It supports loading from
    various formats, including single image files, video files, and lists of image and video paths.

    Attributes:
        files (list): List of image and video file paths.
        nf (int): Total number of files (images and videos).
        video_flag (list): Flags indicating whether a file is a video (True) or an image (False).
        mode (str): Current mode, 'image' or 'video'.
        vid_stride (int): Stride for video frame-rate, defaults to 1.
        bs (int): Batch size, set to 1 for this class.
        cap (cv2.VideoCapture): Video capture object for OpenCV.
        frame (int): Frame counter for video.
        frames (int): Total number of frames in the video.
        count (int): Counter for iteration, initialized at 0 during `__iter__()`.

    Methods:
        _new_video(path): Create a new cv2.VideoCapture object for a given video path.
    r   c              
   C   s  d}t |tr6t|jdkr6t|j}t|  }g }t |ttfrPt	|n|gD ]}tt|
 }d|v r|t	tj|dd qVtj|r|t	ttj|d qVtj|r|| qV|r||  r|t|| 
  qVt| dqVg g  }}	|D ]B}
|
dd	  }|tv rB||
 n|tv r|	|
 qt|t|	 }}||	 | _|| | _|| _d
g| dg|  | _d| _|| _|| _ t!|	r| "|	d  nd| _#| jdkrtd| dt$ dS )zHInitialize the Dataloader and raise FileNotFoundError if file not found.Nz.txt*T)	recursivez*.*z does not exist.r{   Fimager   zNo images or videos found in z. )%
isinstancer   r   suffixparentr8   
splitlineslisttuplesortedabsoluteextendglobr5   r6   isdirru   r7   rW   is_fileFileNotFoundErrorr   lowerr   r	   r:   filesnfni
video_flagr3   r4   r;   any
_new_videorp   r   )r[   r6   batchr4   r   r   par   Zvideosrq   r   r   nvr   r   r   rd     sH    
  





zLoadImagesAndVideos.__init__c                 C   s
   d| _ | S )z:Returns an iterator object for VideoStream or ImageFolder.r   r|   r~   r   r   r   r   >  s    zLoadImagesAndVideos.__iter__c                 C   s  g g g   }}}t || jk r| j| jkr>|r:|||fS t| j| j }| j| j rvd| _| jrn| j	 sx| 
| t| jD ]}| j }|s qq|r4| j \}}|rt|  jd7  _|| || |d| jd  d| j d| j d| j d| d | j| jkrt|  jd7  _| j  n@|  jd7  _| jrT| j  | j| jk r| 
| j| j  qd| _t|}|d	u rtd
|  n:|| || |d| jd  d| j d| d |  jd7  _| j| jkrqq|||fS )zUReturns the next batch of images or video frames along with their paths and metadata.Zvideor   zvideo r&   z (frame z) r'   r   Nu    WARNING ⚠️ Image Read Error zimage  )r:   r;   r}   r   r   r   r   r3   rp   rL   r   r@   r4   rg   rh   r   rW   r=   rv   rJ   Zimreadr   rl   r   )r[   pathsrA   rY   r6   r!   rb   r   r   r   r   r   C  sR    




6




&zLoadImagesAndVideos.__next__c                 C   s\   d| _ t|| _t| jtj| _| j s>t	d| t| jtj
| j | _dS )z6Creates a new video capture object for the given path.r   zFailed to open video N)r   rJ   rK   rp   rN   rO   rP   r<   rL   r   rR   r4   r=   )r[   r6   r   r   r   r   x  s    
zLoadImagesAndVideos._new_videoc                 C   s   t | j| j S )z,Returns the number of batches in the object.)rT   ceilr   r;   r~   r   r   r   r     s    zLoadImagesAndVideos.__len__N)r   r   )	r   r   r   r   rd   r   r   r   r   r   r   r   r   r      s   
,5	r   c                   @   s<   e Zd ZdZdd Zedd Zdd Zdd	 Zd
d Z	dS )LoadPilAndNumpya  
    Load images from PIL and Numpy arrays for batch processing.

    This class is designed to manage loading and pre-processing of image data from both PIL and Numpy formats.
    It performs basic validation and format conversion to ensure that the images are in the required format for
    downstream processing.

    Attributes:
        paths (list): List of image paths or autogenerated filenames.
        im0 (list): List of images stored as Numpy arrays.
        mode (str): Type of data being processed, defaults to 'image'.
        bs (int): Batch size, equivalent to the length of `im0`.

    Methods:
        _single_check(im): Validate and format a single image to a Numpy array.
    c                    sN   t |ts|g}dd t|D  _ fdd|D  _d _t j _dS )z$Initialize PIL and Numpy Dataloader.c                 S   s$   g | ]\}}t |d d| dqS filenamer   z.jpggetattrr    r]   rc   r   r   r   r"     r#   z,LoadPilAndNumpy.__init__.<locals>.<listcomp>c                    s   g | ]}  |qS r   )_single_check)r    rc   r~   r   r   r"     r#   r   N)r   r   rD   r   r   r3   r:   r;   r[   r   r   r~   r   rd     s    
zLoadPilAndNumpy.__init__c                 C   st   t | tjtjfs$J dt|  t | tjrp| jdkrD| d} t| dddddddf } t| } | S )z,Validate and format an image to numpy array.z,Expected PIL/np.ndarray image type, but got RGBNr{   )	r   r   ri   ndarraytyper3   convertr   Zascontiguousarray)rc   r   r   r   r     s    $

"
zLoadPilAndNumpy._single_checkc                 C   s
   t | jS )z*Returns the length of the 'im0' attribute.)r:   r   r~   r   r   r   r     s    zLoadPilAndNumpy.__len__c                 C   s2   | j dkrt|  j d7  _ | j| jdg| j fS )z8Returns batch paths, images, processed images, None, ''.r   r.   r}   r   r   r   r;   r~   r   r   r   r     s    
zLoadPilAndNumpy.__next__c                 C   s
   d| _ | S )z,Enables iteration for class LoadPilAndNumpy.r   r|   r~   r   r   r   r     s    zLoadPilAndNumpy.__iter__N)
r   r   r   r   rd   staticmethodr   r   r   r   r   r   r   r   r     s   	

r   c                   @   sD   e Zd ZdZddddZedddZd	d
 Zdd Zdd Z	dS )
LoadTensoraR  
    Load images from torch.Tensor data.

    This class manages the loading and pre-processing of image data from PyTorch tensors for further processing.

    Attributes:
        im0 (torch.Tensor): The input tensor containing the image(s).
        bs (int): Batch size, inferred from the shape of `im0`.
        mode (str): Current mode, set to 'image'.
        paths (list): List of image paths or filenames.
        count (int): Counter for iteration, initialized at 0 during `__iter__()`.

    Methods:
        _single_check(im, stride): Validate and possibly modify the input tensor.
    N)returnc                 C   s8   |  || _| jjd | _d| _dd t|D | _dS )zInitialize Tensor Dataloader.r   r   c                 S   s$   g | ]\}}t |d d| dqS r   r   r   r   r   r   r"     r#   z'LoadTensor.__init__.<locals>.<listcomp>N)r   r   rB   r;   r3   rD   r   r   r   r   r   rd     s    zLoadTensor.__init__    c                 C   s   d| dt | j d}t| jdkrPt| jdkr<t|t| | d} | jd | sl| jd | rtt||  dt	| j
j krtd	|   d
 |  d } | S )z-Validate and format an image to torch.Tensor.ua   WARNING ⚠️ torch.Tensor inputs should be BCHW i.e. shape(1, 3, 640, 640) divisible by stride z. Input shapez is incompatible.r   r   r      g      ?uQ   WARNING ⚠️ torch.Tensor inputs should be normalized 0.0-1.0 but max value is z. Dividing input by 255.g     o@)r   rB   r:   
ValueErrorr   rl   Z	unsqueezerQ   r/   Zfinforf   ZepsrS   )rc   Zstrider^   r   r   r   r     s&    

zLoadTensor._single_checkc                 C   s
   d| _ | S )zReturns an iterator object.r   r|   r~   r   r   r   r     s    zLoadTensor.__iter__c                 C   s2   | j dkrt|  j d7  _ | j| jdg| j fS )z!Return next item in the iterator.r   r.   r   r~   r   r   r   r     s    
zLoadTensor.__next__c                 C   s   | j S )zReturns the batch size.r   r~   r   r   r   r     s    zLoadTensor.__len__)r   )
r   r   r   r   rd   r   r   r   r   r   r   r   r   r   r     s   r   c              	   C   s   g }| D ]v}t |ttfrJ|tt|dr@tj|ddj	n| qt |tjt
jfrh|| qtdt|j dq|S )zUMerges a list of source of different types into a list of numpy arrays or PIL images.httpT)r   ztype z is not a supported Ultralytics prediction source type. 
See https://docs.ultralytics.com/modes/predict for supported source types.)r   r   r   rW   r   rm   
startswithrequestsrO   rawri   r   	TypeErrorr   r   )r   r   rc   r   r   r   autocast_list  s    0r   pytubec                 C   s|  |dkrvt d ddlm} || jjddd}t|dd	 dd
}|D ]*}|jrFt|jdd dkrF|j  S qFn|dkrt d ddl	}|
| jddjS |dkrxt d ddl}|ddi}|j| dd}W d   n1 s0    Y  t|dg D ]n}	|	dpddkp4|	dp0ddk}
|
r|	d dkr|	d dkr|	d dkr|	d  S qdS )ak  
    Retrieves the URL of the best quality MP4 video stream from a given YouTube video.

    This function uses the specified method to extract the video info from YouTube. It supports the following methods:
    - "pytube": Uses the pytube library to fetch the video streams.
    - "pafy": Uses the pafy library to fetch the video streams.
    - "yt-dlp": Uses the yt-dlp library to fetch the video streams.

    The function then finds the highest quality MP4 format that has a video codec but no audio codec, and returns the
    URL of this video stream.

    Args:
        url (str): The URL of the YouTube video.
        method (str): The method to use for extracting video info. Default is "pytube". Other options are "pafy" and
            "yt-dlp".

    Returns:
        (str): The URL of the best quality MP4 video stream, or None if no suitable stream is found.
    r   zpytubefix>=6.5.2r   )YouTubeZmp4T)Zfile_extensionZ
only_videoc                 S   s   | j S r   )
resolution)r^   r   r   r   <lambda>(  r#   z&get_best_youtube_url.<locals>.<lambda>)keyreverseNr{   i8  pafy)r   zyoutube_dl==2020.12.2)Zpreftypezyt-dlpquietF)downloadformatsr   i  r   ZvcodecnoneZacodecexturl)r   Z	pytubefixr   streamsfilterr   r   rN   r   r   newZgetbestvideoyt_dlpZ	YoutubeDLZextract_inforeversedrO   )r   methodr   r   r   r   r   ZydlZ	info_dictrq   Z	good_sizer   r   r   rF     s*    
,*0rF   )r   )'r   rT   r5   rn   dataclassesr   pathlibr   	threadingr   urllib.parser   rJ   numpyri   r   r/   ZPILr   Zultralytics.data.utilsr   r   r	   Zultralytics.utilsr
   r   r   r   Zultralytics.utils.checksr   r   r   r   r   r   r   r   rF   ZLOADERSr   r   r   r   <module>   s6   	 A 7@
3