o
    e=o                     @   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 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mZmZmZmZ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 d d
l m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z'm(Z( e  G dd dZ)de*de*fddZ+dS )    N)import_module)load_dotenv)tqdm)API_URLAPP_URL	DEMO_KEYSTYPE_CLASSICATIONTYPE_INSTANCE_SEGMENTATIONTYPE_OBJECT_DETECTIONTYPE_SEMANTIC_SEGMENTATIONUNIVERSE_URL)Dataset)ClassificationModel)InstanceSegmentationModel)ObjectDetectionModel)SemanticSegmentationModel)amend_data_yaml)
write_line)get_wrong_dependencies_versions*print_warn_for_wrong_dependencies_versionsc                   @   s   e Zd ZdZ	d'ddZdd Zd(dd	Zd)defddZd'ddZ	d*defddZ
dededdfddZdd Zdd Zdd Zdd Zdd  Zd!ed"efd#d$Zd%d& ZdS )+Versionz8
    Class representing a Roboflow dataset version.
    Nc              	   C   s  |t v r'|dkr|| _|| _d| _d| _dS || _|| _d| _d| _d| _dS || _|| _t|d| _|| _|d | _|d	 | _	|d
 | _|d | _
|d | _|d | _|| _|| _|	| _|
| _|du rfi n|| _|| _d| v rx|d | _ng | _tjt|}| jtkrt| j| j| j||| j| jd| _dS | jtkrt| j| j| j||| j| jd| _dS | jtkrt| j| j| j| j|d| _dS | jtkrt| j| j| _dS d| _dS )z.
        Initialize a Version object.
        coco-128-samplezcoco-1281zchess-pieces-new23zjoseph-nelson/chess-pieces-new
version_idaugmentationcreatedidimagespreprocessingsplitsNexports)localcolorsr    )r$   r    r#   ) r   _Version__api_keymodel_formatnameversionr   unwrap_version_idtyper   r   r   r    r!   	workspaceprojectpublicr$   keysr"   ospathbasenamestrr
   r   modelr   r   r	   r   r   r   )selfversion_dictr*   api_keyr'   r(   r&   r#   r+   r,   r-   r$   version_without_workspace r8   D/var/www/myenv/lib/python3.10/site-packages/roboflow/core/version.py__init__*   s|   









	
	

zVersion.__init__c                 C   s   t  d| j d| j d| j d}tj|d| jid}|  | d d d u r,d}n
t	| d d }| d d |fS )	N/?nocache=truer6   paramsr(   progressg        
generating)
r   r+   r,   r(   requestsgetr%   raise_for_statusjsonfloat)r4   urlresponser?   r8   r8   r9   __check_if_generating   s   "zVersion.__check_if_generatingFc                 C   sx   |   \}}|r-dtt|d d d }tjd|  tj  td | j	ddS |r:tjd	 tj  d S )
Nz0Generating version still in progress. Progress: d      %   T)recurse
)
_Version__check_if_generatingr2   roundsysstdoutwriteflushtimesleep_Version__wait_if_generating)r4   rN   still_generatingr?   progress_messager8   r8   r9   __wait_if_generating   s   


zVersion.__wait_if_generatingT	overwritec                 C   sN  |    |dkr!ztd tdg W n ty    td Y nw | |}|| jvr0| | |du r8|  }t	j
|rM|sMt| j| j|t	j
|S | jdkrUd}n2| |}tj|d| jid	}|jd
krr| d d }nzt|  tjy   |  Y nw | ||| | || | || t| j| j|t	j
|S )a#  
        Download and extract a ZIP of a version's dataset in a given format

        :param model_format: A format to use for downloading
        :param location: An optional path for saving the file
        :param overwrite: An optional flag to prevent dataset overwrite when dataset is already downloaded

        Args:
            model_format (str): A format to use for downloading
            location (str): An optional path for saving the file
            overwrite (bool): An optional flag to prevent dataset overwrite when dataset is already downloaded

        Returns:
            Dataset Object

        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
        yolov8ultralyticsr^   z==z8.0.196z[WARNING] we noticed you are downloading a `yolov8` datasets but you don't have `ultralytics` installed. Roboflow `.deploy` supports only models trained with `ultralytics==8.0.196`, to intall it `pip install ultralytics==8.0.196`.Nr   z5https://app.roboflow.com/ds/n9QwXwUK42?key=NnVCe2yMxPr6   r=      exportlink)rX   r   r   ImportErrorprint_Version__get_format_identifierr"   ra   _Version__get_download_locationr/   r0   existsr   r'   r(   abspathr%   _Version__get_download_urlrA   rB   status_coderD   RuntimeErrorJSONDecodeErrorrC   _Version__download_zip_Version__extract_zip_Version__reformat_yaml)r4   r&   locationr\   rb   rF   rG   r8   r8   r9   download   sB   





zVersion.downloadc                 C   sR  |  |}|   | |}tj|d| jid}|js0zt|  tj	y/   |
  Y nw |jdkryd}|dkrytd tj|d| jid}|j}|dkru| d }d| d tt|d d	 d
 }tjd|  tj  |dks;|jdkrtjd td| d  tj  dS zt|  tj	y   |
  Y dS w )aI  
        Ask the Roboflow API to generate a version's dataset in a given format so that it can be downloaded via the `download()` method.

        The export will be asynchronously generated and available for download after some amount of seconds - depending on dataset size.

        Args:
            model_format (str): A format to use for downloading

        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
        r6   r=         r?   zExporting format z in progress : rI   rJ   rK   rL   r`   rO   zVersion export complete for z formatTN)re   rX   ri   rA   rB   r%   okrk   rD   rl   rC   rj   rV   rW   r2   rQ   rR   rS   rT   rU   rd   )r4   r&   rF   rG   status_code_checkr?   rZ   r8   r8   r9   ra      sB   



 


zVersion.exportreturnc                    sD  |    d}| jtkrd}| jtkrd}| jtkrd}|| jvr%| | | jd^}}}t	 d| d| d| j
 d}i }	|rE||	d< |rK||	d< td tj||	d	| jid
}
|
jsrzt|
  tjyq   |
  Y nw d}|rddlm  ddlm d/ fdd	}d}g }g }|dks|dkrt	 d| j d| j d| j
 d}tj|d	| jid}
|
  |
 d }d| v r|d }ni }d| v rd|d  v rd}	 | j&S d|d  v r|d d dkrtdd 	 | j&S d| v r,td d! |d d" D }td#d! |d d" D }td$d! |d d" D }d%}n|d& t|d'kr;d&g}d(d | }g }g }g }t|t|ksXt|dkr|rc||||| n*t|dkr|d) t!|d*  d+ t!|d*  d, t!|d*  }|st| d-}t"#|}t$%d' |dks|dks| j&S )0a  
        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 results. Default is `False`.

        Returns:
            An instance of the trained model class

        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
        yolov5pytorchfolderzpng-mask-semanticr;   z/trainspeed
checkpointz-Reaching out to Roboflow to start training...r6   )rD   r>   trainingr   )clear_output)pyplot c                    sv    dd  ddd | |d | d  ddd | |d d d	   d S )
NT)waitrJ   rs   z#00FFCEmAPz#A351FBepochsloss)subplotplottitleylabelxlabelshow)r   r   r   r   r|   pltr8   r9   	live_plotU  s   




z Version.train.<locals>.live_plotFrunningr<   r=   r(   modelstrainresultsfinishedstatusfailedzTraining failed)linezroboflow-trainc                 S      g | ]}t |d  qS )epoch)int.0r   r8   r8   r9   
<listcomp>|      z!Version.train.<locals>.<listcomp>r   c                 S   r   )r   rE   r   r8   r8   r9   r   }  r   c                 S   s0   g | ]}t |d  t |d  t |d  qS )box_loss
class_lossobj_lossr   r   r8   r8   r9   r     s    "zTraining in Progress.rM   zTraining Machine Spinning Upz	: Epoch: z mAP: z loss: TN)r~   )'rX   r*   r   r	   r   r"   ra   r   rsplitr   r(   r   rA   postr%   rt   rk   rD   rl   rC   IPython.displayr|   
matplotlibr}   r+   r,   rB   r.   nparrayappendlenjoinr2   copydeepcopyrV   rW   r3   )r4   ry   rz   plot_in_notebooktrain_model_formatr+   r,   _rF   datarG   r   r   first_graph_writeprevious_epochsnum_machine_spin_dotsr(   r   r   r   r   r   r8   r   r9   r     s   




"
.
*

 2

;zVersion.train
model_type
model_pathc                    s  g d}t  fdd|D std  d| d v r9z
ddl}ddl}W n	 ty0   d	w td
gdd nd v sAd v rQzddl}W n	 tyP   dw |tj	|d}t
|d jtri|d j}n)g }t|d jD ]\}}	||	|d j|	 f qr|jdd d dd |D }d v rd v r|d jd }
|d }n
|d j}
|d j}z||d j|
dd | D |j d}W np ty   ||d j|
dd |j D |j d}Y nSw d v sd v r7ttj	|dd}t|}W d   n	1 s	w   Y  ||d jd |v r|d  n|d! |d" d# d$}t|d d%r7|d j|d%< ttj	|d&d'}t|| W d   n	1 sSw   Y  ||d  tj	|d( g d)}ttj	|d*d'7}|D ],}tj tj	||r|j!tj	|||tj"d+ qy|d,v rtd-| d.qyW d   n	1 sw   Y  t#$t% d/| j& d/| j' d/| j( d0| j) d1  d2}z|j*d3krt+d4|,  W n ty } zt-d5|  W Y d}~dS d}~ww t#j.| d6 ttj	|d*d7d8}zG|,  | j/rBt-d9t0 d/| j& d/| j' d/| j(  t-d:t1 d/| j& d/| j' d;| j(  W dS t-d9t0 d/| j& d/| j' d/| j(  W dS  tyr } zt-d<|  W Y d}~dS d}~ww )=zUploads provided weights file to Roboflow

        Args:
            model_path (str): File path to model weights to be uploaded
        )yolov5z
yolov7-segr]   c                 3   s    | ]}| v V  qd S Nr8   )r   supported_modelr   r8   r9   	<genexpr>  s    z!Version.deploy.<locals>.<genexpr>zModel type z% not supported. Supported models are r]   r   NztThe ultralytics python package is required to deploy yolov8 models. Please install it with `pip install ultralytics`r_   T)ask_to_continuer   yolov7zhThe torch python package is required to deploy yolov5 models. Please install it with `pip install torch`zweights/best.ptr3   c                 S   s   | d S )Nr   r8   )xr8   r8   r9   <lambda>  s    z Version.deploy.<locals>.<lambda>)keyc                 S   s   g | ]}|d  qS )rs   r8   )r   r   r8   r8   r9   r     s    z"Version.deploy.<locals>.<listcomp>z-clsnc
train_argsc                 S   .   i | ]\}}|d ks|dks|dkr||qS r3   imgszbatchr8   r   kvalr8   r8   r9   
<dictcomp>  s   . z"Version.deploy.<locals>.<dictcomp>)namesyamlr   argsultralytics_versionr   c                 S   r   r   r8   r   r8   r8   r9   r     s
    zopt.yamlrr   img_size
batch_size)r   r   )r   r   r   r   r   model_artifacts.jsonwstate_dict.pt)zresults.csvzresults.pngr   r   zroboflow_deploy.zip)arcnamecompress_type)r   r   zFile z; not found. Please make sure to provide a valid model path.r;   z/uploadModel?api_key=z&modelType=z&nocache=truei  zwThis version already has a trained model. Please generate and train a new version in order to upload model to Roboflow.z4An error occured when getting the model upload URL: rF   rb)r   z'View the status of your deployment at: z$Share your model with the world at: z/model/z+An error occured when uploading the model: )2any
ValueErrortorchr^   rc   r   loadr/   r0   r   
isinstancer   list	enumerater   sortr   r   r   items__version__	Exception__dict__open	safe_loadhasattrrD   dumpsave
state_dictzipfileZipFilerg   rT   ZIP_DEFLATEDrA   rB   r   r+   r,   r(   r%   rj   rk   rC   rd   putr-   r   r   )r4   r   r   supported_modelsr   r^   r3   class_namesir   r   r   model_artifactsstreamoptsfplista_fileszipMefilereser8   r   r9   deploy  s"  




	




zVersion.deployc           
   
      s  t jst  d fdd	}zNtj|dd}td d6}t|jd}t	|j
d	d
d d  dt|d	 d dD ]}|rP|| |  qCW d   n1 s[w   Y  W n tyv }	 z	td|  |	d}	~	ww tjd tj  dS )a;  
        Download a dataset's zip file from the given URL and save it in the desired location

        Args:
            link (str): link the URL of the remote zip file
            location (str): filepath of the data directory to save the zip file to
            format (str): the format identifier string
        P   c                    sD   d d   d| | d | |f  }t jd|  t j  d S )N#Downloading Dataset Version Zip in  to z: %d%% [%d / %d] bytesrI   rL   )rR   rS   rT   rU   )currenttotalwidthrZ   formatrp   r8   r9   bar_progressP  s   z,Version.__download_zip.<locals>.bar_progressT)r   /roboflow.zipwbzcontent-lengthi   )
chunk_sizer   r   :rs   )descr   Nz(Error when trying to download dataset @ rO   )r   )r/   r0   rg   makedirsrA   rB   r   r   headersr   iter_contentrT   rU   r   rd   rR   rS   )
r4   rb   rp   r   r  rG   ftotal_lengthchunkr   r8   r   r9   __download_zipD  s4   	



zVersion.__download_zipc              
   C   s   t |d d.}t| d| d| ddD ]}z||| W q t jy.   tdw W d   n1 s9w   Y  t|d  dS )	aQ  
        Extracts the contents of a downloaded ZIP file and then deletes the zipped file.

        Args:
            location (str): filepath of the data directory that contains the ZIP file
            format (str): the format identifier string

        Raises:
            RuntimeError: If there is an error unzipping the file
        r  r   z"Extracting Dataset Version Zip to z in r  )r  zError unzipping downloadN)	r   r   r   infolistextracterrorrk   r/   remove)r4   rp   r   zip_refmemberr8   r8   r9   __extract_zipp  s   

zVersion.__extract_zipc                 C   s@   | j dd}| d| j }tjd}|r| d| S |S )zv
        Get the local path to save a downloaded dataset to

        Returns:
            str: the local path
         -DATASET_DIRECTORYr;   )r'   replacer(   r/   environrB   )r4   version_slugfilename	directoryr8   r8   r9   __get_download_location  s   zVersion.__get_download_locationc              	   C   s4   | j d^}}}t d| d| d| j d| 	S )z
        Get the Roboflow API URL for downloading (and exporting downloadable zips)

        Args:
            format (str): the format identifier string

        Returns:
            str: the Roboflow API URL
        r;   )r   r   r   r(   )r4   r   r+   r,   r   r8   r8   r9   __get_download_url  s   
"zVersion.__get_download_urlc                 C   s,   |s| j }|stdddd}|||S )a  
        If `format` is none, fall back to the instance's `model_format` value.

        If a human readable format name was passed, return the identifier that should be used for Roboflow API calls

        Otherwise, assume that the passed in format is also the identifier

        Args:
            format (str): a human readable format string

        Returns:
            str: format identifier string
        z_You must pass a format argument to version.download() or define a model in your Roboflow objectrw   yolov7pytorch)r   r   )r&   rk   rB   )r4   r   friendly_formatsr8   r8   r9   __get_format_identifier  s   
zVersion.__get_format_identifierrp   r   c                    sB   t jd}dtdtf fdd} dv rt||d dS dS )	z
        Certain formats seem to require reformatting the downloaded YAML.

        Args:
            location (str): filepath of the data directory that contains the yaml file
            format (str): the format identifier string
        z	data.yamlcontentrv   c                    s    dkr%| d  d | d< | d  d | d< | d  d | d<  dv r?| d  d | d< | d  d | d< z dkrYtd	gd
s\d| d< d| d< d| d< W | S W | S W | S  tyh   Y | S w )N	mt-yolov6r   r   r   test)rw   r  r]   z..r]   r_   )dependencies_versionsztrain/imageszvalid/imagesztest/images)lstripr   ModuleNotFoundError)r"  r   r8   r9   data_yaml_callback  s.   

z3Version.__reformat_yaml.<locals>.data_yaml_callback)rw   r#  r  r]   )r0   callbackN)r/   r0   r   dictr   )r4   rp   r   	data_pathr(  r8   r   r9   __reformat_yaml  s
   zVersion.__reformat_yamlc              	   C   s4   | j | j| j| j| j| j| j| jd}tj	|ddS )z:
        String representation of version object.
        )r'   r*   r(   r   r   r    r!   r+   rJ   )indent)
r'   r*   r(   r   r   r    r!   r+   rD   dumps)r4   
json_valuer8   r8   r9   __str__  s   
zVersion.__str__r   )F)NNT)NNF)__name__
__module____qualname____doc__r:   rP   rX   boolrq   ra   r   r2   r   rm   rn   rf   ri   re   ro   r0  r8   r8   r8   r9   r   %   s&    
W

C7   ,!r   r   rv   c                 C   s   dt | vr| S | dd S )Nr;   r   )r2   splitr   r8   r8   r9   r)     s   r)   ),r   rD   r/   rR   rV   r   	importlibr   numpyr   rA   r   dotenvr   r   roboflow.configr   r   r   r   r	   r
   r   r   roboflow.core.datasetr   roboflow.models.classificationr   %roboflow.models.instance_segmentationr    roboflow.models.object_detectionr   %roboflow.models.semantic_segmentationr   roboflow.util.annotationsr   roboflow.util.generalr   roboflow.util.versionsr   r   r   r2   r)   r8   r8   r8   r9   <module>   s:    (
     P