
    |h)                     $   d dl Z d dlmZm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 g ej                  _         G d d      Zed	k(  rDd dlZ eej(                        Zed
kD  rej(                  d
   ndZ ee      j/                          yy)    N)AnyList)YOLO)LOGGER)check_requirements)GITHUB_ASSETS_STEMSc                   H    e Zd ZdZdeddfdZddZddZddZdd	Z	dd
Z
y)	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 (bool): Enable tracking option.
        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: Set up the Streamlit web interface with custom HTML elements.
        sidebar: Configure the Streamlit sidebar for model and inference settings.
        source_upload: Handle video file uploads through the Streamlit interface.
        configure: Configure the model and load selected classes for inference.
        inference: Perform real-time object detection inference.

    Examples:
        Create an Inference instance with a custom model
        >>> inf = Inference(model="path/to/model.pt")
        >>> inf.inference()

        Create an Inference instance with default settings
        >>> inf = Inference()
        >>> inf.inference()
    kwargsreturnNc                 \   t        d       ddl}|| _        d| _        d| _        d| _        d| _        d| _        d| _        d| _	        g | _
        d| _        ddi|| _        d| _        | j                  d   | j                  d   | _        t        j                  d| j                          y)	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   s      h/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/solutions/streamlit_inference.py__init__zInference.__init__7   s     	./	!')
!4262>>'"."nnW5DO1$..1ABC    c                     d}d}d}| j                   j                  dd       | j                   j                  |d       | j                   j                  |d       | j                   j                  |d       y	)
z=Set 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_cfgs       r   web_uizInference.web_uiS   su    Lv0
 	+FvV4@4@$?r   c           	      *   | j                   j                  5  d}| j                   j                  |d       ddd       | j                   j                  j                  d       | j                   j                  j	                  dd      | _        | j                   j                  j                  dd	      d
k(  | _        t        | j                   j                  j                  ddd| j                  d            | _
        t        | j                   j                  j                  ddd| j                  d            | _        | j                   j                  d      \  }}|j                         | _        |j                         | _        y# 1 sw Y   SxY w)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Nor1   zConfidence Thresholdg        g      ?g{Gz?zIoU Threshold   )r   sidebarimagetitle	selectboxr   radior   floatsliderr   r   columnsemptyr   r   )r   logocol1col2s       r   r4   zInference.sidebarf   s'   WW__ 	+uDGGMM$cM*	+ 	23ggoo//
 ''////0A=QUZZGGOO""#93TYYPTU
	 //c488UYZ[WW__Q'
d#	+ 	+s    FFc                    d| _         | j                  dk(  r| j                  j                  j	                  dg d      }|_t        j                  |j                               }t        dd      5 }|j                  |j                                ddd       d| _         yy| j                  d	k(  rd
| _         yy# 1 sw Y   *xY w)z:Handle video file uploads through the Streamlit interface. r0   zUpload Video File)mp4movavimkv)typeNzultralytics.mp4wbr/   r   )
r   r   r   r4   file_uploaderioBytesIOreadopenwrite)r   vid_filegouts       r   source_uploadzInference.source_upload{   s    ;;'!ww445HOk4lH#JJx}}/+T2 (cIIaffh'(%6"	 $
 [[H$!"D %( (s   1 B::Cc           	         g dg dct        t        D cg c],  t        fdD              rdvrj                  dd      . c}fd      }| j                  r/|j                  d	| j                  j                  d
d      d	          | j                  j                  j                  d|      }| j                  j                  d      5  t        |j                          d
      | _        t        | j                  j                  j!                               }ddd       | j                  j#                  d       | j                  j                  j%                  d|dd       }|D cg c]  }|j'                  |       c}| _        t+        | j(                  t              st        | j(                        | _        yyc c}w # 1 sw Y   xY wc c}w )z<Configure the model and load selected classes for inference.)yolo11nyolo11syolo11myolo11lyolo11x)rA   z-segz-posez-obbz-clsc              3   @   K   | ]  }j                  |        y w)N)
startswith).0bxs     r   	<genexpr>z&Inference.configure.<locals>.<genexpr>   s     61q||A6s   	grayscaleyolor   c                     j                  | d d j                               j                  | dd  j                         xs d      fS )N   rA   )indexlower)r\   M_ORDT_ORDs    r   <lambda>z%Inference.configure.<locals>.<lambda>   s<    5;;q!u{{}5u{{1QR5;;=CVTV7WX r   )keyr   z.pt   ModelzModel is downloading...NzModel loaded successfully!Classes   )default)sortedr   anyreplacer   insertsplitr   r4   r7   spinnerr   rc   r   listnamesvaluessuccessmultiselectrb   r   
isinstance)	r   r\   available_modelsselected_modelclass_namesselected_classesoptionrd   re   s	    `     @@r   	configurezInference.configure   s    OPuu! -666;a;O 		&&)
 Y
 ??##At'<'<UA'Fq'IJ227<LMWW__67 	:!5!5!7 8<=DJtzz//6689K	: 	45  77??66y+WbcedeWf6gEUV6[..v6V$++T2 $T%6%6 7D 3)	: 	: Ws   1GAG6GGc                 |   | j                          | j                          | j                          | j                          | j                  j                  j                  d      r| j                  j                  d      }t        j                  | j                        }|j                         s| j                  j                  d       y|j                         r;|j                         \  }}|s| j                  j                  d       n	| j                  r?| j                  j                  || j                   | j"                  | j$                  d      }n3| j                  || j                   | j"                  | j$                        }|d	   j'                         }|r*|j)                          | j                  j+                          | j,                  j/                  |d
       | j0                  j/                  |d
       |j                         r;|j)                          t        j2                          y)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.T)r   r   classespersist)r   r   r   r   BGR)channels)r*   r4   rQ   r~   r   buttoncv2VideoCapturer   isOpenederrorrK   warningr   r   trackr   r   r   plotreleasestopr   r5   r   destroyAllWindows)r   stop_buttoncaprv   frameresultsannotated_frames          r   	inferencezInference.inference   s   77??!!'*''..0K""4#5#56C<<>FG,,.!$GGOO$wx ??"jj..DII488TEVEV`d / G #jjTYYDHHVZVgVgjhG")!*//"3KKMGGLLN$$UU$;$$_u$E+ ,,.. KKMr   )r   N)__name__
__module____qualname____doc__r   r   r*   r4   rQ   r~   r    r   r   r
   r
      s8    #JD D D8@&&*#88& r   r
   __main__rh   )r   )rI   typingr   r   r   torchultralyticsr   ultralytics.utilsr   ultralytics.utils.checksr   ultralytics.utils.downloadsr   r   __path__r
   r   syslenargvargsr   r   r   r   r   <module>r      s    
  
   $ 7 ; y  y x z sxx=D!8CHHQKEE$$& r   