o
    e"V                     @   s   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z
d dlZd dlZd dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ d dlmZ G dd	 d	eZdS )
    NImage)API_URLOBJECT_DETECTION_MODELOBJECT_DETECTION_URL)InferenceModel)check_image_url)PredictionGroup)*print_warn_for_wrong_dependencies_versionsc                       s   e Zd ZdZ											d fdd		Z							dd
dZ							dddZ								d ddZd!ddZd"ddZ									d#ddZ
dd Z  ZS )$ObjectDetectionModelzm
    Run inference on an object detection model hosted on Roboflow or served through Roboflow Inference.
    N   (      Fjsonc                    s   t t| || || _|| _|| _|p| j| _|| _|| _|| _	|	| _
|
| _|| _|du r0i n|| _|du r9i n|| _|du rFtd | _n	td|  || _|dur]|dur_|   dS dS dS )a  
        Create a ObjectDetectionModel object through which you can run inference.

        Args:
            api_key (str): Your API key (obtained via your workspace API settings page).
            name (str): The url-safe version of the dataset name. You can find it in the web UI by looking at
                        the URL on the main project view or by clicking the "Get curl command" button in the train
                        results section of your dataset version after training your model.
            local (str): Address of the local server address if running a local Roboflow deployment server.
                        Ex. http://localhost:9001/
            version (str): The version number identifying the version of your dataset.
            classes (str): Restrict the predictions to only those of certain classes. Provide as a comma-separated string.
            overlap (int): The maximum percentage (on a scale of 0-100) that bounding box predictions of the same class are
                        allowed to overlap before being combined into a single box.
            confidence (int): A threshold for the returned predictions on a scale of 0-100. A lower number will return
                            more predictions. A higher number will return fewer high-certainty predictions.
            stroke (int): The width (in pixels) of the bounding box displayed around predictions (only has an effect when
                        format is image).
            labels (bool): Whether or not to display text labels on the predictions (only has an effect when format is
                        image).
            format (str): The format of the output.
                        - 'json': returns an array of JSON predictions (See response format tab).
                        - 'image': returns an image with annotated predictions as a binary blob with a Content-Type
                                    of image/jpeg.
        N/z4initalizing local object detection model hosted at :)superr   __init___ObjectDetectionModel__api_keyidnameversionclassesoverlap
confidencestrokelabelsformatcolorspreprocessingr   base_urlprint#_ObjectDetectionModel__generate_url)selfapi_keyr   r   r   localr   r   r   r   r   r   r   r   	__class__ O/var/www/myenv/lib/python3.10/site-packages/roboflow/models/object_detection.pyr      s(   +zObjectDetectionModel.__init__c
           
   	   C   s(   || _ || _| j|||||||	d dS )a-  
        Loads a Model from on a model endpoint.

        Args:
            name (str): The url-safe version of the dataset name
            version (str): The version number identifying the version of your dataset.
            local (bool): Whether the model is hosted locally or on Roboflow
        )r$   r   r   r   r   r   r   N)r   r   r!   )
r"   r   r   r$   r   r   r   r   r   r   r'   r'   r(   
load_model`   s   
zObjectDetectionModel.load_modelc	                 C   s  | j ||||||d t|ddu rn| j|d d}	|st|trt|d}
|
j}t	
|}d| j v rm|d t| jd d	 ksS|d
 t| jd d krm|
t| jd d	 t| jd d f}
|
j}d}	t }|
j|dd t| }|d}tj| j|ddid}t|d t|d
 d}nHt|tjrtd|\}}|j}t|}|d}tj| j|ddid}ddd}ntd|  jdtj !| 7  _ddd}t| j}|"  | j#dkro|$ }|	rdg }|d D ]c}t|d t|d t| jd d	   |d< t|d t|d
 t| jd d   |d< t|d	 t|d t| jd d	   |d	< t|d t|d
 t| jd d   |d< |%| q||d< t&j'||t(|| j)dS | j#dkrx|j*S dS )a  
        Infers detections based on image from specified model and image path.

        Args:
            image_path (str): path to the image you'd like to perform prediction on
            hosted (bool): whether the image you're providing is hosted on Roboflow
            format (str): The format of the output.

        Returns:
            PredictionGroup Object

        Example:
            >>> import roboflow

            >>> rf = roboflow.Roboflow(api_key="")

            >>> project = rf.workspace().project("PROJECT_ID")

            >>> model = project.version("1").model

            >>> prediction = model.predict("YOUR_IMAGE.jpg")
        )r   r   r   r   r   r   __len__T)image_path_checkFRGBresizer   widthr   heightPNG)r   asciiContent-Type!application/x-www-form-urlencodeddataheaders)r.   r/   z.jpg0z-image_path must be a string or a numpy array.z&image=r   predictionsxy)
image_pathprediction_type
image_dimsr   imageN)+r!   hasattr&_ObjectDetectionModel__exception_check
isinstancestrr   openconvertsizecopydeepcopyr   keysintr-   ioBytesIOsavebase64	b64encodegetvaluedecoderequestspostapi_urlnpndarraycv2imencodeshape
ValueErrorurllibparse
quote_plusraise_for_statusr   r   appendr	   create_prediction_groupr   r   content)r"   r;   hostedr   r   r   r   r   r   r-   r>   
dimensionsoriginal_dimensionsbufferedimg_strrespr=   retvalbuffer	resp_json	new_predspr'   r'   r(   predict   s   "


"





..$$zObjectDetectionModel.predictr   https://detect.roboflow.com/  ro   c	                    sP  dt jd< j|||||d dfdd	t|du s# s+tdt| tj	d  tj
d	  rtdt jd< td
g tdg ddl}	ddl}
ddlm  ddlm} |ddd|
jdddddddntdtj t  d fdd}r| |	j|fd}|  dS | dS )ae  
        Infers detections based on webcam feed from specified model.

        Args:
            webcam_id (int): Webcam ID (default 0)
            inference_engine_url (str): Inference engine address to use (default https://detect.roboflow.com)
            within_jupyter (bool): Whether or not to display the webcam within Jupyter notebook (default True)
            confidence (int): Confidence threshold for detections
            overlap (int): Overlap threshold for detections
            stroke (int): Stroke width for bounding box
            labels (bool): Whether to show labels on bounding box
        r7   OPENCV_VIDEOIO_PRIORITY_MSMF)r   r   r   r   inference_engine_urlNc              
      sv  |d u ri n|_ || v r(|d ur(||   d t fdddD  n	dd tdD  |pDtd|jd	 |jd
   d d
 }t| d	 t| d
 ft| d t| d f}}tj	||| |tj
d |rt|d
 d
}	tj|d	|d |	dd	 }
|d	 |
d	  |d
 |
d
  d f}t	||| dtj
 tj|||d	 |d
 d fd	|d g d|	tj
d d S d S )N#c                 3   s&    | ]}t  ||d   dV  qdS )      N)rI   ).0icolorr'   r(   	<genexpr>>  s   $ zDObjectDetectionModel.webcam.<locals>.plot_one_box.<locals>.<genexpr>)r   rs      c                 S   s   g | ]}t d dqS )r      )randomrandint)ru   _r'   r'   r(   
<listcomp>@  s    zEObjectDetectionModel.webcam.<locals>.plot_one_box.<locals>.<listcomp>   gMb`?r   r   rs   )	thicknesslineType)	fontScaler   )   r{   r{   )r   rH   lstriptuplerangeroundrX   rI   rV   	rectangleLINE_AAmaxgetTextSizeputText)r9   imgrx   labelline_thicknessr   tlc1c2tft_size)r"   rw   r(   plot_one_box6  s2   
(2$
z1ObjectDetectionModel.webcam.<locals>.plot_one_boxz!No webcam available at webcam_id r   r   )IPython>=7.0.0)
ipywidgetsr   r   r   )displayzloading Roboflow model...T)
display_idFzStop InferencedangerDescriptionsquare)valuedescriptiondisabledbutton_styletooltipiconRoboflow Webcam Inferencec                    s  	 d urj du rnntdd@ tdkrn͈ \}}t|}t|d}td|\}}t	|}|
d}tjj|ddid	}| }|d
 }g }g }	|D ]c}
|
d |
d |
d |
d |
d g}t|d |
d d  |d< t|d |
d d  |d< t|d |
d d  |d< t|d |
d d  |d< || |	|
d  |||
d djd qUtd|\}}rΈ | d ntd| tdd@ tdkr  nq  std t  td d S )NTr   r{   qz.jpegr1   r2   r3   r4   r8   r9   r:   r   r   r.   rs   r/   r   class)r   r   r   )r5   r   )r   rV   waitKeyordreadr-   fliprW   rM   rN   rP   rQ   rR   rS   r   rI   r^   r   updatetobytesimshowreleasedestroyWindowdestroyAllWindows)buttonr~   frameframe_uploadre   rr   r8   formatted_predictionsr   predformatted_predframe_displayIPythonImagecapdisplay_handler   r"   
stopButtonweb_cam_reswithin_jupyterr'   r(   view}  sp   


	
C

z)ObjectDetectionModel.webcam.<locals>.view)targetargs)NNNN)osenvironr!   rV   VideoCaptureisOpened	ExceptionrB   setCAP_PROP_FRAME_WIDTHCAP_PROP_FRAME_HEIGHTr
   	threadingr   IPython.displayr   r   ToggleButtonnamedWindowWINDOW_NORMALstartWindowThreadThreadstart)r"   	webcam_idrq   r   r   r   r   r   r   r   widgetsr   r   threadr'   r   r(   webcam  sP   

!



LzObjectDetectionModel.webcampt.c                    s   dg}||vrt d| d| | jd\}}}t d| d| d| j d}tj|d| jid}|  |	 d }	d fd
d	}
tj|	dd}t
 d d4}t|jd}t|jddd  dt|d d dD ]}|r}|| |  qpW d   dS 1 sw   Y  dS )a  
        Download the weights associated with a model.

        Args:
            format (str): The format of the output.
                        - 'pt': returns a PyTorch weights file
            location (str): The location to save the weights file to
        r   zUnsupported format z. Must be one of r   z/ptFiler#   )params
weightsUrlP   c                    s@   d  d d| | d | |f  }t jd|  t j  d S )NDownloading weights to /weights.ptz: %d%% [%d / %d] bytesd   )sysstdoutwriteflush)currenttotalr.   progress_messagelocationr'   r(   bar_progress  s   z3ObjectDetectionModel.download.<locals>.bar_progressT)streamr   wbzcontent-lengthi   )
chunk_sizer   r   )descr   N)r   )r   r   rsplitr   r   rQ   getr   r]   r   rC   rI   r6   tqdmiter_contentr   r   )r"   r   r   supported_formats	workspaceprojectr   
pt_api_urlr   pt_weights_urlr   responseftotal_lengthchunkr'   r   r(   download  s4   	





zObjectDetectionModel.downloadc                 C   s8   |d urt j|st|std| d d S d S d S )NzImage does not exist at !)r   pathexistsr   r   )r"   r+   r'   r'   r(   __exception_check  s
   z&ObjectDetectionModel.__exception_checkc	                 C   s"  |dur|st d | _nd| _|dur|| _|dur|| _|dur$|| _|dur+|| _|dur2|| _|dur9|| _|dur@|| _| j	d}	|	d }
d
| j|
 d t| j d| j ddt| j d	t| j d
t| j dt| j  d| j g| _| jdur|  jd| j 7  _dS dS )z7
        Generate the URL to run inference on.
        Nr   zhttp://localhost:9001/r    z	?api_key=z&name=YOUR_IMAGE.jpgz	&overlap=z&confidence=z&stroke=z&labels=z&format=z	&classes=)r   r   r   r   r   r   r   r   r   r   joinrB   r   r   lowerrS   )r"   r$   r   r   r   r   r   r   rq   splittedwithout_workspacer'   r'   r(   __generate_url	  sD   
z#ObjectDetectionModel.__generate_urlc                 C   s\   | j d}|d }|d t| j | j| j| j| j| j| j| j	| j
| jd
}tj|ddS )Nr   r   )
r   r   r   r   r   r   r   r   r   r   rs   )indent)r   r   rB   r   r   r   r   r   r   r   r   r   r   dumps)r"   r  r  
json_valuer'   r'   r(   __str__C  s   zObjectDetectionModel.__str__)NNNNr   r   r   Fr   NN)NNNNNNN)FNNr   r   r   F)r   rm   Fr   r   r   Frn   )r   r   )N)NNNNNNNN)__name__
__module____qualname____doc__r   r)   rl   r   r   r@   r!   r  __classcell__r'   r'   r%   r(   r      sj    H
%
 
 
>
2	
:r   )rM   rF   rJ   r   r   r|   r   rZ   rV   numpyrT   rQ   r   PILr   roboflow.configr   r   r   roboflow.models.inferencer   roboflow.util.image_utilsr   roboflow.util.predictionr	   roboflow.util.versionsr
   r   r'   r'   r'   r(   <module>   s&    