o
    Whv&                     @   s   d dl Z d dlm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 G dd dZed	krNd dlZeejZed
krCejd
 ndZeed  dS dS )    N)Any)YOLO)LOGGER)check_requirements)GITHUB_ASSETS_STEMSc                   @   sF   e Zd ZdZdefddZdd Zdd Zd	d
 Zdd Z	dd Z
dS )	Inferencea  
    A class to perform object detection, image classification, image segmentation and pose estimation inference.

    This class provides functionalities for loading models, configuring settings, uploading video files, and performing
    real-time inference using Streamlit and Ultralytics YOLO models.

    Attributes:
        st (module): Streamlit module for UI creation.
        temp_dict (dict): Temporary dictionary to store the model path and other configuration.
        model_path (str): Path to the loaded model.
        model (YOLO): The YOLO model instance.
        source (str): Selected video source (webcam or video file).
        enable_trk (str): Enable tracking option ("Yes" or "No").
        conf (float): Confidence threshold for detection.
        iou (float): IoU threshold for non-maximum suppression.
        org_frame (Any): Container for the original frame to be displayed.
        ann_frame (Any): Container for the annotated frame to be displayed.
        vid_file_name (str | int): Name of the uploaded video file or webcam index.
        selected_ind (List[int]): List of selected class indices for detection.

    Methods:
        web_ui: Sets up the Streamlit web interface with custom HTML elements.
        sidebar: Configures the Streamlit sidebar for model and inference settings.
        source_upload: Handles video file uploads through the Streamlit interface.
        configure: Configures the model and loads selected classes for inference.
        inference: Performs real-time object detection inference.

    Examples:
        >>> inf = Inference(model="path/to/model.pt")  # Model is an optional argument
        >>> inf.inference()
    kwargsc                 K   s   t d ddl}|| _d| _d| _d| _d| _d| _d| _d| _	g | _
d| _ddi|| _d| _| jd dur=| jd | _td| j  dS )	z
        Initialize the Inference class, checking Streamlit requirements and setting up the model path.

        Args:
            **kwargs (Any): Additional keyword arguments for model configuration.
        zstreamlit>=1.29.0r   NFg      ?g?modelu   Ultralytics Solutions: ✅ )r   	streamlitstsource
enable_trkconfiou	org_frame	ann_framevid_file_nameselected_indr	   	temp_dict
model_pathr   info)selfr   r    r   ]/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/solutions/streamlit_inference.py__init__/   s"   zInference.__init__c                 C   sP   d}d}d}| j jddd | j j|dd | j j|dd | j j|dd d	S )
z>Sets up the Streamlit web interface with custom HTML elements.z-<style>MainMenu {visibility: hidden;}</style>z<div><h1 style="color:#FF64DA; text-align:center; font-size:40px; margin-top:-50px;
        font-family: 'Archivo', sans-serif; margin-bottom:20px;">Ultralytics YOLO Streamlit Application</h1></div>u   <div><h4 style="color:#042AFF; text-align:center; font-family: 'Archivo', sans-serif; 
        margin-top:-15px; margin-bottom:50px;">Experience real-time object detection on your webcam with the power 
        of Ultralytics YOLO! 🚀</h4></div>zUltralytics Streamlit Appwide)
page_titlelayoutT)unsafe_allow_htmlN)r   set_page_configmarkdown)r   menu_style_cfgmain_title_cfgsub_title_cfgr   r   r   web_uiK   s   zInference.web_uic                 C   s   | j j d}| j j|dd W d   n1 sw   Y  | j jd | j jdd| _| j jdd	| _t| j j	d
dd| j
d| _
t| j j	ddd| jd| _| j d\}}| | _| | _dS )zAConfigure the Streamlit sidebar for model and inference settings.z`https://raw.githubusercontent.com/ultralytics/assets/main/logo/Ultralytics_Logotype_Original.svg   )widthNzUser ConfigurationVideo)webcamvideozEnable Tracking)YesNozConfidence Thresholdg        g      ?g{Gz?zIoU Threshold   )r   sidebarimagetitle	selectboxr   radior   floatsliderr   r   columnsemptyr   r   )r   logocol1col2r   r   r   r-   ^   s"   

zInference.sidebarc                 C   s   d| _ | jdkrA| jjjdg dd}|dur?t| }tdd}|	|  W d   n1 s5w   Y  d| _ dS dS | jd	krKd
| _ dS dS )z:Handle video file uploads through the Streamlit interface. r)   zUpload Video File)mp4movavimkv)typeNzultralytics.mp4wbr(   r   )
r   r   r   r-   file_uploaderioBytesIOreadopenwrite)r   vid_filegoutr   r   r   source_uploads   s   



zInference.source_uploadc                    s   dd t D }| jr|d| jdd  | jjd|}| jd t|	  d| _
t| j
j  W d   n1 sAw   Y  | jd | jjjd	  dd
 d} fdd|D | _t| jtsrt| j| _dS dS )z<Configure the model and load selected classes for inference.c                 S   s"   g | ]}| d r|ddqS )yolo11yolor   )
startswithreplace).0xr   r   r   
<listcomp>   s   " z'Inference.configure.<locals>.<listcomp>r   z.ptModelzModel is downloading...NzModel loaded successfully!Classes   )defaultc                    s   g | ]}  |qS r   )index)rN   optionclass_namesr   r   rP      s    )r   r   insertsplitr   r-   r0   spinnerr   lowerr	   listnamesvaluessuccessmultiselectr   
isinstance)r   available_modelsselected_modelselected_classesr   rW   r   	configure   s   zInference.configurec                 C   s"  |    |   |   |   | jjdr| jd}t| j}|	 s/| j
d dS |	 r| \}}|sB| jd nE| jdkrV| jj|| j| j| jdd}n| j|| j| j| jd	}|d
  }|rs|  | j  | jj|dd | jj|dd |	 s3|  t  dS )zEPerform real-time object detection inference on video or webcam feed.StartStopz&Could not open webcam or video source.NzQFailed to read frame from webcam. Please verify the webcam is connected properly.r*   T)r   r   classespersist)r   r   ri   r   BGR)channels)r$   r-   rI   rf   r   buttoncv2VideoCapturer   isOpenederrorrC   warningr   r	   trackr   r   r   plotreleasestopr   r.   r   destroyAllWindows)r   stop_buttoncapr`   frameresultsannotated_framer   r   r   	inference   s:   

zInference.inferenceN)__name__
__module____qualname____doc__r   r   r$   r-   rI   rf   r}   r   r   r   r   r      s     r   __main__   )r	   )rA   typingr   rn   ultralyticsr   ultralytics.utilsr   ultralytics.utils.checksr   ultralytics.utils.downloadsr   r   r~   syslenargvargsr	   r}   r   r   r   r   <module>   s    0
