o
    e`                     @   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	m
Z
 d dlmZ d dl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mZmZ d d
lmZ d dlmZ G dd dZ dS )    N)ndarray)Image)tqdm)rfapi)API_URLCLIP_FEATURIZE_URL	DEMO_KEYS)Project)folderparser)check_box_sizeclip_encodecount_comparisons)
write_line)	ocr_inferc                   @   sr  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zd>de	de	de	de
fddZ					d?de	de	dede	dede
fddZ			d@de	de	dede
fddZ			 	!dAd"e	d#e	d$ed%e	d&e	d'e	fd(d)Z		 	!dBd"e	d#e	d$ed&e	d'e	f
d*d+ZdCd,e	d-e	fd.d/Z			 	!dAd"e	d#e	d$ed%e	d&e	d'e	fd0d1Zddg di d2fd3e	d4e	d5ed6e	d7e
d8ede	fd9d:Zd;d< Zd=S )D	Workspacez&
    Manage a Roboflow workspace.
    c                 C   sj   |t v r|| _|| _g | _d S |d }|d | _|d | _d| v r(|d | _|d | _|| _|| _d S )N	workspacenameprojectsmembersurl)r   _Workspace__api_keymodel_formatproject_listr   keysr   r   )selfinfoapi_keydefault_workspacer   workspace_info r   F/var/www/myenv/lib/python3.10/site-packages/roboflow/core/workspace.py__init__   s   





zWorkspace.__init__c                 C   s   t | j dS )zE
        Print all projects in the workspace to the console.
        N)printr   )r   r   r   r    list_projects+   s   zWorkspace.list_projectsc                 C   s0   g }| j D ]}t| j|| j}||j q|S )zp
        Retrieve all projects in the workspace.

        Returns:
            List of Project objects.
        )r   r	   r   r   appendid)r   projects_array	a_projectprojr   r   r    r   1   s
   
zWorkspace.projectsc                 C   s   t jd t jd t j  | jtv rt| ji | jS d|v r+td	|| j
t| j| j
|}|d }t| j|| jS )a  
        Retrieve a Project() object that represents a project in the workspace.

        This object can be used to retrieve the model through which to run inference.

        Args:
            project_id (str): id of the project

        Returns:
            Project Object
        zloading Roboflow project...
/z6The {} project is not available in this ({}) workspaceproject)sysstdoutwriteflushr   r   r	   r   RuntimeErrorformatr   r   get_project)r   
project_iddataset_infor   r   r    r+   ?   s   

zWorkspace.projectc                 C   st   ||||d}t jtd | j d | j |d}|  d|  v r,t| d | 	| d 
dd S )a  
        Create a project in a Roboflow workspace.

        Args:
            project_name (str): name of the project
            project_type (str): type of the project
            project_license (str): license of the project (set to `private` for private projects, only available for paid customers)
            annotation (str): annotation of the project

        Returns:
            Project Object
        )r   typelicense
annotationr*   z/projects?api_key=)jsonerrorr%   )requestspostr   r   r   raise_for_statusr8   r   r0   r+   split)r   project_nameproject_typeproject_licenser7   datarr   r   r    create_project\   s   "zWorkspace.create_project .pngdir	image_exttarget_imagereturnc                 C   sL   g }t  d| d| D ]}t||}|||i t|dd d}q|S )a  
        Compare all images in a directory to a target image using CLIP

        Args:
            dir (str): name reference to a directory of images for comparison
            image_ext (str): file format for expected images (don't include the . before the file type name)
            target_image (str): name reference for target image to compare individual images from directory against

        Returns:
            dict: a key:value mapping of image_name:comparison_score_to_target
        z.//*c                 S   s   t |  d  S )Nr   )listvalues)itemr   r   r    <lambda>   s    z(Workspace.clip_compare.<locals>.<lambda>)key)globr   r$   sorted)r   rG   rH   rI   comparisonsimage
similarityr   r   r    clip_comparey   s   
zWorkspace.clip_comparer   rT   first_stage_model_namefirst_stage_model_versionsecond_stage_model_namesecond_stage_model_versionc                 C   s$  g }t |d}| |}||j}	| |}
|
|j}t| | |	|}|jdkr|
dkr|D ]<}|d |d d  |d |d d  |d |d d  |d |d d  f}|	|}|
d	 ||d	d
  q7ztd	 W |S  ty   td Y |S w tdd |S )ak  
        For each prediction in a first stage detection, perform detection with the second stage model

        Args:
            image (str): name of the image to be processed
            first_stage_model_name (str): name of the first stage detection model
            first_stage_model_version (int): version number for the first stage model
            second_stage_mode (str): name of the second stage detection model
            second_stage_model_version (int): version number for the second stage model

        Returns:
            dict: a json obj containing the results of the second stage detection
        RGBobject-detectionclassificationxwidth   yheightz
./temp.pngr   zno detectionsznplease use an object detection model for the first stage--can only perform two stage with bounding box resultsz6please use a classification model for the second stage)r   openconvertr+   versionmodelr"   predictr5   cropsaver$   osremoveFileNotFoundError)r   rT   rW   rX   rY   rZ   results	pil_imagestage_one_projectstage_one_modelstage_two_projectstage_two_modelpredictionsboundingboxbox
croppedImgr   r   r    	two_stage   s<   





	zWorkspace.two_stagec                 C   s   g }t |d}| |}||j}||}|jdkrZ|D ]6}	|	d |	d d  |	d |	d d  |	d |	d d  |	d |	d d  f}
||
}|	t
|d  q!|S td	 |S )
a  
        For each prediction in the first stage object detection, perform OCR as second stage.

        Args:
            image (str): name of the image to be processed
            first_stage_model_name (str): name of the first stage detection model
            first_stage_model_version (int): version number for the first stage model

        Returns:
            dict: a json obj containing the results of the second stage detection
        r[   r\   r^   r_   r`   ra   rb   rm   zZplease use an object detection model--can only perform two stage with bounding box results)r   rc   rd   r+   re   rf   rg   r5   rh   r$   r   r"   )r   rT   rW   rX   rm   rn   ro   rp   rs   rt   ru   rv   r   r   r    two_stage_ocr   s"   



	zWorkspace.two_stage_ocr
   yolov8MITr\   dataset_pathr?   num_workersdataset_formatrA   r@   c                 C   s.   |dkr|  |||||S | ||||||S )a'  
        Upload a dataset to Roboflow.

        Args:
            dataset_path (str): path to the dataset
            project_name (str): name of the project
            num_workers (int): number of workers to use for parallel uploads
            dataset_format (str): format of the dataset (`voc`, `yolov8`, `yolov5`)
            project_license (str): license of the project (set to `private` for private projects, only available for paid customers)
            project_type (str): type of the project (only `object-detection` is supported)
        auto)_upload_dataset_auto_upload_dataset_legacy)r   r|   r?   r}   r~   rA   r@   r   r   r    upload_dataset  s   zWorkspace.upload_datasetc                    s   t |}| j|||d\}|rtdj  ntdj  |d }|d dd  dd	  fd
d}	tjj|d}
t|
	|	| W d    d S 1 sVw   Y  d S )N)r3   r6   r5   Created project Uploading to existing project imageslocationc                 S   s   | di  d}| di  d}| di  d}| d}|r,d|  d| d}n|r8d	|  d| d}n	d
|  d| d}|rj| drM|d7 }n| dr\|d|d  7 }n| drj|d|d  7 }t| d S )NrT   r%   success	duplicater7   z[DUPLICATE]  ()z[UPLOADED] [ERR] z / annotations = OKwarnz / annotations = WARN: r9   z / annotations = ERR: )getr"   )
image_path	uploadresimage_idimg_successimg_duplicater7   msgr   r   r    _log_img_uploadB  s"   




z7Workspace._upload_dataset_auto.<locals>._log_img_uploadc                 S   s   d|  d| d}t | d S )Nr   r   r   )r"   )r   er   r   r   r    _log_img_upload_errV  s   z;Workspace._upload_dataset_auto.<locals>._log_img_upload_errc              
      s    | d  }| d }d }d }|  d}|r$ |d  }| d}zj||||d} || W d S  tyM } z|| W Y d }~d S d }~ww )Nfiler>   annotationfilelabelmap)r   annotation_pathannotation_labelmapr>   )r   single_upload	Exception)	imagedescr   r>   r   r   annotationdescr   r   r   r   r   r+   r   r    _upload_imageZ  s(   

z5Workspace._upload_dataset_auto.<locals>._upload_imagemax_workers)
r
   parsefolder_get_or_create_projectr"   r%   
concurrentfuturesThreadPoolExecutorrL   map)r   r|   r?   r}   rA   r@   parsed_datasetcreatedr   r   executorr   r   r    r   .  s   

"zWorkspace._upload_dataset_autor6   r5   c              	   C   s>   z
|  |}|dfW S  ty   | j||||ddf Y S w )NF)r?   rA   r7   r@   T)r+   r0   rD   )r   r3   r6   r5   existing_projectr   r   r    r   q  s   

z Workspace._get_or_create_projectc                    sl  |dkrd|dvrt d|dks|dkrIdD ],}tjj|d | d	 |d | d
 |d d}|j|d d | |d d | d q|d }|dd | jD v ra| | td j  n| j	||||d td j  dt
dt
f fddfdd}	td t|d }
|	|
d td t|d }
|	|
d td  t|d! }
|	|
d" d S )#Nr\   z;upload_dataset only supported for object-detection projects)vocrz   yolov5darknetzydataset_format not supported - please use voc, yolov8, yolov5. PS, you can always convert your dataset in the Roboflow UIrz   r   )trainvalidtestr*   z/imagesz/labelsz
/data.yaml)images_directory_pathannotations_directory_pathdata_yaml_path_voc)r   r   c                 S   s   g | ]}|d  qS )r   r   ).0pr   r   r    
<listcomp>  s    z4Workspace._upload_dataset_legacy.<locals>.<listcomp>r   )rA   r7   r@   r   img_filer>   c                    s    |  dd} j| ||d dS )z
            Upload an image or annotation to a project.

            Args:
                img_file (str): path to the image
                split (str): split to which the the image should be added (train, valid, test)
            z.jpgz.xml)r   r   r>   N)replaceupload)r   r>   
label_file)dataset_upload_projectr   r    upload_file  s   z5Workspace._upload_dataset_legacy.<locals>.upload_filec              
      s`   t jj d}tt|| |gt|  t| tjd W d    d S 1 s)w   Y  d S )Nr   )totalr   )	r   r   r   rL   r   r   lenr,   r-   )	file_listr>   r   )r}   r   r   r    parallel_upload  s   "z9Workspace._upload_dataset_legacy.<locals>.parallel_uploadzuploading training set...z/train/*.jpgr   zuploading validation set...z/valid/*.jpgr   zuploading test set...z/test/*.jpgr   )r   svDetectionDataset	from_yoloas_pascal_vocr   r+   r"   r%   rD   strr   rQ   )r   r|   r?   r}   r~   rA   r@   r>   datasetr   r   r   )r   r}   r   r    r     sN   	



z Workspace._upload_dataset_legacyFraw_data_locationraw_data_extensioninference_endpointupload_destinationconditionalsuse_localhostc              	   C   s
  g }d|vrg n|d |d< d|vrddgn|d |d< d|vr"dn|d |d< d|vr.dn|d |d< d|vr:d	n|d |d< d
|vrHt dn|d
 |d
< d|vrVt dn|d |d< |r`dnd}| |d	 j|d |dj}	| |}
td|	 td|
 t|ttu r|g}n	t|d | }|d	 }d	}t|D ]\}}ztdt	|d  d t	t
| d | d  W n	 ty   Y nw d| v r|}t||t}|d7 }||d ks||d kr|}d	}n	t|d |  q|	| d }|||d t||d |d |d std qt|D ]Y\}}t| t||d
 |d s4td q|d d  |d d	 krs|d d  |d d krst
|d d	krf|d! |d vrftd" qtd# |
j|d$d%  nqqt|tur|S |d& d S )'a"  perform inference on each image in directory and upload based on conditions
        @params:
            raw_data_location: (str) = folder of frames to be processed
            raw_data_extension: (str) = extension of frames to be processed
            inference_endpoint: (List[str, int]) = name of the project
            upload_destination: (str) = name of the upload project
            conditionals: (dict) = dictionary of upload conditions
            use_localhost: (bool) = determines if local http format used or remote endpoint
        target_classesconfidence_interval   c   required_class_variance_count   required_objects_countrequired_class_countr   minimum_size_requirementz-infmaximum_size_requirementinfzhttp://localhost:9001/N)version_numberlocalzinference reference point: zupload destination: rK   z*** Processing image [r*   z] - z ***similarity_confidence_thresholdsimilarity_timeout_limitz  --> similarity too high to --> rs   )rT   rs   z [X] image failed count casesz% [X] prediction failed box size cases
confidenced   classz% [X] prediction failed target_classesz >> image uploaded!   )num_retry_uploadsr:   )floatr+   re   rf   r"   r5   r   rQ   	enumerater   r   r   r   r   r   rg   r8   r$   r   r   r   )r   r   r   r   r   r   r   prediction_resultsr   inference_modelupload_projectglobbed_filesimage1similarity_timeout_counterindexrT   image2rU   rs   i
predictionr   r   r    active_learning  s   


*zWorkspace.active_learningc                 C   s&   |   }| j| j|d}tj|ddS )N)r   r   r   r`   )indent)r   r   r   r8   dumps)r   r   
json_valuer   r   r    __str__Z  s   zWorkspace.__str__N)rE   rF   rE   )rE   rE   r   rE   r   )rE   rE   r   )ry   rz   r{   r\   )ry   r{   r\   )r{   r\   )__name__
__module____qualname____doc__r!   r#   r   r+   rD   r   dictrV   intrw   rx   r   r   r   r   rL   boolr   r   r   r   r   r    r      s    
J
9
$
C
Q
 r   )!concurrent.futuresr   rQ   r8   rj   r,   r;   supervisionr   numpyr   PILr   r   roboflow.adaptersr   roboflow.configr   r   r   roboflow.core.projectr	   roboflow.utilr
   #roboflow.util.active_learning_utilsr   r   r   roboflow.util.generalr   roboflow.util.two_stage_utilsr   r   r   r   r   r    <module>   s$    