
    hW                         d 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	m
Z
mZ ddlZddlZddlZddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZm Z  dd
l!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z( dZ) G d d      Z*y)ar  
Run prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.

Usage - sources:
    $ yolo mode=predict model=yolo11n.pt source=0                               # webcam
                                                img.jpg                         # image
                                                vid.mp4                         # video
                                                screen                          # screenshot
                                                path/                           # directory
                                                list.txt                        # list of images
                                                list.streams                    # list of streams
                                                'path/*.jpg'                    # glob
                                                'https://youtu.be/LNwODJXcvt4'  # YouTube
                                                'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP, TCP stream

Usage - formats:
    $ yolo mode=predict model=yolo11n.pt                 # PyTorch
                              yolo11n.torchscript        # TorchScript
                              yolo11n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True
                              yolo11n_openvino_model     # OpenVINO
                              yolo11n.engine             # TensorRT
                              yolo11n.mlpackage          # CoreML (macOS-only)
                              yolo11n_saved_model        # TensorFlow SavedModel
                              yolo11n.pb                 # TensorFlow GraphDef
                              yolo11n.tflite             # TensorFlow Lite
                              yolo11n_edgetpu.tflite     # TensorFlow Edge TPU
                              yolo11n_paddle_model       # PaddlePaddle
                              yolo11n.mnn                # MNN
                              yolo11n_ncnn_model         # NCNN
                              yolo11n_imx_model          # Sony IMX
                              yolo11n_rknn_model         # Rockchip RKNN
    N)Path)AnyDictListOptionalUnion)get_cfgget_save_dir)load_inference_source)	LetterBox)AutoBackend)DEFAULT_CFGLOGGERMACOSWINDOWS	callbackscolorstrops)check_imgszcheck_imshow)increment_path)select_devicesmart_inference_modea  
inference results will accumulate in RAM unless `stream=True` is passed, causing potential out-of-memory
errors for large sources or long-running streams and videos. See https://docs.ultralytics.com/modes/predict/ for help.

Example:
    results = model(source=..., stream=True)  # generator of Results objects
    for r in results:
        boxes = r.boxes  # Boxes object for bbox outputs
        masks = r.masks  # Masks object for segment masks outputs
        probs = r.probs  # Class probabilities for classification outputs
c            
          e Zd ZdZeddfdeeeef      deeee	e
   f      fdZdeej                  e	ej                      f   dej                  fdZdej                  fd	Zde	ej                      de	ej                      fd
Zd ZddefdZd dZd Z e       d d       Zd!defdZdededej                  de	e   def
dZd"dedefdZd#defdZ defdZ!dede
fdZ"y)$BasePredictora  
    A base class for creating predictors.

    This class provides the foundation for prediction functionality, handling model setup, inference,
    and result processing across various input sources.

    Attributes:
        args (SimpleNamespace): Configuration for the predictor.
        save_dir (Path): Directory to save results.
        done_warmup (bool): Whether the predictor has finished setup.
        model (torch.nn.Module): Model used for prediction.
        data (dict): Data configuration.
        device (torch.device): Device used for prediction.
        dataset (Dataset): Dataset used for prediction.
        vid_writer (Dict[str, cv2.VideoWriter]): Dictionary of {save_path: video_writer} for saving video output.
        plotted_img (np.ndarray): Last plotted image.
        source_type (SimpleNamespace): Type of input source.
        seen (int): Number of images processed.
        windows (List[str]): List of window names for visualization.
        batch (tuple): Current batch data.
        results (List[Any]): Current batch results.
        transforms (callable): Image transforms for classification.
        callbacks (Dict[str, List[callable]]): Callback functions for different events.
        txt_path (Path): Path to save text results.
        _lock (threading.Lock): Lock for thread-safe inference.

    Methods:
        preprocess: Prepare input image before inference.
        inference: Run inference on a given image.
        postprocess: Process raw predictions into structured results.
        predict_cli: Run prediction for command line interface.
        setup_source: Set up input source and inference mode.
        stream_inference: Stream inference on input source.
        setup_model: Initialize and configure the model.
        write_results: Write inference results to files.
        save_predicted_images: Save prediction visualizations.
        show: Display results in a window.
        run_callbacks: Execute registered callbacks for an event.
        add_callback: Register a new callback function.
    N	overrides
_callbacksc                    t        ||      | _        t        | j                        | _        | j                  j                  d| j                  _        d| _        | j                  j                  rt        d      | j                  _        d| _        | j                  j                  | _	        d| _
        d| _        d| _        i | _        d| _        d| _        d| _        g | _        d| _        d| _        d| _        |xs t+        j,                         | _        d| _        t1        j2                         | _        t+        j6                  |        y)a*  
        Initialize the BasePredictor class.

        Args:
            cfg (str | dict): Path to a configuration file or a configuration dictionary.
            overrides (dict, optional): Configuration overrides.
            _callbacks (dict, optional): Dictionary of callback functions.
        Ng      ?FT)warnr   )r	   argsr
   save_dirconfdone_warmupshowr   modeldataimgszdevicedataset
vid_writerplotted_imgsource_typeseenwindowsbatchresults
transformsr   get_default_callbackstxt_path	threadingLock_lockadd_integration_callbacks)selfcfgr   r   s       Z/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/ultralytics/engine/predictor.py__init__zBasePredictor.__init__m   s     C+	$TYY/99>>!!DIIN 99>>)t4DIIN 
IINN	
	
#Hy'F'F'H^^%
++D1    imreturnc                    t        |t        j                         }|r{t        j                  | j                  |            }|j                  d   dk(  r
|ddddf   }|j                  d      }t        j                  |      }t        j                  |      }|j                  | j                        }| j                  j                  r|j                         n|j                         }|r|dz  }|S )a  
        Prepare input image before inference.

        Args:
            im (torch.Tensor | List[np.ndarray]): Images of shape (N, 3, H, W) for tensor, [(H, W, 3) x N] for list.

        Returns:
            (torch.Tensor): Preprocessed image tensor of shape (N, 3, H, W).
           .N)r   rA            )
isinstancetorchTensornpstackpre_transformshape	transposeascontiguousarray
from_numpytor(   r%   fp16halffloat)r8   r=   
not_tensors      r:   
preprocesszBasePredictor.preprocess   s     $B55
$,,R01Bxx|q TrT	]l+B%%b)B!!"%BUU4;;**//RWWYrxxz#IB	r<   c                 \   | j                   j                  rS| j                  j                  s=t	        | j
                  t        | j                  d   d         j                  z  d      nd} | j                  |g|| j                   j                  || j                   j                  d|S )zGRun inference on a given image using the specified model and arguments.r   T)mkdirF)augment	visualizeembed)r    rX   r,   tensorr   r!   r   r/   stemr%   rW   rY   )r8   r=   r    kwargsrX   s        r:   	inferencezBasePredictor.inference   s     yy""D,<,<,C,C 4==4

1a0@+A+F+FFdS 	
 tzz"ufjudii&7&79TXT]T]TcTcuntuur<   c                    t        |D ch c]  }|j                   c}      dk(  }t        | j                  |xr` | j                  j
                  xrH | j                  j                  xs0 t        | j                  dd      xr | j                  j                   | j                  j                        }|D cg c]  } ||       c}S c c}w c c}w )z
        Pre-transform input image before inference.

        Args:
            im (List[np.ndarray]): List of images with shape [(H, W, 3) x N].

        Returns:
            (List[np.ndarray]): List of transformed images.
        rB   dynamicF)autostride)image)lenrK   r   r'   r    rectr%   ptgetattrimxra   )r8   r=   xsame_shapes	letterboxs        r:   rJ   zBasePredictor.pre_transform   s     B/q177/0A5JJ b		b`74::y%#H#_QUQ[Q[Q_Q_M_::$$
	 -//q	"// 0 0s   C9Cc                     |S )z6Post-process predictions for an image and return them. )r8   predsimg	orig_imgss       r:   postprocesszBasePredictor.postprocess   s    r<   streamc                     || _         |r | j                  ||g|i |S t         | j                  ||g|i |      S )a  
        Perform inference on an image or stream.

        Args:
            source (str | Path | List[str] | List[Path] | List[np.ndarray] | np.ndarray | torch.Tensor, optional):
                Source for inference.
            model (str | Path | torch.nn.Module, optional): Model for inference.
            stream (bool): Whether to stream the inference results. If True, returns a generator.
            *args (Any): Additional arguments for the inference method.
            **kwargs (Any): Additional keyword arguments for the inference method.

        Returns:
            (List[ultralytics.engine.results.Results] | generator): Results objects or generator of Results objects.
        )rq   stream_inferencelist)r8   sourcer%   rq   r    r\   s         r:   __call__zBasePredictor.__call__   sR     (4((HHHH---feMdMfMNNr<   c                 6    | j                  ||      }|D ]  } y)aD  
        Method used for Command Line Interface (CLI) prediction.

        This function is designed to run predictions using the CLI. It sets up the source and model, then processes
        the inputs in a streaming manner. This method ensures that no outputs accumulate in memory by consuming the
        generator without storing results.

        Args:
            source (str | Path | List[str] | List[Path] | List[np.ndarray] | np.ndarray | torch.Tensor, optional):
                Source for inference.
            model (str | Path | torch.nn.Module, optional): Model for inference.

        Note:
            Do not modify this function or remove the generator. The generator ensures that no outputs are
            accumulated in memory, which is critical for preventing memory issues during long-running predictions.
        N)rs   )r8   ru   r%   gen_s        r:   predict_clizBasePredictor.predict_cli   s(    " ##FE2 	A	r<   c                    t        | j                  j                  | j                  j                  d      | _        t        || j                  j                  | j                  j                  | j                  j                  t        | j                  dd            | _
        | j                  j                  | _        t        | dd      s~| j                  j                  sO| j                  j                  s9t        | j                        dkD  s!t        t        | j                  d	d
g            rt!        j"                  t$               i | _        y)z
        Set up source and inference mode.

        Args:
            source (str | Path | List[str] | List[Path] | List[np.ndarray] | np.ndarray | torch.Tensor):
                Source for inference.
        rC   )ra   min_dimchrA   )ru   r/   
vid_stridebufferchannelsrq   Ti  
video_flagFN)r   r    r'   r%   ra   r   r/   r~   stream_bufferrf   r)   r,   rq   
screenshotrc   anyr   warningSTREAM_WARNINGr*   )r8   ru   s     r:   setup_sourcezBasePredictor.setup_source   s     !9J9JTUV
,))//yy++99**TZZq1
  <<33tXt,##**4<< 4'74<<w?@NN>*r<   c              /   r   K    j                   j                  rt        j                  d        j                  s j                  |        j                  5   j                  ||n j                   j                          j                   j                  s j                   j                  rB j                   j                  r j                  dz  n j                  j                  dd        j                  s j                  j                   j                  j                  s j                  j                   rdn j"                  j$                   j                  j&                  g j(                         d _        dg dc _         _         _        t1        j2                   j4                  	      t1        j2                   j4                  	      t1        j2                   j4                  	      f} j7                  d
        j"                  D ]Q   _         j7                  d        j.                  \  }}}|d   5   j9                  |      }	ddd       |d   5    j:                  	g|i |}
 j                   j<                  r1t?        |
t@        jB                        r|
gn|
E d{    	 ddd       	 ddd       |d   5   jE                  
	|       _#        ddd        j7                  d       tI        |      }	 tK        |      D ]  } xj*                  dz  c_        |d   jL                  dz  |z  |d   jL                  dz  |z  |d   jL                  dz  |z  d jF                  |   _'         j                   j                  sC j                   j                  s- j                   j                  s j                   jP                  s||xx    jS                  |tU        ||         	|      z  cc<    	  j                   j                  r$t        j                  djY                  |              j7                  d        jF                  E d{    T ddd        jZ                  j]                         D ]-  }t?        |t^        j`                        s|jc                          /  j                   jP                  rt_        jd                           j                   j                  r j*                  r~tg         fdD              }t        j                  dti         j                   j.                   j*                        tk         j                  dd      g	jl                  dd  |z          j                   j                  s, j                   j                  s j                   jn                  rtI        tq         j                  js                  d                  } j                   j                  rd| dd|dkD  z   d j                  dz   nd}t        j                  dtu        d j                         |         j7                  d       y# 1 sw Y   xY w7 # 1 sw Y   xY w# 1 sw Y   xY w# tV        $ r Y  8w xY w7 D# 1 sw Y   AxY ww)a=  
        Stream real-time inference on camera feed and save results to file.

        Args:
            source (str | Path | List[str] | List[Path] | List[np.ndarray] | np.ndarray | torch.Tensor, optional):
                Source for inference.
            model (str | Path | torch.nn.Module, optional): Model for inference.
            *args (Any): Additional arguments for the inference method.
            **kwargs (Any): Additional keyword arguments for the inference method.

        Yields:
            (ultralytics.engine.results.Results): Results objects.
         NlabelsTparentsexist_okrB   )r'   r   )r(   on_predict_starton_predict_batch_startrC   on_predict_postprocess_end     @@)rT   r]   rp   
on_predict_batch_endc              3   V   K   | ]   }|j                   j                  z  d z   " yw)r   N)tr-   ).0rh   r8   s     r:   	<genexpr>z1BasePredictor.stream_inference.<locals>.<genexpr>t  s"     ?accDIIo+?s   &)zRSpeed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape r}   rA   zlabels/*.txtz labelsz
 saved to zResults saved to boldon_predict_end);r    verboser   infor%   setup_modelr6   r   ru   savesave_txtr!   rV   r#   warmupre   tritonr)   bsr}   r'   r-   r.   r/   r   Profiler(   run_callbacksrT   r]   rY   rE   rF   rG   rp   r0   rc   rangedtspeedr$   write_resultsr   StopIterationjoinr*   valuescv2VideoWriterreleasedestroyAllWindowstupleminrf   rK   	save_croprt   globr   )r8   ru   r%   r    r\   	profilerspathsim0sr   r=   rm   nivr   nls   `               r:   rs   zBasePredictor.stream_inference  s^     99KKO zzU#ZZ >	((:f		@P@PQ yy~~!3!3-1YY-?-?)T]]YYbfquYv ##

!! $

1B1B1Y]YcYcYfYftimisist "  $( 23R/DIt|TZ4;;/4;;/4;;/I
 12"ll ((
""#;<!%tQ q\ /.B/ q\ !*DNN2???Eyy.8.ME7SXXX 	! !&! q\ E#'#3#3E2t#DDLE""#?@ I"1X Q		Q	*3A,//C*?!*C)213)>)B+4Q<??S+@1+D1Q-
  99,,		$))BTBTX\XaXaXfXfaDD$6$6q$uQx."a$PPDQ 99$$KK		!-""#9:<<''Q((->	(B '') 	A!S__-			 99>>!!# 99?Y??AKKd		3WTZZq5QaTVT\T\]^]_T`abdfgh 99>>TYY//4993F3FT$--,,^<=>BW[W`W`WiWi"RDsb1f~.j9Q8RSoqAKK+HVT]],K+LQCPQ+,q/ / Y! !E E  %  (}>	( >	(s   AZ7G-Z*Y,Z*$AY<3Y9
4Y<9	Z*Z*Z	)$Z*CZ-ZAZ*#Z'$Z*+?Z7+GZ7,Y61Z*9Y<<ZZ*	ZZ*	Z$Z*#Z$$Z**Z4/Z7r   c           	      p   t        |xs | j                  j                  t        | j                  j                  |      | j                  j
                  | j                  j                  | j                  j                  d|      | _        | j                  j                  | _        | j                  j                  | j                  _        t        | j                  d      r<t        | j                  dd      s%| j                  j                  | j                  _        | j                  j                          y)z
        Initialize YOLO model with given parameters and set it to evaluation mode.

        Args:
            model (str | Path | torch.nn.Module, optional): Model to load or use.
            verbose (bool): Whether to print verbose output.
        )r   T)weightsr(   dnnr&   rP   fuser   r'   r_   FN)r   r    r%   r   r(   r   r&   rQ   rP   hasattrrf   r'   eval)r8   r%   r   s      r:   r   zBasePredictor.setup_model  s     !,TYY__ !1!17C		

 jj''		4::w'

Iu0U"jj..DIIO

r<   r   pr   c                 0   d}t        |j                        dk(  r|d   }| j                  j                  s,| j                  j                  s| j                  j
                  r|| dz  }| j                  j                  }n+t        j                  d||         }|rt        |d         nd}| j                  dz  |j                  | j                  j                  dk(  rdnd	| z   z  | _        | d
j                  |j                  dd  z  }| j                   |   }| j                  j#                         |_        ||j%                          |j&                  d   ddz  }| j(                  j*                  s| j(                  j,                  r|j/                  | j(                  j0                  | j(                  j2                  | j(                  j4                  | j(                  j6                  | j(                  j8                  rdn||         | _        | j(                  j<                  r4|j=                  | j                   d| j(                  j>                         | j(                  j@                  r4|jA                  | j                  dz  | j                  j                         | j(                  j,                  r| j-                  tC        |             | j(                  j*                  r)| jE                  | j                  |jF                  z  |       |S )aq  
        Write inference results to a file or directory.

        Args:
            i (int): Index of the current image in the batch.
            p (Path): Path to the current image.
            im (torch.Tensor): Preprocessed image tensor.
            s (List[str]): List of result strings.

        Returns:
            (str): String with result information.
        r   rA   Nz: zframe (\d+)/rB   r   rb   ry   z
{:g}x{:g} rC   r]   z.1fms)
line_widthboxesr"   r   im_gpuz.txt)	save_confcrops)r!   	file_name)$rc   rK   r,   rq   from_imgrZ   r)   countresearchintr!   r[   moder3   formatr0   __str__r   r   r    r   r$   plotr   
show_boxes	show_confshow_labelsretina_masksr+   r   r   r   strsave_predicted_imagesname)	r8   r   r   r=   r   stringframematchresults	            r:   r   zBasePredictor.write_results  s^    rxx=ADB""d&6&6&?&?4CSCSCZCZ2hFLL&&EIIoqt4E%*CaME0AFFDLLDUDUY`D`bhijoipfq4rs%,%%rxx|44a--//1V^^%&v||K'@&ERHH 99>>TYY^^%{{99//ii**YY((yy,,#yy55t2a5  +  D 99OOt}}oT2dii>Q>QOR99dmmg&=I[I[\99>>IIc!f99>>&&t}}qvv'=uEr<   	save_pathr   c                    | j                   }| j                  j                  dv rt| j                  j                  dk(  r| j                  j                  nd}| j                  |j
                   dz  }|| j                  vr| j                  j                  rt        |      j                  dd       t        rdn	t        rdnd	\  }}t        j                  t        t        |      j!                  |            t        j"                  | ||j$                  d
   |j$                  d   f      | j                  |<   | j                  |   j'                  |       | j                  j                  r*t        j(                  | d|j
                   d| d|       yyt        j(                  t        |j!                  d            |       y)z
        Save video predictions as mp4 or images as jpg at specified path.

        Args:
            save_path (Path): Path to save the results.
            frame (int): Frame number for video mode.
        >   videorq   r      _framesTr   )z.mp4avc1).aviWMV2)r   MJPGrB   r   )filenamefourccfps	frameSize/ry   z.jpgN)r+   r)   r   r   r!   r[   r*   r    save_framesr   rV   r   r   r   r   r   with_suffixVideoWriter_fourccrK   writeimwrite)r8   r   r   r=   r   frames_pathsuffixr   s           r:   r   z#BasePredictor.save_predicted_images  sn     << 33&*ll&7&77&B$,,""C--Y^^,<G*DDK/99((%++D4+H5:!1T[@Paq-0__ i!<!<V!DE116:!xx{BHHQK8	.	* OOI&,,R0yy$${m1Y^^,<AeWDI2N %
 KKI11&9:B?r<   c                    | j                   }t        j                         dk(  r|| j                  vr| j                  j	                  |       t        j                  |t
        j                  t
        j                  z         t        j                  ||j                  d   |j                  d          t        j                  ||       t        j                  | j                  j                  dk(  rdnd      dz  t        d      k(  rt         y)	zDisplay an image in a window.LinuxrB   r   rb   i,  rD   qN)r+   platformsystemr.   appendr   namedWindowWINDOW_NORMALWINDOW_KEEPRATIOresizeWindowrK   imshowwaitKeyr)   r   ordr   )r8   r   r=   s      r:   r$   zBasePredictor.show  s    ??'AT\\,ALL"OOAs0033G3GGHQRXXa[9

1b;;dll//7:sBTISQTXU Vr<   eventc                 V    | j                   j                  |g       D ]
  } ||         y)z2Run all registered callbacks for a specific event.N)r   get)r8   r   callbacks      r:   r   zBasePredictor.run_callbacks  s)    **5"5 	HTN	r<   funcc                 @    | j                   |   j                  |       y)z-Add a callback function for a specific event.N)r   r   )r8   r   r  s      r:   add_callbackzBasePredictor.add_callback  s    u$$T*r<   )NNF)NN)T)r   )r   )#__name__
__module____qualname____doc__r   r   r   r   r   r   callabler;   r   rF   rG   rH   ndarrayrT   r]   rJ   rp   boolrv   rz   r   r   rs   r   r   r   r   r   r$   r   r  rl   r<   r:   r   r   C   si   'V .2:>	'2 DcN+'2 T#tH~"567	'2RU5<<bjj1A#AB u|| 2vELL v0RZZ 0 0T"**5E 0(O O**4 h- h-T$ 01s 1t 1 1$s) 1PS 1f @t  @C  @D	 c 	 3 
+# +X +r<   r   )+r
  r   r   r4   pathlibr   typingr   r   r   r   r   r   numpyrH   rF   ultralytics.cfgr	   r
   ultralytics.datar   ultralytics.data.augmentr   ultralytics.nn.autobackendr   ultralytics.utilsr   r   r   r   r   r   r   ultralytics.utils.checksr   r   ultralytics.utils.filesr   ultralytics.utils.torch_utilsr   r   r   r   rl   r<   r:   <module>r     sY   B  	   3 3 
   1 2 . 2 [ [ [ > 2 M
{+ {+r<   