o
    eF\                     @   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mZm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	gZd
d Zee_G dd dZdS )    N)ImageUnidentifiedImageError)rfapi)API_URLDEFAULT_BATCH_NAME	DEMO_KEYS)Version)retry)load_labelmapPNGJPEGc                 O   s   t | d S )N
)str)msgargskwargs r   D/var/www/myenv/lib/python3.10/site-packages/roboflow/core/project.pycustom_formatwarning   s   r   c                   @   s  e Zd ZdZdEdededefddZdd	 Zd
d Zdd Zdd Z	ddddddi ddddfde
fddZdEdedefddZdefdd Zddddd!d"eg df	ded#ed$e
d%ed&ed'ed(ed)ed*e
fd+d,Zdddddd!d"eg df
d*e
fd-d.Zd/d0 Zddd"d1dddddg d2f
d3ed4ed5ed6ed7ed8ed9ed:e
d;ed<efd=d>Zddd"d1dddddd?d@gf
d3ed4ed5ed6ed7ed8ed9ed:e
d;ed<efdAdBZdCdD ZdS )FProjectz
    A Roboflow Project.
    Napi_key	a_projectmodel_formatc                 C   s   |t v r|| _|| _dS || _|d | _|d | _|d | _tj|d | _|d | _	|d | _
|d | _|d | _|d	 | _|d
 | _|d | _tj|d | _|| _| j	d}|d | _|d | _dS )a  
        Create a Project object that represents a Project associated with a Workspace.

        Args:
            api_key (str): private roboflow api key
            a_project (str): the project id
            model_format (str): the model format of the project

        Example:
            >>> import roboflow

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

            >>> project = rf.workspace().project("PROJECT_ID")
        
annotationclassescolorscreatedidimagesnamepublicsplitstypeunannotatedupdated/r      N)r   _Project__api_keyr   r   r   r   datetimefromtimestampr   r   r   r   r    r!   r"   r#   r$   rsplit_Project__workspace_Project__project_name)selfr   r   r   tempr   r   r   __init__    s(   











zProject.__init__c                 C   sL   t td | j d | j d | j }|jdkrt|j|	 }|d S )ab  
        Retrieve all versions of a project.

        Returns:
            A list of all versions of the project.

        Example:
            >>> import roboflow

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

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

            >>> version_info = project.get_version_information()
        r%   z	?api_key=   versions)
requestsgetr   r+   r,   r'   status_codeRuntimeErrortextjson)r-   dataset_infor   r   r   get_version_informationG   s    

zProject.get_version_informationc                 C   s   |   }t| dS )a  
        Print out versions for that specific project.

        Example:
            >>> import roboflow

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

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

            >>> project.list_versions()
        N)r9   print)r-   version_infor   r   r   list_versionsb   s   zProject.list_versionsc                 C   sb   |   }g }|D ]&}t|d|v r| jnd| j| j|d | jd| j| j| j| j	d}|
| q|S )aV  
        Return all versions in the project as Version objects.

        Returns:
            A list of Version objects.

        Example:
            >>> import roboflow

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

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

            >>> versions = project.versions()
        modelNr   local	workspaceprojectr    r   )r9   r   r"   r'   r   r   r+   r,   r    r   append)r-   r;   version_array	a_versionversion_objectr   r   r   r1   r   s$   zProject.versionsc                 C   s   ddh|  kstdtjt d| j d| j d| j |d}z| }W n	 t	y0   dw |j
dkr[tjd	|d
  d t|d  d  tjd tj  t|d S d|  v rgt|d tt|)a  
        Generate a version of a dataset hosted on Roboflow.

        Args:
            settings: A Python dict with augmentation and preprocessing keys and specifications for generation. These settings mirror capabilities available via the Roboflow UI.
                    For example:
                        {
                            "augmentation": {
                                "bbblur": { "pixels": 1.5 },
                                "bbbrightness": { "brighten": true, "darken": false, "percent": 91 },
                                "bbcrop": { "min": 12, "max": 71 },
                                "bbexposure": { "percent": 30 },
                                "bbflip": { "horizontal": true, "vertical": false },
                                "bbnoise": { "percent": 50 },
                                "bbninety": { "clockwise": true, "counter-clockwise": false, "upside-down": false },
                                "bbrotate": { "degrees": 45 },
                                "bbshear": { "horizontal": 45, "vertical": 45 },
                                "blur": { "pixels": 1.5 },
                                "brightness": { "brighten": true, "darken": false, "percent": 91 },
                                "crop": { "min": 12, "max": 71 },
                                "cutout": { "count": 26, "percent": 71 },
                                "exposure": { "percent": 30 },
                                "flip": { "horizontal": true, "vertical": false },
                                "hue": { "degrees": 180 },
                                "image": { "versions": 32 },
                                "mosaic": true,
                                "ninety": { "clockwise": true, "counter-clockwise": false, "upside-down": false },
                                "noise": { "percent": 50 },
                                "rgrayscale": { "percent": 50 },
                                "rotate": { "degrees": 45 },
                                "saturation": { "percent": 50 },
                                "shear": { "horizontal": 45, "vertical": 45 }
                            },
                            "preprocessing": {
                                "auto-orient": true,
                                "contrast": { "type": "Contrast Stretching" },
                                "filter-null": { "percent": 50 },
                                "grayscale": true,
                                "isolate": true,
                                "remap": { "original_class_name": "new_class_name" },
                                "resize": { "width": 200, "height": 200, "format": "Stretch to" },
                                "static-crop": { "x_min": 10, "x_max": 90, "y_min": 10, "y_max": 90 },
                                "tile": { "rows": 2, "columns": 2 }
                            }
                        }

        Returns:
            int: The version number that is being generated.

        Example:
            >>> import roboflow

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

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

            >>> versions = project.generate_version(settings={...})
        augmentationpreprocessingz~augmentation and preprocessing keys are required to generate. If none are desired specify empty dict associated with that key.r%   z/generate?api_key=r7   z<Error when requesting to generate a new version for project.r0   messagez for new version version.r   error)keysr5   r2   postr   r+   r,   r'   r7   	Exceptionr4   sysstdoutwriter   flushintdumps)r-   settingsrr_jsonr   r   r   generate_version   s,   <
(
zProject.generate_versionTi  z
Stretch to)widthheightformat)zauto-orientresize)rG   rF   Freturnc                 C   s*   | j |d}| |}|j|||d}|S )aY  
        Ask the Roboflow API to train a previously exported version's dataset.

        Args:
            speed: Whether to train quickly or accurately. Note: accurate training is a paid feature. Default speed is `fast`.
            checkpoint: A string representing the checkpoint to use while training
            plot: Whether to plot the training loss curve. Default is False.

        Returns:
            True

        Raises:
            RuntimeError: If the Roboflow API returns an error with a helpful JSON body
            HTTPError: If the Network/Roboflow API fails and does not return JSON

        Example:
            >>> import roboflow

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

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

            >>> version = project.version(1)

            >>> version.train()
        )rW   )speed
checkpointplot_in_notebook)rZ   rK   train)r-   new_version_settingsr`   ra   rb   new_version	new_modelr   r   r   rc      s   (
zProject.trainversion_numberr?   c                 C   s   | j tv r d}| j dkrd}nd}ti d| j ||| jdddd	S |  }|D ]+}tj|d }|t|krQt|| j	| j | j
|| j|| j| j| j| jd	}|  S q&td
|)aZ  
        Retrieves information about a specific version and returns a Version() object.

        Args:
            version_number (int): the version number that you want to retrieve
            local (str): specifies the localhost address and port if pointing towards local inference engine

        Returns:
            Version() object
         zcoco-128-samplezcoco-128zchess-pieces-newr"   N)r?   r@   rA   r   r>   zVersion number {} is not found.)r'   r   r   r   r9   ospathbasenamer   r"   r   r+   r,   r    r   r5   r]   )r-   rg   r?   r   r;   rE   current_version_numversr   r   r   rK     sH   

zProject.version
image_pathc                 C   s8   zt |}|jtv }|  W |S  ty   Y dS w )z
        Check if an image is valid. Useful before attempting to upload an image to Roboflow.

        Args:
            image_path (str): path to image you'd like to check

        Returns:
            bool: whether the image is valid or not
        F)r   openr]   ACCEPTED_IMAGE_FORMATScloser   )r-   rn   imgvalidr   r   r   check_valid_imageQ  s   



zProject.check_valid_imagerc   r   annotation_pathhosted_imageimage_idsplitnum_retry_uploads
batch_name	tag_namesis_predictionc
                 K   s  | dp	| d}tj|p|}tj|}|s#|s#td||rM|p+| |}|s9td|dt	| j
d|||||||||	d	|
 dS t|}|D ]0}|d | }| |r|| j
d|||||||||	d	|
 td| d	  qTtd| d
  qTdS )a  
        Upload an image or annotation to the Roboflow API.

        Args:
            image_path (str): path to image you'd like to upload
            annotation_path (str): if you're upload annotation, path to it
            hosted_image (bool): whether the image is hosted
            image_id (str): id of the image
            split (str): to upload the image to
            num_retry_uploads (int): how many times to retry upload on failure
            batch_name (str): name of batch to upload to within project
            tag_names (list[str]): tags to be applied to an image
            is_prediction (bool): whether the annotation data is a prediction rather than ground truth

        Example:
            >>> import roboflow

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

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

            >>> project.upload(image_path="YOUR_IMAGE.jpg")
        zhttp://zhttps://zeThe provided image path [ {} ] is not a valid path. Please provide a path to an image or a directory.zSThe image you provided {} is not a supported file format. We currently support: {}.z, )	rn   ru   rv   rw   rx   ry   rz   r{   r|   r%   z[ z ] was uploaded succesfully.z ] was skipped.Nr   )
startswithri   rj   isfileisdirr5   r]   rt   joinrp   single_uploadlistdirr:   )r-   rn   ru   rv   rw   rx   ry   rz   r{   r|   r   	is_hostedis_fileis_diris_imager   imagerj   r   r   r   uploadd  sb   %




zProject.uploadc              
   K   s   | j dd }|r|rtd|s|stdt|tr!t|}d\}}|r?t|ttj| j	||f||||	d|}|d }|rn| 
|\}}ztj| j	|||||
|d}W n tym } z
d	|i}W Y d }~nd }~ww ||d
S )Nr%   r&   z+You can't pass both image_id and image_pathz'You need to pass image_path or image_idNN)rv   rx   rz   r{   r   )r|   annotation_labelmaprM   )r   r   )r   r*   rP   
isinstancer   r
   r	   r   upload_imager'   _annotation_paramssave_annotationBaseException)r-   rn   ru   r   rv   rw   rx   ry   rz   r{   r|   r   project_urluploaded_imageuploaded_annotationannotation_nameannotation_strer   r   r   r     sT   

	
zProject.single_uploadc                 C   s   d\}}t j|r0t|d t|d }W d    n1 s!w   Y  t j|}||fS | jdkrEtd| d |}|}||fS td| )Nr   rX   classificationz	-> using z( as classname for classification projectzVFile not found or uploading to non-classification type project with invalid string. - )	ri   rj   existsro   readrk   r"   r:   rP   )r-   ru   r   annotation_stringr   r   r   r     s"   

zProject._annotation_paramsd   )r   r   r   labels
like_imagepromptoffsetlimittag
class_name
in_datasetbatchbatch_idfieldsc                 C   s   i }|dur
||d< |dur||d< |dur||d< |dur"||d< |dur*||d< |dur2||d< |dur:||d< |durB||d	< |	durJ|	|d
< |
|d< t jtd | j d | j d | j |d}| d S )a  
        Search for images in a project.

        Args:
            like_image (str): name of an image in your dataset to use if you want to find images similar to that one
            prompt (str): search prompt
            offset (int): offset of results
            limit (int): limit of results
            tag (str): tag that an image must have
            class_name (str): class name that an image must have
            in_dataset (str): dataset that an image must be in
            batch (bool): whether the image must be in a batch
            batch_id (str): batch id that an image must be in
            fields (list): fields to return in results (default: ["id", "created", "name", "labels"])

        Returns:
            A list of images that match the search criteria.

        Example:
            >>> import roboflow

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

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

            >>> results = project.search(query="cat", limit=10)
        Nr   r   r   r   r   r   r   r   r   r   r%   z/search?api_key=rH   results)r2   rO   r   r+   r,   r'   r7   )r-   r   r   r   r   r   r   r   r   r   r   payloaddatar   r   r   search  s2   ( zProject.searchr   r   c                 c   sB    	 | j |||||||||	|
d
}|V  t||k rdS ||7 }q)a  
        Create a paginated list of search results for use in searching the images in a project.

        Args:
            like_image (str): name of an image in your dataset to use if you want to find images similar to that one
            prompt (str): search prompt
            offset (int): offset of results
            limit (int): limit of results
            tag (str): tag that an image must have
            class_name (str): class name that an image must have
            in_dataset (str): dataset that an image must be in
            batch (bool): whether the image must be in a batch
            batch_id (str): batch id that an image must be in
            fields (list): fields to return in results (default: ["id", "created", "name", "labels"])

        Returns:
            A list of images that match the search criteria.

        Example:
            >>> import roboflow

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

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

            >>> results = project.search_all(query="cat", limit=10)

            >>> for result in results:

            >>>     print(result)
        T)
r   r   r   r   r   r   r   r   r   r   N)r   len)r-   r   r   r   r   r   r   r   r   r   r   r   r   r   r   
search_allU  s&   ,zProject.search_allc                 C   s    | j | j| jd}tj|ddS )zC
        Show a string representation of a Project object.
        )r   r"   r@      )indent)r   r"   r+   r7   rV   )r-   json_strr   r   r   __str__  s   zProject.__str__)N)__name__
__module____qualname____doc__r   r/   r9   r<   r1   rZ   boolrc   rU   rK   rt   r   listr   r   r   r   r   r   r   r   r   r   r      s    '#^

.4	

^
6	

P	

Ar   )r(   r7   ri   rQ   warningsr2   PILr   r   roboflow.adaptersr   roboflow.configr   r   r   roboflow.core.versionr   roboflow.util.generalr	   roboflow.util.image_utilsr
   rp   r   formatwarningr   r   r   r   r   <module>   s     