
    h3                     &   S SK r S SKrS SKJr  S SKrS SKrS SKJr  S SKJ	r	  S SK
Jr  S SKJr  / \R                  l         " S S5      r\S	:X  aB  S SKr\" \R(                  5      r\S
:  a  \R(                  S
   OSr\" \S9R/                  5         gg)    N)Any)YOLO)LOGGER)check_requirements)GITHUB_ASSETS_STEMSc                   f    \ rS rSrSrS\SS4S jrSS jrSS jrSS	 jr	SS
 jr
SS jrSS jrSrg)	Inference   a  
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                 l   [        S5        SSKnX l        SU l        / U l        SU l        SU l        SU l        SU l        SU l	        SU l
        / U l        SU l        SS0UEU l        SU l        U R                  S   b  U R                  S   U l        [        R                   " SU R                   35        g)	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      c/home/james-whalen/.local/lib/python3.13/site-packages/ultralytics/solutions/streamlit_inference.py__init__Inference.__init__8   s     	./ 	!')
!4262>>'"."nnW5DO1$..1ABC    c                     SnSnSnU R                   R                  SSS9  U R                   R                  USS9  U R                   R                  USS9  U R                   R                  USS9  g	)
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_uiInference.web_uiU   su    Lv?
 	+FvV4@4@$?r!   c           	      n   U R                   R                     SnU R                   R                  USS9  SSS5        U R                   R                  R                  S5        U R                   R                  R	                  SS5      U l        U R
                  S;   a.  U R                   R                  R                  S	S
5      S:H  U l        [        U R                   R                  R                  SSSU R                  S5      5      U l
        [        U R                   R                  R                  SSSU R                  S5      5      U l        U R
                  S:w  aH  U R                   R                  S5      u  p#UR                  5       U l        UR                  5       U l        gg! , (       d  f       GNx= f)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)r2   r3   zEnable Tracking)YesNor5   zConfidence Thresholdg        g      ?g{Gz?zIoU Thresholdr4      )r   sidebarr4   title	selectboxr   radior   floatsliderr   r   columnsemptyr   r   )r   logocol1col2s       r   r8   Inference.sidebarh   s;   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%%
F4c                 r   SSK JnJn  SU l        U R                  S:X  a  U R
                  R                  R                  SUS9nUb`  [        R                  " UR                  5       5      n[        SS	5       nUR                  UR                  5       5        SSS5        SU l        ggU R                  S
:X  a  SU l        gU R                  S:X  a  SSKnU R
                  R                  R                  SUSS9=n(       a  U H  nUR                  SSUR                  R!                  S5      S    3S9 n	U	R                  UR                  5       5        U R"                  R%                  U	R                  UR                  S.5        SSS5        M     ggg! , (       d  f       GN= f! , (       d  f       M  = f)z:Handle video file uploads through the Streamlit interface.r   )IMG_FORMATSVID_FORMATS r3   zUpload Video File)typeNzultralytics.mp4wbr2   r4   zUpload Image FilesT)rH   accept_multiple_filesF.)deletesuffix)pathname)ultralytics.data.utilsrE   rF   r   r   r   r8   file_uploaderioBytesIOreadopenwritetempfileNamedTemporaryFilerP   splitr   append)
r   rE   rF   vid_filegoutrX   imgfilesimgfiletfs
             r   source_uploadInference.source_upload   sn   C;;'!ww445H{4[H#JJx}}/+T2cIIaffh' 3%6"	 $
 [[H$!"D[[G#77??88$;d 9  x   (G!44EAgllN`N`adNefhNiMjJk4lpr0++22BGGW\\3Z[ ml  ( $ 32 mls   7 F4AF'
F$'
F6	c           	      @  ^^^^	 / SQ/ SQsmm[        [         V^s/ s H9  m[        U4S jT 5       5      (       d  M  ST;  d  M'  TR                  SS5      PM;     snUU4S jS9nU R                  (       a  UR                  S	U R                  5        U R                  R                  R                  S
U5      m	U R                  R                  S5         T	R                  S5      (       d  [        U	4S jS 5       5      (       a  T	nOT	R                  5        S3n[        U5      U l        [        U R                  R                  R!                  5       5      nSSS5        U R                  R#                  S5        U R                  R                  R%                  SWUSS S9nU Vs/ s H  odR'                  U5      PM     snU l        [+        U R(                  [        5      (       d  [        U R(                  5      U l        ggs  snf ! , (       d  f       N= fs  snf )z<Configure the model and load selected classes for inference.)yolo11nyolo11syolo11myolo11lyolo11x)rG   z-segz-posez-obbz-clsc              3   F   >#    U  H  nTR                  U5      v   M     g 7fN)
startswith).0bxs     r   	<genexpr>&Inference.configure.<locals>.<genexpr>   s     61q||As   !	grayscaleyolor   c                    > TR                  U S S R                  5       5      TR                  U SS  R                  5       =(       d    S5      4$ )N   rG   )indexlower)ro   M_ORDT_ORDs    r   <lambda>%Inference.configure.<locals>.<lambda>   s:    5;;q!u{{}5u{{1QR5;;=CVTV7WXr!   )keyr   ModelzModel is downloading...).ptz.onnxz.torchscriptz
.mlpackagez.enginec              3   ,   >#    U  H	  oT;   v   M     g 7frk    )rm   fmtselected_models     r   rp   rq      s      i1Q#~%1Qs   )openvino_model
rknn_modelr~   NzModel loaded successfully!Classes   )default)sortedr   anyreplacer   insertr   r8   r:   spinnerendswithrw   r   r   listnamesvaluessuccessmultiselectrv   r   
isinstance)
r   ro   available_modelsr   class_namesselected_classesoptionrx   ry   r   s
    `     @@@r   	configureInference.configure   s    OPuu! -,A666 *;Fa;O *		&&),
 Y
 ??##At7227<LMWW__67&&'`aaeh i1Qi f f ,
 . 4 4 67s;
j)DJtzz//6689K 8 	45  77??66y+WbcedeWf6gEUVEU6..v6EUV$++T22 $T%6%6 7D 35 87 Ws#   HHHBH
(H

Hc                    U R                    GH#  nUS   n[        R                  " U5      nUb  U R                  R	                  SUS    35        U R                  R                  S5      u  pEU   U R                  R                  USSS9  SSS5        U R                  X0R                  U R                  U R                  S	9nUS
   R                  5       nU   U R                  R                  USSS9  SSS5         [        R                  " U5        GM  U R                  R                  S5        GM&     g! , (       d  f       N= f! , (       d  f       NZ= f! [         a     GMY  f = f)z%Perform inference on uploaded images.rO   Nz#### Processed: rP   r7   BGRzOriginal Imagechannelscaptionr   r   classesr   zPredicted Imagez"Could not load the uploaded image.)r   cv2imreadr   r(   r>   r4   r   r   r   r   plotosunlinkFileNotFoundErrorerror)r   img_infoimg_pathr4   rA   rB   resultsannotated_images           r   image_inferenceInference.image_inference   s   ++H'HJJx(E   #3HV4D3E!FG!WW__Q/
GGMM%%AQMR **URVRcRc*d")!*//"3GGMM/EK\M] IIh' BC# , T T ) s*   /D6E<E6
E	
E	
E'&E'c                 ^   U R                  5         U R                  5         U R                  5         U R                  5         U R                  R                  R                  S5      (       Ga-  U R                  S:X  a>  U R                  (       a  U R                  5         gU R                  R                  S5        gU R                  R                  R                  S5      n[        R                  " U R                  5      nUR                  5       (       d  U R                  R                  S5        gUR                  5       (       GaC  UR                  5       u  p4U(       d  U R                  R!                  S5        GOU R"                  (       a;  U R$                  R'                  X@R(                  U R*                  U R,                  SS	9nO/U R%                  X@R(                  U R*                  U R,                  S
9nUS   R/                  5       nU(       a*  UR1                  5         U R                  R3                  5         U R4                  R7                  USSS9  U R8                  R7                  USSS9  UR                  5       (       a  GMC  UR1                  5         [        R:                  " 5         g)zEPerform real-time object detection inference on video or webcam feed.Startr4   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,   r8   rb   r   r   buttonr   r   r   r   r   VideoCapturer   isOpenedr   rU   warningr   r   trackr   r   r   r   releasestopr   r4   r   destroyAllWindows)r   stop_buttoncapr   framer   annotated_frames          r   	inferenceInference.inference   s   77??!!'**{{g%&&((*  GGLL!TU''//008K""4#5#56C<<>>FG,,..!$GGOO$wx ??"jj..II488TEVEV`d / G #jjYYDHHVZVgVgjhG")!*//"3KKMGGLLN$$UUDT$U$$_uN_$`+ ,,... KKMr!   )r   r   r   r   r   r   r   r   r   r   r   r   r   )r   N)__name__
__module____qualname____firstlineno____doc__r   r   r,   r8   rb   r   r   r   __static_attributes__r   r!   r   r	   r	      s@    #JD D D:@&*.\2 8DD*- r!   r	   __main__   )r   )rS   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 ; j  j Z z sxx=D!8CHHQKEE$$& r!   