o
    Wh8                     @   s   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	m
Z
mZmZmZmZmZmZ d dlmZmZ G dd deZG d	d
 d
eZG dd deZdS )    )Path)load_inference_source)Model)yolo)ClassificationModelDetectionModelOBBModel	PoseModelSegmentationModel
WorldModel
YOLOEModelYOLOESegModel)ROOT	yaml_loadc                       s.   e Zd ZdZd	 fdd	Zedd Z  ZS )
YOLOz1YOLO (You Only Look Once) object detection model.
yolo11n.ptNFc                    s   t |}d|jv r|jdv rt||d}t|| _|j| _dS d|jv r;|jdv r;t|||d}t|| _|j| _dS t j	|||d dS )ao  
        Initialize a YOLO model.

        This constructor initializes a YOLO model, automatically switching to specialized model types
        (YOLOWorld or YOLOE) based on the model filename.

        Args:
            model (str | Path): Model name or path to model file, i.e. 'yolo11n.pt', 'yolov8n.yaml'.
            task (str | None): YOLO task specification, i.e. 'detect', 'segment', 'classify', 'pose', 'obb'.
                Defaults to auto-detection based on model.
            verbose (bool): Display model info on load.

        Examples:
            >>> from ultralytics import YOLO
            >>> model = YOLO("yolov8n.pt")  # load a pretrained YOLOv8n detection model
            >>> model = YOLO("yolov8n-seg.pt")  # load a pretrained YOLOv8n segmentation model
            >>> model = YOLO("yolo11n.pt")  # load a pretrained YOLOv11n detection model
        z-world>   .pt.yml.yaml)verboseyoloe)taskr   modelr   r   N)
r   stemsuffix	YOLOWorldtype	__class____dict__YOLOEsuper__init__)selfr   r   r   pathnew_instancer    Q/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/yolo/model.pyr"      s   

zYOLO.__init__c              	   C   s~   t tjjtjjtjjdttjjtjj	tjj
dttjjtjjtjjdttjjtjjtjjdttjjtjjtjjddS )z=Map head to model, trainer, validator, and predictor classes.)r   trainer	validator	predictor)classifydetectsegmentposeobb)r   r   r,   ClassificationTrainerClassificationValidatorClassificationPredictorr   r-   DetectionTrainerDetectionValidatorDetectionPredictorr
   r.   SegmentationTrainerSegmentationValidatorSegmentationPredictorr	   r/   PoseTrainerPoseValidatorPosePredictorr   r0   
OBBTrainerOBBValidatorOBBPredictorr#   r'   r'   r(   task_map8   s4   zYOLO.task_map)r   NF)__name__
__module____qualname____doc__r"   propertyrA   __classcell__r'   r'   r&   r(   r      s
     r   c                       s8   e Zd ZdZdd fddZedd	 Zd
d Z  ZS )r   z"YOLO-World object detection model.yolov8s-world.ptFreturnNc                    s<   t  j|d|d t| jdsttd d| j_dS dS )a  
        Initialize YOLOv8-World model with a pre-trained model file.

        Loads a YOLOv8-World model for object detection. If no custom class names are provided, it assigns default
        COCO class names.

        Args:
            model (str | Path): Path to the pre-trained model file. Supports *.pt and *.yaml formats.
            verbose (bool): If True, prints additional information during initialization.
        r-   r   namescfg/datasets/coco8.yamlNr!   r"   hasattrr   r   r   getrJ   )r#   r   r   r&   r'   r(   r"   `   s   zYOLOWorld.__init__c                 C   s   dt tjjtjjtjjdiS )4Map head to model, validator, and predictor classes.r-   r   r*   r+   r)   )r   r   r-   r5   r6   worldWorldTrainerr@   r'   r'   r(   rA   q   s   zYOLOWorld.task_mapc                 C   sB   | j | d}||v r|| || j _| jr|| jj _dS dS )z
        Set the model's class names for detection.

        Args:
            classes (list[str]): A list of categories i.e. ["person"].
         N)r   set_classesremoverJ   r+   )r#   classes
backgroundr'   r'   r(   rT   }   s   
zYOLOWorld.set_classes)rH   FrI   N)	rB   rC   rD   rE   r"   rF   rA   rT   rG   r'   r'   r&   r(   r   ]   s    
r   c                       s   e Zd ZdZdd fddZedd	 Zd
d Zdd Zdd Z	dd Z
dd Z			dddZddi ddfdedef fddZ  ZS )r    z.YOLOE object detection and segmentation model.yoloe-11s-seg.ptNFrI   c                    s<   t  j|||d t| jdsttd d| j_dS dS )ah  
        Initialize YOLOE model with a pre-trained model file.

        Args:
            model (str | Path): Path to the pre-trained model file. Supports *.pt and *.yaml formats.
            task (str, optional): Task type for the model. Auto-detected if None.
            verbose (bool): If True, prints additional information during initialization.
        r   rJ   rK   NrL   )r#   r   r   r   r&   r'   r(   r"      s   	zYOLOE.__init__c                 C   s6   t tjjtjjtjjdttjjtj	j
tjjddS )rO   rP   )r-   r.   )r   r   r   YOLOEDetectValidatorr-   r6   YOLOETrainerr   YOLOESegValidatorr.   r9   YOLOESegTrainerr@   r'   r'   r(   rA      s   zYOLOE.task_mapc                 C      t | jtsJ | j|S )z3Get text positional embeddings for the given texts.)
isinstancer   r   get_text_pe)r#   textsr'   r'   r(   r`         zYOLOE.get_text_pec                 C   s   t | jtsJ | j||S )a  
        Get visual positional embeddings for the given image and visual features.

        This method extracts positional embeddings from visual features based on the input image. It requires
        that the model is an instance of YOLOEModel.

        Args:
            img (torch.Tensor): Input image tensor.
            visual (torch.Tensor): Visual features extracted from the image.

        Returns:
            (torch.Tensor): Visual positional embeddings.

        Examples:
            >>> model = YOLOE("yoloe-11s-seg.pt")
            >>> img = torch.rand(1, 3, 640, 640)
            >>> visual_features = model.model.backbone(img)
            >>> pe = model.get_visual_pe(img, visual_features)
        )r_   r   r   get_visual_pe)r#   imgvisualr'   r'   r(   rc      s   zYOLOE.get_visual_pec                 C   s$   t | jtsJ | jj||d dS )a  
        Set vocabulary and class names for the YOLOE model.

        This method configures the vocabulary and class names used by the model for text processing and
        classification tasks. The model must be an instance of YOLOEModel.

        Args:
            vocab (list): Vocabulary list containing tokens or words used by the model for text processing.
            names (list): List of class names that the model can detect or classify.

        Raises:
            AssertionError: If the model is not an instance of YOLOEModel.

        Examples:
            >>> model = YOLOE("yoloe-11s-seg.pt")
            >>> model.set_vocab(["person", "car", "dog"], ["person", "car", "dog"])
        )rJ   N)r_   r   r   	set_vocab)r#   vocabrJ   r'   r'   r(   rf      s   zYOLOE.set_vocabc                 C   r^   )z)Get vocabulary for the given class names.)r_   r   r   	get_vocab)r#   rJ   r'   r'   r(   rh      rb   zYOLOE.get_vocabc                 C   sJ   t | jtsJ | j|| d|vsJ || j_| jr#|| jj_dS dS )z
        Set the model's class names and embeddings for detection.

        Args:
            classes (list[str]): A list of categories i.e. ["person"].
            embeddings (torch.Tensor): Embeddings corresponding to the classes.
        rS   N)r_   r   r   rT   rJ   r+   )r#   rV   
embeddingsr'   r'   r(   rT      s   zYOLOE.set_classesc                 K   sZ   d| i}i | j ||ddi}|p| d|| jd}|| j||d |j| _|jS )a:  
        Validate the model using text or visual prompts.

        Args:
            validator (callable, optional): A callable validator function. If None, a default validator is loaded.
            load_vp (bool): Whether to load visual prompts. If False, text prompts are used.
            refer_data (str, optional): Path to the reference data for visual prompts.
            **kwargs (Any): Additional keyword arguments to override default settings.

        Returns:
            (dict): Validation statistics containing metrics computed during validation.
        rectmodevalr*   )args
_callbacks)r   load_vp
refer_data)	overrides_smart_load	callbacksr   metrics)r#   r*   ro   rp   kwargscustomrm   r'   r'   r(   rl      s   
z	YOLOE.valstreamvisual_promptsc           
         s  t |r4d|v rd|v sJ d|  t |d t |d ks4J dt |d  dt |d  d|p:| d| jjdd	|d
u dd| jd| _t |rt|tr_t	dd |d D nt t
|d }|| jjd _dd t|D | j_| j|  | jj| jd |d
u r|d
urt|}|jdv rtt|d d }|d
urt |r| j|}	| j| jj|	 t| jtjjrdnd| _d
| _t j||fi |S )av  
        Run prediction on images, videos, directories, streams, etc.

        Args:
            source (str | int | PIL.Image | np.ndarray, optional): Source for prediction. Accepts image paths,
                directory paths, URL/YouTube streams, PIL images, numpy arrays, or webcam indices.
            stream (bool): Whether to stream the prediction results. If True, results are yielded as a
                generator as they are computed.
            visual_prompts (dict): Dictionary containing visual prompts for the model. Must include 'bboxes' and
                'cls' keys when non-empty.
            refer_image (str | PIL.Image | np.ndarray, optional): Reference image for visual prompts.
            predictor (callable, optional): Custom predictor function. If None, a predictor is automatically
                loaded based on the task.
            **kwargs (Any): Additional keyword arguments passed to the predictor.

        Returns:
            (List | generator): List of Results objects or generator of Results objects if stream=True.

        Examples:
            >>> model = YOLOE("yoloe-11s-seg.pt")
            >>> results = model.predict("path/to/image.jpg")
            >>> # With visual prompts
            >>> prompts = {"bboxes": [[10, 20, 100, 200]], "cls": ["person"]}
            >>> results = model.predict("path/to/image.jpg", visual_prompts=prompts)
        bboxesclsz7Expected 'bboxes' and 'cls' in visual prompts, but got z=Expected equal number of bounding boxes and classes, but got z and z respectivelyr+   predictFN   )r   rk   saver   batch)rq   rn   c                 s   s    | ]	}t t|V  qd S )N)lenset).0cr'   r'   r(   	<genexpr>N  s    z YOLOE.predict.<locals>.<genexpr>c                 S   s   g | ]}d | qS )objectr'   )r   ir'   r'   r(   
<listcomp>S  s    z!YOLOE.predict.<locals>.<listcomp>)r   >   videorw   r   r.   r-   )r   keysrr   r   r   rs   r+   r_   listmaxr   ncrangerJ   set_promptscopysetup_modelr   rk   nextiterget_vperT   r   r.   r9   r!   r{   )
r#   sourcerw   rx   refer_imager+   ru   num_clsdatasetvper&   r'   r(   r{     sJ   "

zYOLOE.predict)rY   NFrX   )NFN)rB   rC   rD   rE   r"   rF   rA   r`   rc   rf   rh   rT   rl   booldictr{   rG   r'   r'   r&   r(   r       s0    

r    N)pathlibr   ultralytics.data.buildr   ultralytics.engine.modelr   ultralytics.modelsr   ultralytics.nn.tasksr   r   r   r	   r
   r   r   r   ultralytics.utilsr   r   r   r   r    r'   r'   r'   r(   <module>   s   (
H3