
    FPhK                         d dl Z d dlZd dlmZ d dlmZ d dlmZmZm	Z	 d dl
mZ d dlmZ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  G d	 d
ej8                        Zy)    N)Path)Union)	TASK2DATAget_cfgget_save_dir)HUB_WEB_ROOT)attempt_load_one_weightguess_model_tasknnyaml_model_load)ASSETSDEFAULT_CFG_DICTLOGGERRANK	callbackschecksemojis	yaml_load)GITHUB_ASSETS_STEMSc                   P    e Zd ZdZd$deeef   ddf fdZd%dZe	d        Z
e	d        Zd&d	efd
Zd'defdZd Zd Zd(dZd)dZd Zd*dZd+dZd'dZd Zd Zd'dZd,dZ fdZed        Zed        Zed        ZdefdZdefdZ d  Z!e	d!        Z"d" Z#ed#        Z$ xZ%S )-Modelao  
    A base class to unify APIs for all models.

    Args:
        model (str, Path): Path to the model file to load or create.
        task (Any, optional): Task type for the YOLO model. Defaults to None.

    Attributes:
        predictor (Any): The predictor object.
        model (Any): The model object.
        trainer (Any): The trainer object.
        task (str): The type of model task.
        ckpt (Any): The checkpoint object if the model loaded from *.pt file.
        cfg (str): The model configuration if loaded from *.yaml file.
        ckpt_path (str): The checkpoint file path.
        overrides (dict): Overrides for the trainer object.
        metrics (Any): The data for metrics.

    Methods:
        __call__(source=None, stream=False, **kwargs):
            Alias for the predict method.
        _new(cfg:str, verbose:bool=True) -> None:
            Initializes a new model and infers the task type from the model definitions.
        _load(weights:str, task:str='') -> None:
            Initializes a new model and infers the task type from the model head.
        _check_is_pytorch_model() -> None:
            Raises TypeError if the model is not a PyTorch model.
        reset() -> None:
            Resets the model modules.
        info(verbose:bool=False) -> None:
            Logs the model info.
        fuse() -> None:
            Fuses the model for faster inference.
        predict(source=None, stream=False, **kwargs) -> List[ultralytics.engine.results.Results]:
            Performs prediction using the YOLO model.

    Returns:
        list(ultralytics.engine.results.Results): The prediction results.
    Nmodelreturnc                    t         |           t        j                         | _        d| _        d| _        d| _        d| _        d| _        d| _	        i | _
        d| _        d| _        || _        t        |      j                         }| j!                  |      r*ddlm}  ||      | _        | j                  j&                  }n | j)                  |      r|| _        || _        yt+        |      j,                  }|s7t+        |      j.                  t0        v rt+        |      j3                  d      d}}|dv r| j5                  ||       y| j7                  ||       y)a  
        Initializes the YOLO model.

        Args:
            model (Union[str, Path], optional): Path or name of the model to load or create. Defaults to 'yolov8n.pt'.
            task (Any, optional): Task type for the YOLO model. Defaults to None.
        Nr   )HUBTrainingSession.pt)z.yamlz.yml)super__init__r   get_default_callbacks	predictorr   trainerckptcfg	ckpt_path	overridesmetricssessiontaskstrstripis_hub_modelultralytics.hub.sessionr   
model_fileis_triton_modelr   suffixstemr   with_suffix_new_load)selfr   r(   r   r/   	__class__s        cC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/engine/model.pyr   zModel.__init__8   s*    	"88:
		E
  " U#B-e4DLLL++E !!%(DJDI e##$u+**.AA K33E:E6E&&IIeT"JJud#    c                 *     | j                   ||fi |S )zNCalls the 'predict' function with given arguments to perform object detection.)predict)r4   sourcestreamkwargss       r6   __call__zModel.__call__c   s    t||FF5f55r7   c                 r    ddl m}  ||       }|j                  xr |j                  xr |j                  dv S )zTIs model a Triton Server URL string, i.e. <scheme>://<netloc>/<endpoint>/<task_name>r   )urlsplit>   grfchttp)urllib.parser?   netlocpathscheme)r   r?   urls      r6   r.   zModel.is_triton_modelg   s2     	*uozzIchhI3::9I+IIr7   c           	      (    t         j                  t         d       j                  d      D cg c]  }t	        |       c}ddgk(  t	               dk(  xr0 t               j                          xr t         fddD              f      S c c}w )z+Check if the provided model is a HUB model.z/models/_*      c              3   &   K   | ]  }|v 
 y wN ).0xr   s     r6   	<genexpr>z%Model.is_hub_model.<locals>.<genexpr>t   s     AaZ`UV!5.Z`s   z./\)any
startswithr   splitlenr   existsall)r   rO   s   ` r6   r+   zModel.is_hub_modeln   s     ~X67"[[-.-SV-.2r(:J"aT%[%7%7%9!9acAaZ`Aa>ac d 	d.s   B
r#   c                    t        |      }|| _        |xs t        |      | _         |xs | j	                  d      ||xr	 t
        dk(        | _        | j                  | j                  d<   | j                  | j                  d<   i t        | j                  | j                  _	        | j                  | j                  _        y)a/  
        Initializes a new model and infers the task type from the model definitions.

        Args:
            cfg (str): model configuration file
            task (str | None): model task
            model (BaseModel): Customized model.
            verbose (bool): display model info on load
        r   )verboser(   N)
r   r#   r
   r(   _smart_loadr   r   r%   r   args)r4   r#   r(   r   rY   cfg_dicts         r6   r2   z
Model._newv   s     #3'6,X6	8e8t//8(GLbX\`bXbc
"&((w!%v A-@@

))

r7   weightsc                     t        |      j                  }|dk(  rt        |      \  | _        | _        | j                  j
                  d   | _        | j                  | j                  j
                        x| _        | j                  _        | j                  j                  | _
        n?t        j                  |      }|dc| _        | _        |xs t        |      | _        || _
        || j                  d<   | j                  | j                  d<   y)z
        Initializes a new model and infers the task type from the model head.

        Args:
            weights (str): model checkpoint to be loaded
            task (str | None): model task
        r   r(   Nr   )r   r/   r	   r   r"   r[   r(   _reset_ckpt_argsr%   pt_pathr$   r   
check_filer
   )r4   r]   r(   r/   s       r6   r3   zModel._load   s     g%%U?$;G$D!DJ	

/DI/3/D/DTZZ__/UUDNTZZ_!ZZ//DN''0G$+T!DJ	9 0 9DI$DN")w!%vr7   c                    t        | j                  t        t        f      xr" t        | j                        j                  dk(  }t        | j                  t
        j                        }|s|st        d| j                   d      yy)z1Raises TypeError is model is not a PyTorch model.r   zmodel='a  ' should be a *.pt PyTorch model to run this method, but is a different format. PyTorch models can train, val, predict and export, i.e. 'model.train(data=...)', but exported formats like ONNX, TensorRT etc. only support 'predict' and 'val' modes, i.e. 'yolo predict model=yolov8n.onnx'.
To run CUDA or MPS inference please pass the device argument directly in your inference command, i.e. 'model.predict(source=..., device=0)'N)
isinstancer   r)   r   r/   r   Module	TypeError)r4   pt_str	pt_modules      r6   _check_is_pytorch_modelzModel._check_is_pytorch_model   sv    DJJd4Ydjj9I9P9PTY9Ytzz2995	V$** &j kl l $	r7   c                     | j                          | j                  j                         D ]  }t        |d      s|j	                          ! | j                  j                         D ]	  }d|_         | S )zdResets the model modules parameters to randomly initialized values, losing all training information.reset_parametersT)rh   r   moduleshasattrrj   
parametersrequires_grad)r4   mps      r6   reset_weightszModel.reset_weights   sa    $$&##%Aq,-""$ & &&(A"AO )r7   c                     | j                          t        |t        t        f      rt	        |      \  }| _        | j                  j                  |       | S )zLTransfers parameters with matching names and shapes from 'weights' to model.)rh   rc   r)   r   r	   r"   r   load)r4   r]   s     r6   rs   z
Model.load   sB    $$&gT{+!8!AGTY

 r7   c                 \    | j                          | j                  j                  ||      S )z
        Logs model info.

        Args:
            detailed (bool): Show detailed information about model.
            verbose (bool): Controls verbosity.
        )detailedrY   )rh   r   info)r4   ru   rY   s      r6   rv   z
Model.info   s'     	$$&zz'BBr7   c                 X    | j                          | j                  j                          y)z+Fuse PyTorch Conv2d and BatchNorm2d layers.N)rh   r   fuser4   s    r6   rx   z
Model.fuse   s    $$&

r7   c                    |t         }t        j                  d| d       t        j                  d   j                  d      xs" t        j                  d   j                  d      xr t        d dD              }d	|d
}i | j                  ||ddi}|j                  dd      }| j                  sT |xs | j                  d      || j                        | _	        | j                  j                  | j                  |       net        | j                  j                  |      | j                  _        d|v sd|v r.t!        | j                  j                        | j                  _        |r1t%        | j                  d      r| j                  j'                  |       |r| j                  j)                  |      S | j                  ||      S )a  
        Perform prediction using the YOLO model.

        Args:
            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.
                Accepts all source types accepted by the YOLO model.
            stream (bool): Whether to stream the predictions or not. Defaults to False.
            predictor (BasePredictor): Customized predictor.
            **kwargs : Additional keyword arguments passed to the predictor.
                Check the 'configuration' section in the documentation for all available options.

        Returns:
            (List[ultralytics.engine.results.Results]): The prediction results.
        Nu2   WARNING ⚠️ 'source' is missing. Using 'source=z'.r   yoloultralyticsc              3   @   K   | ]  }|t         j                  v   y wrL   )sysargv)rN   rO   s     r6   rP   z Model.predict.<locals>.<genexpr>   s      _W#UaAM#Us   )r9   trackzmode=predictz
mode=trackg      ?)confsavemoder9   promptsr    r%   
_callbacks)r   rY   projectnameset_prompts)r:   r:   r;   )r   r   warningr~   r   endswithrQ   r%   popr    rZ   r   setup_modelr   r   r[   r   save_dirrl   r   predict_cli)	r4   r:   r;   r    r<   is_clicustomr[   r   s	            r6   r9   zModel.predict   s    >FNNOPVxWYZ[((1+&&v.U#((1+2F2F}2U W[^ _W#U_W \W /H$..HFHfHfiH((9d+~~HiH4+;+;K+HTXeiesestDNNN&&TZZ&H")$..*=*=t"DDNND FdN*6t~~7J7J*K'wt~~}=NN&&w/<Bt~~)))8t^dmsHttr7   c                     t        | j                  d      sddlm}  || |       |j	                  d      xs d|d<   d|d<    | j
                  d	||d|S )
ag  
        Perform object tracking on the input source using the registered trackers.

        Args:
            source (str, optional): The input source for object tracking. Can be a file path or a video stream.
            stream (bool, optional): Whether the input source is a video stream. Defaults to False.
            persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.
            **kwargs (optional): Additional keyword arguments for the tracking process.

        Returns:
            (List[ultralytics.engine.results.Results]): The tracking results.
        trackersr   )register_trackerr   g?r   r   r   rM   )rl   r    ultralytics.trackersr   getr9   )r4   r:   r;   persistr<   r   s         r6   r   zModel.track   sZ     t~~z2=T7+F+2sv vt||C6&CFCCr7   c                     ddi}i | j                   ||ddi} |xs | j                  d      || j                        } || j                         |j                  | _        |j                  S )z
        Validate a model on a given dataset.

        Args:
            validator (BaseValidator): Customized validator.
            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
        rectTr   val	validatorr[   r   r   )r%   rZ   r   r   r&   )r4   r   r<   r   r[   s        r6   r   z	Model.val  sv     $D$..DFDfDfeD?Y?$"2"2;"?dW[WeWef	

# ((   r7   c                     | j                          ddlm} ddi}i t        | j                  j
                  ||ddi} || |j                  d      |d   |d	   |d
   |d   |j                  d            S )z
        Benchmark a model on all export formats.

        Args:
            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
        r   )	benchmarkrY   Fr   r   dataimgszhalfint8device)r   r   r   r   r   r   rY   )rh   ultralytics.utils.benchmarksr   r   r   r[   r   )r4   r<   r   r   r[   s        r6   r   zModel.benchmark  s     	$$&:U#_"_djjoo__6_6S^_F#w-ff>JJy)+ 	+r7   c                     | j                          ddlm} | j                  j                  d   dddd}i | j
                  ||ddi}  ||| j                  	      | j                  
      S )z
        Export model.

        Args:
            **kwargs : Any other args accepted by the Exporter. To see all args check 'configuration' section in docs.
           )Exporterr   NF)r   batchr   rY   r   exportr   r   )rh   exporterr   r   r[   r%   r   )r4   r<   r   r   r[   s        r6   r   zModel.export-  sj     	$$&&::??73aZ_`G$..GFGfGfhGBx$4>>BTTr7   c                    | j                          | j                  r6t        |      rt        j                  d       | j                  j
                  }t        j                          |j                  d      r!t        t        j                  |d               n| j                  }dt        | j                     i}i |||ddi}|j                  d      r| j                  |d<    |xs | j                  d      || j                         | _        |j                  d      ss| j"                  j%                  | j&                  r| j(                  nd	| j(                  j*                  
      | j"                  _        | j"                  j(                  | _        | j                  | j"                  _        | j"                  j/                          t0        dv r| j"                  j2                  j5                         r| j"                  j2                  n| j"                  j6                  }t9        |      \  | _        }| j(                  j:                  | _        t=        | j"                  j>                  dd	      | _         | j@                  S )z
        Trains the model on a given dataset.

        Args:
            trainer (BaseTrainer, optional): Customized trainer.
            **kwargs (Any): Any number of arguments representing the training configuration.
        uO   WARNING ⚠️ using HUB training arguments, ignoring local training arguments.r#   r   r   trainresumer!   r   N)r]   r#   )rX   r   r&   )!rh   r'   rQ   r   r   
train_argsr   check_pip_update_availabler   r   
check_yamlr%   r   r(   r$   rZ   r   r!   	get_modelr"   r   yamlhub_sessionr   r   bestrU   lastr	   r[   getattrr   r&   )r4   r!   r<   r%   r   r[   r"   rH   s           r6   r   zModel.train;  s    	$$&<<6{pq\\,,F))+CI::eCTIf//u>?Z^ZhZh	)DII./A)AvAAA88H!^^DN>>4#3#3I#>$[_[i[ijxx!!%!7!7dii

]agkgqgqgvgv!7!wDLL++DJ#'<< 7?(,(9(9(@(@(B4<<$$HYHYD3D9MDJ!ZZ__DN"4<<#9#99dKDL||r7   c                     | j                          |rddlm}  || g|d|i|S ddlm} i }i | j
                  ||ddi}  ||| j                        | |	      S )
z
        Runs hyperparameter tuning, optionally using Ray Tune. See ultralytics.utils.tuner.run_ray_tune for Args.

        Returns:
            (dict): A dictionary containing the results of the hyperparameter search.
        r   )run_ray_tunemax_samplesr   )Tunerr   r   r   )r   
iterations)rh   ultralytics.utils.tunerr   tunerr   r%   r   )r4   use_rayr   r[   r<   r   r   r   s           r6   tunez
Model.tune^  sr     	$$&<NtN*NvNN$FJdnnJJ&J&'JD>5dt~~>TV`aar7   c                     | j                          t        | 	  |      } d| _        | j                  | j
                  d<   | S )zjApply to(), cpu(), cuda(), half(), float() to model tensors that are not parameters or registered buffers.Nr   )rh   r   _applyr    r   r%   )r4   fnr5   s     r6   r   zModel._applyp  s;    $$&w~b!#';;x r7   c                 ^    t        | j                  d      r| j                  j                  S dS )z(Returns class names of the loaded model.namesN)rl   r   r   ry   s    r6   r   zModel.namesx  s&     $+4::w#?tzzITIr7   c                     t        | j                  t        j                        r-t	        | j                  j                               j                  S dS )z Returns device if PyTorch model.N)rc   r   r   rd   nextrm   r   ry   s    r6   r   zModel.device}  s:     8B$**bii7XtDJJ))+,33b^bbr7   c                 ^    t        | j                  d      r| j                  j                  S dS )z&Returns transform of the loaded model.
transformsN)rl   r   r   ry   s    r6   r   zModel.transforms  s&     )0

L(Itzz$$StSr7   eventc                 @    | j                   |   j                  |       y)zAdd a callback.N)r   append)r4   r   funcs      r6   add_callbackzModel.add_callback  s    u$$T*r7   c                 "    g | j                   |<   y)zClear all event callbacks.N)r   r4   r   s     r6   clear_callbackzModel.clear_callback  s     "ur7   c                     t         j                  j                         D ]&  }t         j                  |   d   g| j                   |<   ( y)zReset all registered callbacks.r   N)r   default_callbackskeysr   s     r6   reset_callbackszModel.reset_callbacks  s<    00557E%.%@%@%G%J$KDNN5! 8r7   c                 h    h d}| j                         D ci c]  \  }}||v s|| c}}S c c}}w )z-Reset arguments when loading a PyTorch model.>   r   r(   r   
single_cls)items)r[   includekvs       r6   r_   zModel._reset_ckpt_args  s5     :!%>Ag1>>>s   ..c                    	 | j                   | j                     |   S # t        $ r^}| j                  j                  }t        j                         d   d   }t        t        d| d| d| j                   d            |d}~ww xY w)z'Load model/trainer/validator/predictor.r      u   WARNING ⚠️ 'z' model does not support 'z' mode for 'z' task yet.N)	task_mapr(   	Exceptionr5   __name__inspectstackNotImplementedErrorr   )r4   keyer   r   s        r6   rZ   zModel._smart_load  s    	|==+C00 	|>>**D==?1%a(D%)$/I$|\`\e\e[ffqrsuz{|	|s    	BAB  Bc                     t        d      )z
        Map head to model, trainer, validator, and predictor classes.

        Returns:
            task_map (dict): The map of model task to mode classes.
        z'Please provide task map for your model!)r   ry   s    r6   r   zModel.task_map  s     ""KLLr7   )
yolov8n.ptN)NF)NNTrL   )r   )FT)NFN)NFF)F
   )&r   
__module____qualname____doc__r   r)   r   r   r=   staticmethodr.   r+   r2   r3   rh   rq   rs   rv   rx   r9   r   r   r   r   r   r   r   propertyr   r   r   r   r   r   r_   rZ   r   __classcell__)r5   s   @r6   r   r      sH   &P)$eCI. )$T )$V6 J J d d$ $*+S +,
l	C
#uJD(! +*U!Fb$ J J c c T T+# +#C #L
 ? ?| M Mr7   r   )r   r~   pathlibr   typingr   ultralytics.cfgr   r   r   ultralytics.hub.utilsr   ultralytics.nn.tasksr	   r
   r   r   ultralytics.utilsr   r   r   r   r   r   r   r   ultralytics.utils.downloadsr   rd   r   rM   r7   r6   <module>r      sB     
   < < . _ _ j j j ;bMBII bMr7   