
    h1                     ,   d dl Z 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      j1                          yy)    N)AnyList)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/eduruby.in/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)r0   r1   zEnable Tracking)YesNor3   zConfidence Thresholdg        g      ?g{Gz?zIoU Thresholdr2      )r   sidebarr2   title	selectboxr   radior   floatsliderr   r   columnsemptyr   r   )r   logocol1col2s       r   r6   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      }|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 r1   zUpload Video File)typeNzultralytics.mp4wbr0   r2   zUpload Image FilesT)rE   accept_multiple_filesF.)deletesuffix)pathname)ultralytics.data.utilsrB   rC   r   r   r   r6   file_uploaderioBytesIOreadopenwritetempfileNamedTemporaryFilerM   splitr   append)
r   rB   rC   vid_filegoutrU   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#ww445IP[sw4xH' \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                  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)rD   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   rD   )indexlower)rj   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   insertrW   r   r6   r8   spinnerr   rq   r   listnamesvaluessuccessmultiselectrp   r   
isinstance)	r   rj   available_modelsselected_modelclass_namesselected_classesoptionrr   rs   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                    t        | 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 Uw xY w)z%Perform inference on uploaded images.rL   Nz#### Processed: rM   r5   BGRzOriginal Imagechannelscaptionr   r   classesr   zPredicted Imagez"Could not load the uploaded image.)	enumerater   cv2imreadr   r'   r<   r2   r   r   r   r   plotosunlinkFileNotFoundErrorerror)	r   idximg_infoimg_pathr2   r?   r@   resultsannotated_images	            r   image_inferencezInference.image_inference   sH   &t':':; 	DMC'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*   :E)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.Startr2   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+   r6   r_   r   r   buttonr   r   r   r   r   VideoCapturer   isOpenedr   rR   warningr   r   trackr   r   r   r   releasestopr   r2   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+   r6   r_   r   r   r    r    r   r
   r
      s?    #JD D D:@&*.\088D*- r    r
   __main__rv   )r   )rP   r   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 ; c  c L z sxx=D!8CHHQKEE$$& r    