
    j3                     2   d dl Z d dlZd dl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    rId dlZ eej                  Zed
k    rej        d
         ndZ ee                                           dS dS )    N)Any)YOLO)LOGGER)check_requirements)GITHUB_ASSETS_STEMSc                   R    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
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 (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| _        g | _        d| _        d| _        d| _        d| _        d| _	        d| _
        g | _        d| _        ddi|| _        d| _        | j        d         | j        d         | _        t          j        d| j                    dS )	zInitialize 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img_file_names
enable_trkconfiou	org_frame	ann_framevid_file_nameselected_indr   	temp_dict
model_pathr   info)selfr
   r   s      n/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/solutions/streamlit_inference.py__init__zInference.__init__7   s     	./// 	!')
!4262>'"."nW5DOB$.BBCCCCC    c                     d}d}d}| j                             dd           | j                             |d           | j                             |d           | j                             |d           d	S )
z=Set up the Streamlit web interface with custom HTML elements.z-<style>MainMenu {visibility: hidden;}</style>z<div><h1 style="color:#111F68; 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><h5 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, videos, and images
        with the power of Ultralytics YOLO! 🚀</h5></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   s    Lv?
 	+FvVVV4@@@4@@@$?????r   c           	         | j         j        5  d}| j                             |d           ddd           n# 1 swxY w Y   | j         j                            d           | j         j                            dd          | _        | j        dv r)| j         j                            d	d
          dk    | _        t          | j         j        	                    ddd| j
        d                    | _
        t          | j         j        	                    ddd| j        d                    | _        | j        dk    rQ| j                             d          \  }}|                                | _        |                                | _        dS 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Source)webcamvideoimage)r/   r0   zEnable Tracking)YesNor2   zConfidence Thresholdg        g      ?g{Gz?zIoU Thresholdr1      )r   sidebarr1   title	selectboxr   radior   floatsliderr   r   columnsemptyr   r   )r   logocol1col2s       r   r5   zInference.sidebarf   s   W_ 	+ 	+uDGMM$cM***	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	2333go//(
 
 ;---"go334E}UUY^^DOGO""#93TYPTUU
 
	 //c48UYZZ[[;'!!++JD$!ZZ\\DN!ZZ\\DNNN "!s   8<<c                 \   ddl m}m} d| _        | j        dk    r| j        j                            d|          }|~t          j	        |
                                          }t          dd	          5 }|                    |
                                           ddd           n# 1 swxY w Y   d| _        dS dS | j        d
k    r	d| _        dS | j        dk    rddl}| j        j                            d|d          x}r|D ]}|                    dd|j                            d          d                    5 }	|	                    |
                                           | j                            |	j        |j        d           ddd           n# 1 swxY w Y   dS dS dS )z:Handle video file uploads through the Streamlit interface.r   )IMG_FORMATSVID_FORMATS r0   zUpload Video File)typeNzultralytics.mp4wbr/   r1   zUpload Image FilesT)rD   accept_multiple_filesF.)deletesuffix)pathname)ultralytics.data.utilsrA   rB   r   r   r   r5   file_uploaderioBytesIOreadopenwritetempfileNamedTemporaryFilerL   splitr   append)
r   rA   rB   vid_filegoutrT   imgfilesimgfiletfs
             r   source_uploadzInference.source_upload}   sl   CCCCCCCC;'!!w445H{4[[H#Jx}}//+T22 (cIIaffhh'''( ( ( ( ( ( ( ( ( ( ( ( ( ( (%6"""	 $#
 [H$$!"D[G##OOO7?88$;d 9   x \  ( \ \G!44EJkglN`N`adNeNefhNiJkJk4ll \pr000+22BGW\3Z3Z[[[\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ $#\ \\ \s%   4(B((B,/B,AFF 	#F 	c                 ~   g dg dct          fdt          D             fd          }| j        r|                    d| j                   | j        j                            d|          | j                            d          5                      d	          st          fd
dD                       r}n
                                 d}t          |          | _        t          | j        j                                                  ddd           n# 1 swxY w Y   | j                            d           | j        j                            ddd                   }fd|D             | _        t'          | j        t                    st          | j                  | _        dS dS )z<Configure the model and load selected classes for inference.)yolo26nyolo26syolo26myolo26lyolo26x)rC   z-segz-posez-obbz-clsc                 |    g | ]7t          fd D                       rdv!                    dd          8S )c              3   B   K   | ]}                     |          V  d S N)
startswith).0bxs     r   	<genexpr>z1Inference.configure.<locals>.<listcomp>.<genexpr>   s-      661q||A666666r   	grayscaleyolor   )anyreplace)ri   rk   M_ORDs    @r   
<listcomp>z'Inference.configure.<locals>.<listcomp>   se       666666666 <Ga;O;O 		&&));O;O;Or   c                                          | d d                                                                        | dd                                          pd          fS )N   rC   )indexlower)rk   rq   T_ORDs    r   <lambda>z%Inference.configure.<locals>.<lambda>   sJ    5;;q!u{{}}55u{{1QRR5;;==CVTV7W7WX r   )keyr   ModelzModel is downloading...).ptz.onnxz.torchscriptz
.mlpackagez.enginec              3       K   | ]}|v V  	d S rg    )ri   fmtselected_models     r   rl   z&Inference.configure.<locals>.<genexpr>   sA       i i*-~%i i i i i ir   )openvino_model
rknn_modelr{   NzModel loaded successfully!Classes   )defaultc                 :    g | ]}                     |          S r}   )ru   )ri   optionclass_namess     r   rr   z'Inference.configure.<locals>.<listcomp>   s'    VVV6[..v66VVVr   )sortedr   r   insertr   r5   r7   spinnerendswithro   rv   r   r   listnamesvaluessuccessmultiselectr   
isinstance)r   available_modelsr   selected_classesrq   rw   r   r   s       @@@@r   	configurezInference.configure   sX    ONNPuPuPuu!   ,  
 YXXXX
 
 
 ? 	8##At777227<LMMW__677 	: 	:&&'`aa <eh i i i i1Qi i i f f < ,

 . 4 4 6 6;;;
j))DJtz/668899K	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	4555  7?66y+WbcedeceWf6ggVVVVEUVVV$+T22 	8 $T%6 7 7D	8 	8s   B
D&&D*-D*c                    | j         D ]T}|d         }t          j        |          }|| j                            d|d                     | j                            d          \  }}|5  | j                            |dd           ddd           n# 1 swxY w Y   |                     || j        | j	        | j
        	          }|d
                                         }|5  | j                            |dd           ddd           n# 1 swxY w Y   	 t          j        |           )# t          $ r Y 6w xY w| j                            d           VdS )z%Perform inference on uploaded images.rK   Nz#### Processed: rL   r4   BGRzOriginal Imagechannelscaptionr   r   classesr   zPredicted Imagez"Could not load the uploaded image.)r   cv2imreadr   r&   r;   r1   r   r   r   r   plotosunlinkFileNotFoundErrorerror)r   img_infoimg_pathr1   r>   r?   resultsannotated_images           r   image_inferencezInference.image_inference   s   + 	D 	DH'HJx((E   !FHV4D!F!FGGG!W__Q//
d S SGMM%%AQMRRRS S S S S S S S S S S S S S S**URVRc*dd")!*//"3"3 ^ ^GMM/EK\M]]]^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^Ih''''(   D BCCCC#	D 	Ds6   ,BB	B	%DD	D	D11
D?>D?c                    |                                   |                                  |                                  |                                  | j        j                            d          r| j        dk    r8| j        r|                                  n| j        	                    d           dS | j        j                            d          }t          j        | j                  }|                                s| j                            d           dS |                                r*|                                \  }}|s| j                            d           n| j        r/| j                            || j        | j        | j        d	          }n(|                     || j        | j        | j        
          }|d                                         }|r-|                                 | j                                         | j                            |dd           | j                            |dd           |                                *|                                 t          j                     dS )zEPerform real-time object detection inference on video or webcam feed.Startr1   z1Please upload an image file to perform inference.NStopz&Could not open webcam or video source.zQFailed to read frame from webcam. Please verify the webcam is connected properly.T)r   r   r   persistr   r   r   zOriginal Framer   zPredicted Frame)r*   r5   r^   r   r   buttonr   r   r   r   r   VideoCapturer   isOpenedr   rQ   warningr   r   trackr   r   r   r   releasestopr   r1   r   destroyAllWindows)r   stop_buttoncapr   framer   annotated_frames          r   	inferencezInference.inference   sA   7?!!'** %	{g%%& V((****GLL!TUUU'/0088K"4#566C<<>> FGGG,,.. a!$ GOO$wxxx ? i"j..DI48TEV`d /  GG #jjTYDHVZVgjhhG")!*//"3"3 #KKMMMGLLNNN$$UUDT$UUU$$_uN_$```+ ,,.. a. KKMMMr   )r   N)__name__
__module____qualname____doc__r   r   r*   r5   r^   r   r   r   r}   r   r   r	   r	      s        " "HD D D D D D8@ @ @ @&* * * *.\ \ \ \2 8  8  8  8DD D D D*-  -  -  -  -  - r   r	   __main__   )r   )rO   r   typingr   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 7 7 7 7 7 ; ; ; ; ; ; h  h  h  h  h  h  h  h V zJJJ 3sx==D!88CHQKKEIE$$&&&&& r   