
    .h3                     (   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(  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)YOLO)LOGGER)check_requirements)GITHUB_ASSETS_STEMSc                   P    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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                 j   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                          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img_file_names
enable_trkconfiou	org_frame	ann_framevid_file_nameselected_indr   	temp_dict
model_pathr   info)selfr
   r   s      g/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/solutions/streamlit_inference.py__init__zInference.__init__8   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:#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_uiU   su    Lv?
 	+FvV4@4@$?r   c           	      f   | j                   j                  5  d}| j                   j                  |d       ddd       | j                   j                  j                  d       | j                   j                  j	                  dd      | _        | j
                  dv r.| 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
                  dk7  rI| j                   j                  d      \  }}|j                         | _        |j                         | _        yy# 1 sw Y   qx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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.sidebarh   sE   WW__ 	+uDGGMM$cM*	+ 	23ggoo//(
 ;;--"ggoo334E}UY^^DOGGOO""#93TYYPTU
	 //c488UYZ[;;'!+JD$!ZZ\DN!ZZ\DN "!	+ 	+s    F&&F0c                 T   ddl m}m} d| _        | j                  dk(  r| j
                  j                  j                  d|      }|_t        j                  |j                               }t        dd	      5 }|j                  |j                                ddd       d| _        yy| j                  d
k(  rd| _        y| j                  dk(  rddl}| j
                  j                  j                  d|d      x}r|D ]  }|j                  dd|j                  j!                  d      d          5 }	|	j                  |j                                | j"                  j%                  |	j                  |j                  d       ddd        yyy# 1 sw Y   xY w# 1 sw Y   xY w)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   s   C;;'!ww445H{4[H#JJx}}/+T2 (cIIaffh'(%6"	 $
 [[H$!"D[[G#77??88$;d 9  x   ( \G!44EAgllN`N`adNefhNiMjJk4l \pr0++22BGGW\\3Z[\ \\ $( (\ \s   7 F3AFFF'	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                  j                  j                  d
|      	| j                  j                  d      5  	j                  d      st        	fddD              r	}n	j                          d}t        |      | _        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)rC   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   rC   )indexlower)rj   M_ORDT_ORDs    r   <lambda>z%Inference.configure.<locals>.<lambda>   s<    5;;q!u{{}5u{{1QR5;;=CVTV7WX r   )keyr   ModelzModel is downloading...).ptz.onnxz.torchscriptz
.mlpackagez.enginec              3   &   K   | ]  }|v  
 y wrf    )rh   fmtselected_models     r   rk   z&Inference.configure.<locals>.<genexpr>   s      i*-~%is   )openvino_model
rknn_modelrw   NzModel loaded successfully!Classes   )default)sortedr   anyreplacer   insertr   r5   r7   spinnerendswithrq   r   r   listnamesvaluessuccessmultiselectrp   r   
isinstance)
r   rj   available_modelsr   class_namesselected_classesoptionrr   rs   r{   s
    `     @@@r   	configurezInference.configure   s    OPuu! -666;a;O 		&&)
 Y
 ??##At7227<LMWW__67 	:&&'`aeh i1Qi f ,
 . 4 4 67s;
j)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 35	: 	: Ws   1G$A9G)G5)G2c                    | j                   D ])  }|d   }t        j                  |      }|| j                  j	                  d|d           | j                  j                  d      \  }}|5  | j                  j                  |dd       ddd       | j                  || j                  | j                  | j                  	      }|d
   j                         }|5  | j                  j                  |dd       ddd       	 t        j                  |       | j                  j                  d       , y# 1 sw Y   xY w# 1 sw Y   LxY w# t        $ r Y Rw xY w)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H'HJJx(E   #3HV4D3E!FG!WW__Q/
d SGGMM%%AQMRS**URVRcRc*d")!*//"3 ^GGMM/EK\M]^IIh' BC#	DS S^ ^ ) s*   .D;EE;E	E		E E c                 $   | j                          | j                          | j                          | j                          | j                  j                  j                  d      r| j                  dk(  r9| j                  r| j                          y| j                  j                  d       y| j                  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*|j1                          | j                  j3                          | j4                  j7                  |dd       | j8                  j7                  |dd       |j                         r=|j1                          t        j:                          y)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   s   77??!!'*{{g%&&((*  GGLL!TU''//008K""4#5#56C<<>FG,,.!$GGOO$wx ??"jj..DII488TEVEV`d / G #jjTYYDHHVZVgVgjhG")!*//"3KKMGGLLN$$UUDT$U$$_uN_$`+ ,,.. KKMr   )r   N)__name__
__module____qualname____doc__r   r   r*   r5   r^   r   r   r   ry   r   r   r	   r	      s@    #JD D D:@&*.\2 8D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   ry   r   r   <module>r      s    
 	  
   $ 7 ; j  j Z z sxx=D!8CHHQKEE$$& r   