o
    -wi+!                     @   s   d Z ddlZddlZddlmZ ddlZddlmZ ddlm	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 ddlmZ ddlmZ ddlmZ dZG dd ded ZG dd deZdS )zPublic API: files.    N)Optional)gql)
RetryError)util)Attrs)normalize_exceptions)SizedPaginator)utils)Api)RETRY_TIMEDELTA)retrya  fragment RunFilesFragment on Run {
    files(names: $fileNames, after: $fileCursor, first: $fileLimit) {
        edges {
            node {
                id
                name
                url(upload: $upload)
                directUrl
                sizeBytes
                mimetype
                updatedAt
                md5
            }
            cursor
        }
        pageInfo {
            endCursor
            hasNextPage
        }
    }
}c                       sl   e Zd ZdZedeZd fdd	Ze	dd	 Z
e	d
d Ze	dd Zdd Zdd Zdd Z  ZS )Filesz)An iterable collection of `File` objects.a  
        query RunFiles($project: String!, $entity: String!, $name: String!, $fileCursor: String,
            $fileLimit: Int = 50, $fileNames: [String] = [], $upload: Boolean = false) {{
            project(name: $project, entityName: $entity) {{
                internalId
                run(name: $name) {{
                    fileCount
                    ...RunFilesFragment
                }}
            }}
        }}
        {}
        N2   Fc                    s4   || _ |j|j|j|pg |d}t ||| d S )N)projectentityname	fileNamesupload)runr   r   idsuper__init__)selfclientr   namesper_pager   	variables	__class__ T/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/apis/public/files.pyr   ?   s   zFiles.__init__c                 C   s    | j s|   | j d d d S )Nr   r   	fileCount)last_response
_load_pager   r   r   r    _lengthJ   s   zFiles._lengthc                 C   s$   | j r| j d d d d d S dS )Nr   r   filespageInfohasNextPageTr"   r$   r   r   r    moreQ   s
   z
Files.morec                 C   s(   | j r| j d d d d d d S d S )Nr   r   r&   edgescursorr)   r$   r   r   r    r-   Z   s   zFiles.cursorc                 C   s   | j | j| jd d S )N)	fileLimit
fileCursor)r   updater   r-   r$   r   r   r    update_variablesa      zFiles.update_variablesc                    s$    fdd j d d d d D S )Nc                    s    g | ]}t  j|d   jqS )node)Filer   r   ).0rr$   r   r    
<listcomp>e   s    z)Files.convert_objects.<locals>.<listcomp>r   r   r&   r+   r)   r$   r   r$   r    convert_objectsd   s   
zFiles.convert_objectsc                 C   s   d d| jjt| S )Nz<Files {} ({})>/)formatjoinr   pathlenr$   r   r   r    __repr__j   r2   zFiles.__repr__)Nr   F)__name__
__module____qualname____doc__r   r:   FILE_FRAGMENTQUERYr   propertyr%   r*   r-   r1   r8   r>   __classcell__r   r   r   r    r   ,   s     


r   r4   c                       s   e Zd ZdZd fdd	Zedd Zedefdd	Ze	e
jeejeejfd
				ddedededee dejf
ddZe	dd Zdd Ze	defddZ  ZS )r4   a  File is a class associated with a file saved by wandb.

    Attributes:
        name (string): filename
        url (string): path to file
        direct_url (string): path to file in the bucket
        md5 (string): md5 of file
        mimetype (string): mimetype of file
        updated_at (string): timestamp of last update
        size (int): size of file in bytes
        path_uri (str): path to file in the bucket, currently only available for files stored in S3
    Nc                    s,   || _ || _|| _d | _t t| d S N)r   _attrsr   +server_supports_delete_file_with_project_idr   r   dict)r   r   attrsr   r   r   r    r   |   s
   zFile.__init__c                 C   s   | j d }|d urt|S dS )N	sizeBytesr   )rH   int)r   
size_bytesr   r   r    size   s   
z	File.sizereturnc                 C   sV   d}zt | jd }W |S  ty   td Y |S  ty*   td Y |S w )zI
        Returns the uri path to the file in the storage bucket.
         	directUrlz1path_uri is only available for files stored in S3z!Unable to find direct_url of file)r	   parse_s3_url_to_s3_urirH   
ValueErrorwandbtermwarnLookupError)r   path_urir   r   r    rX      s   zFile.path_uri)retry_timedeltacheck_retry_fnretryable_exceptions.Frootreplaceexist_okapic                 C   s^   |du rt  }tj|| j}tj|r"|s"|rt|S tdt	
|| j|j t|S )a  Downloads a file previously saved by a run from the wandb server.

        Args:
            replace (boolean): If `True`, download will overwrite a local file
                if it exists. Defaults to `False`.
            root (str): Local directory to save the file.  Defaults to ".".
            exist_ok (boolean): If `True`, will not raise ValueError if file already
                exists and will not re-download unless replace=True. Defaults to `False`.
            api (Api, optional): If given, the `Api` instance used to download the file.

        Raises:
            `ValueError` if file already exists, replace=False and exist_ok=False.
        NzgFile already exists, pass replace=True to overwrite or exist_ok=True to leave it as is and don't error.)rU   r
   osr<   r;   r   existsopenrT   r   download_file_from_urlurlapi_key)r   r]   r^   r_   r`   r<   r   r   r    download   s   zFile.downloadc                 C   sX   d}d}d| j gi}|  r| jj|d< d}d}d||}t|}| jj||d d S )NrQ   r&   	projectIdz, $projectId: IntzprojectId: $projectIdz
            mutation deleteFiles($files: [ID!]!{}) {{
                deleteFiles(input: {{
                    files: $files
                    {}
                }}) {{
                    success
                }}
            }}
            )variable_values)r   *_server_accepts_project_id_for_delete_filer   _project_internal_idr:   r   r   execute)r   project_id_mutation_fragmentproject_id_variable_fragmentri   mutation_stringmutationr   r   r    delete   s    	

zFile.deletec                 C   s    d | j| jtj| jtjdS )Nz<File {} ({}) {}>)units)r:   r   mimetyper   to_human_sizerO   POW_2_BYTESr$   r   r   r    r>      s
   zFile.__repr__c                 C   sN   d}| j du r$t|}| j|}ddd |di di gD v | _ | j S )zReturns True if the server supports deleting files with a projectId.

        This check is done by utilizing GraphQL introspection in the available fields on the DeleteFiles API.
        a   
           query ProbeDeleteFilesProjectIdInput {
                DeleteFilesProjectIdInputType: __type(name:"DeleteFilesInput") {
                    inputFields{
                        name
                    }
                }
            }
        Nrh   c                 S   s   g | ]}|d  qS )r   r   )r5   xr   r   r    r7      s    zCFile._server_accepts_project_id_for_delete_file.<locals>.<listcomp>DeleteFilesProjectIdInputTypeinputFields)rI   r   r   rl   get)r   query_stringqueryresr   r   r    rj      s   

	z/File._server_accepts_project_id_for_delete_filerG   )r\   FFN)r?   r@   rA   rB   r   rE   rO   strrX   r   r   	retriabler   r   no_retry_authr   requestsRequestExceptionboolr   r
   ioTextIOWrapperrg   rq   r>   rj   rF   r   r   r   r    r4   n   sB    
#
)rB   r   ra   typingr   r   	wandb_gqlr   wandb_gql.clientr   rU   r   wandb.apis.attrsr   wandb.apis.normalizer   wandb.apis.paginatorr   wandb.apis.publicr	   wandb.apis.public.apir
   wandb.apis.public.constr   wandb.sdk.libr   rC   r   r4   r   r   r   r    <module>   s&    B