o
    -wib                    @   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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mZmZmZmZmZmZmZm 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* d dl+Z+d dl+m,Z,m-Z- d d	l.m/Z/m0Z0 d d
l1m2Z2m3Z3m4Z4m5Z5 d dl6m7Z7 d dl8m9Z9 d dl:m;Z; d dl<m=Z= d dl>m?Z?m@Z@ d dlAmBZB d dlCmDZD d dlEmFZFmGZG ddlHmIZImJZJ ddlKmLZLmMZM ddlNmOZO ddlPmQZQ ddlRmSZS eTeUZVdZWerXd dlmZmXZX ddlRmYZY G dd deXdd ZZG d!d" d"eXZ[G d#d$ d$eXZ\G d%d& d&eXZ]G d'd( d(eXZ^G d)d* d*eXZ_G d+d, d,eXZ`G d-d. d.eXZaeZbed/ Zce edeef ZfeTd0Zgejhid1rjegjejk d?d3d4ZlG d5d6 d6ejmZnG d7d8 d8eZod9epd:eeo d2epfd;d<ZqG d=d> d>ZrdS )@    N)deepcopy)Path)IOTYPE_CHECKINGAnyCallableDictIterableListLiteralMappingMutableMapping
NamedTupleOptionalSequenceTextIOTupleUnion)Clientgql)
RetryError)Document)envutil)normalize_exceptionsparse_backend_error_messages)AuthenticationError	CommErrorUnsupportedError
UsageError)parse_sm_secrets)Settings)ServerFeature)is_artifact_registry_project)SERVER_FEATURES_QUERY_GQLServerFeaturesQuery)_thread_local_api_settings)GraphQLSession)B64MD5md5_file_b64   )credentialsretry)
DIFF_FNAMEMETADATA_FNAME)GitRepo   context)Progressmodel-registry)r   	TypedDict)
ProgressFnc                   @   sZ   e Zd ZU dZeed< eed< eed< ee ed< ee ed< eeeee	f   ed< dS )	CreateArtifactFileSpecInputzDCorresponds to `type CreateArtifactFileSpecInput` in schema.graphql.
artifactIDnamemd5mimetypeartifactManifestIDuploadPartsInputN)
__name__
__module____qualname____doc__str__annotations__r   r
   r   object rE   rE   \/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/sdk/internal/internal_api.pyr7   D   s   
 r7   F)totalc                   @   sV   e Zd ZU eed< eed< eed< ee ed< ee ed< ded< eed< d	ed
< dS )CreateArtifactFilesResponseFileidr9   displayName	uploadUrluploadHeadersUploadPartsResponseuploadMultipartUrlsstoragePath#CreateArtifactFilesResponseFileNodeartifactN)r>   r?   r@   rB   rC   r   r   rE   rE   rE   rF   rH   N   s   
 rH   c                   @      e Zd ZU eed< dS )rP   rI   Nr>   r?   r@   rB   rC   rE   rE   rE   rF   rP   X      
 rP   c                   @   s"   e Zd ZU ed ed< eed< dS )rM   UploadUrlPartsuploadUrlPartsuploadIDN)r>   r?   r@   r
   rC   rB   rE   rE   rE   rF   rM   [   s   
 rM   c                   @   s   e Zd ZU eed< eed< dS )rU   
partNumberrK   N)r>   r?   r@   intrC   rB   rE   rE   rE   rF   rU   _      
 rU   c                   @   sJ   e Zd ZU dZeed< eeef ed< eed< eed< eed< eed< dS )	$CompleteMultipartUploadArtifactInputzMCorresponds to `type CompleteMultipartUploadArtifactInput` in schema.graphql.completeMultipartActioncompletedPartsr8   rO   rW   r:   N)r>   r?   r@   rA   rB   rC   r   rY   rE   rE   rE   rF   r[   c   s   
 r[   c                   @   rR   )'CompleteMultipartUploadArtifactResponsedigestNrS   rE   rE   rE   rF   r^   m   rT   r^   c                   @   s   e Zd ZU eed< eed< eee  ed< ee ed< ee ed< ee ed< ee ed< ee ed< ee ed	< eeeef  ed
< eeeef  ed< dS )DefaultSettingssection
git_remoteignore_globsbase_urlroot_dirapi_keyentityorganizationproject_extra_http_headers_proxiesN)r>   r?   r@   rB   rC   r   r
   r   rE   rE   rE   rF   r`   p   s   
 r`   RUNNINGPAUSEDCANCELEDFINISHEDzhttp.clientWANDB_DEBUGreturnc                     sp   t jdsd S tjrd S tj dtdd f fdd} | tj	_
dtj	j_td}|jr6t|jd  d S d S )	Nrq   argsrr   c                     s   t  d|  d S )N )httpclient_loggerlogjoin)rs   levelrE   rF   httpclient_log   s   z7check_httpclient_logger_handler.<locals>.httpclient_logr0   wandbr   )osenvirongetru   handlersloggingDEBUGr   httpclientprintHTTPConnection
debuglevel	getLogger
addHandler)rz   root_loggerrE   rx   rF   check_httpclient_logger_handler   s   

r   c                   @   s&   e Zd ZU eej ed< dddZdS )_ThreadLocalDatar2   rr   Nc                 C   s
   d | _ d S Nr1   selfrE   rE   rF   __init__      
z_ThreadLocalData.__init__rr   N)r>   r?   r@   r   r2   ContextrC   r   rE   rE   rE   rF   r      s   
 r   c                   @   s   e Zd ZU eed< eed< dS )	_OrgNamesentity_namedisplay_nameNrS   rE   rE   rE   rF   r      rZ   r   rh   orgsc                 C   sT   |D ]}| |v r|j   S qt|dkr"td|d jd| dtd| d)a  Match the organization provided in the path with the org entity or org name of the input entity.

    Args:
        organization: The organization name to match
        orgs: List of tuples containing (org_entity_name, org_display_name)

    Returns:
        str: The matched org entity name

    Raises:
        ValueError: If no matching organization is found or if multiple orgs exist without a match
    r0   z8Expecting the organization name or entity name to match r   z# and cannot be linked/fetched with zC. Please update the target path with the correct organization name.zTPersonal entity belongs to multiple organizations and cannot be linked/fetched with zo. Please update the target path with the correct organization name or use a team entity in the entity settings.)r   len
ValueErrorr   )rh   r   	org_namesrE   rE   rF   $_match_org_with_fetched_org_entities   s   
r   c                .   @   s  e Zd ZU dZedZe Ze	j
ed< eed< ddejddejddfd	eed
deef  dedejdedeeeegef  dee ddfddZdededefddZdee	j
 ddfddZd{ddZede	j
fddZ	d{dd Z d{d!d"Z!dededd#fd$d%Z"defd&d'Z#d(eddfd)d*Z$edee fd+d,Z%edefd-d.Z&edee fd/d0Z'edee fd1d2Z(edefd3d4Z)edefd5d6Z*edefd7d8Z+d|d9ee d:ee defd;d<Z,	=d}d9ed>ed?eddfd@dAZ-	=d}d9edBed>ed?eddf
dCdDZ.	d|dEedFee dGee de/eef fdHdIZ0e1de/e2e e2e e2e f fdJdKZ3e1d{dLdMZ4de2fdNdOZ5e1dee fdPdQZ6e1de/eeef fdRdSZ7e1defdTdUZ8e1de/eef fdVdWZ9e1defdXdYZ:e1defdZd[Z;e1de2fd\d]Z<e1	d~d^ed_ed`edaee2e  def
dbdcZ=e1defdddeZ>de?eef fdfdgZ@dheeef defdidjZAe1	d~d^ed_ed`edaee2e  def
dkdlZBe1de?eef fdmdnZCe1dee fdodpZDe1de/e?eef e?eef f fdqdrZEe1d~dsee de2e?eef  fdtduZFe1d~dFedsee dd#fdvdwZGe1		d|dxedyedFee dsee de?eef f
dzd{ZHe1	d~dFedsee de2e?eef  fd|d}ZIe1	d|dFedGee dsee de/ee?eef ee e?eef f fd~dZJe1dsedededee?eef  fddZKe1deded(edefddZLdFedefddZMe1			ddFedee dee dsee de?eef f
ddZNe1dsedefddZOe1dsedFede2e?eef  fddZPe1dsedededee?eeeQeef f  dee?eef  f
ddZRe1		d|dsedFedededee dee dee?eef  fddZSe1eTdddfdedsedededFedee dee dee dee?eef  fddZUe1	d~dsedFedededee?eeeeQef f  dee dee?eef  fddZVe1	d~dede?eef dee dedee dee?eef  fddZWe1			ddedsee dFee dee dee?eef  f
ddZXe1d~ded(ee defddZYe1de2fddZZe1dsedFede2e de?eef dededefddZ[e1dedededefddZ\e1dededefddZ]e1																			ddee dee dFee dee dee dee2e  dee dee dsee dee dee dee dee dee dee dee dee dee dee de/eeee2 f f(ddʄZ^e1				ddededeQdee dsee dFee dee defddτZ_e1dsedFededefddфZ`e1dsedFededefddӄZae1defddՄZbe1			ddFedee2e e?eecf f dGee dsee dee de/ee2e e?ee?eef f f fdd؄Zd			ddFedee2e e?eecf f dGee dsee dee de/ee2e e?ee?eef f f fddڄZee1		d|dFedGee dsee de?ee?eef f fdd܄Zfe1		d|dFededGee dsee dee?eef  f
dd߄Zge1dede/eehjif fddZje1	d~de?eef dee de/eeehji f fddZkdedede?eef ddfddZl	d~dedemdee?eef  deehji fddZn		d|dedecem ded dee?eef  deehji f
ddZoe1			ddedee dee dsee def
ddZpdededede2e?eef  fddZqerdedefddZse1									ddedee dee dee dee dFee dsee dee dee2e  d ee?eef  de/ee2e f fddZte1defddZuerdedevdefddZwe1	d|dFedGee dsee dd	fd
dZxdefddZye1						=ddee2e e?eecf f dGee dsee dFee dee dedeeze{d= f ddfddZ|dedededsedFede}e dede?eef fddZ~ddsededefddZdsede2e fddZ						ddedee dee dee d ee d!ee d"ee de/ee?eef f fd#d$Z						ddedee dee dee d!ee d"ee d ee dee?eef  fd%d&Zde2e fd'd(Zdefd)d*Z			dd+edee dee dee dee f
d,d-Zde2e fd.d/Zde2e fd0d1Zd2e2d3ee d4ee defd5d6Z												=	dd+ed7ed8edee d9ee dee dee dee dee dee? d:ee dee2e?eef   dee2e?eef   d4ee d;ee d3ee de/e?e?f f"d<d=Zdedd#fd>d?Z	@ddedAedBe2e?eef  dCee dDedee fdEdFZ						Gdded8edee dHee dsee dFee dGee dIedJede/ee?eef f fdKdLZ			ddMedHee d8ee dIee de/ee?eef f f
dNdOZdede?eef de?eef fdPdQZdedee fdRdSZde2fdTdUZe1dVedW deedXf fdYdZZe1		d|d[ed\ed]ee d^ed_ def
d`daZ	d|dxedsee dFee ddbfdcddZ		d|dxeddbdsee dFee ddf
dedfZ		d|dxedsee dFee ddfdgdhZ		d|dxedsee dFee ddfdidjZ		d|dxedsee dFee ddfdkdlZ		d|dxedsee dFee ddfdmdnZdedoedehjifdpdqZdrd#de2e? fdsdtZe1d(edefdudvZe1dsedededwededxeeeeef f dee?eef  fdydzZdS (  Apia  W&B Internal Api wrapper.

    Note:
        Settings are automatically overridden by looking for
        a `wandb/settings` file in the current working directory or its parent
        directory. If none can be found, we look in the current user's home
        directory.

    Args:
        default_settings(dict, optional): If you aren't using a settings
        file, or you wish to override the section to use in the settings file
        Override the settings here.
       _global_context_local_dataNT   )daysdefault_settingsz!wandb.sdk.wandb_settings.Settingsz1wandb.sdk.internal.settings_static.SettingsStaticload_settingsretry_timedeltar}   retry_callbackrf   rr   c           	      C   s  || _ t | _t | _ddg dd d d d d d d d| _|| _|p!i }| j| d| _	t
|| jdd| _t| dd	| _d
ddd| _| dpTt| j dd| _| jtjp]i  d }|rhd|f}n| jd urwd| j | jd< ntjd u rd| jpdf}| dpt| j dd}tt| jtj| j dtj| j dd| jd| j|| d dtj|dd| _ || _!t"j#| j$|t%j&t't(j)f|d| _*d | _+d | _,t(- | _.| j/rt0j1| j.j2| j/d| j._2|r| j.j3| t4t"j5|d | j6| _7t4t"j5|d | j8| _9i | _:t%;d!| _<d | _=d | _>d | _?d | _@d | _Ad | _Bd | _Cd | _Dd | _Ed | _Fd | _Gd | _Hd | _Id | _Jd | _Kd | _Ld | _Md S )"Ndefaultoriginzhttps://api.wandb.ai)ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   
   re   )r   re   rb   )remoter*         )system_sample_secondssystem_samplesheartbeat_secondsrj   WANDB__EXTRA_HTTP_HEADERS{}apiBearer Authorization rk   WANDB__PROXIESr   )z
User-AgentzX-WANDB-USERNAMEzX-WANDB-USER-EMAILTrd   z/graphql)headersuse_jsontimeoutauthurlcookiesproxies)	transport)r   check_retry_fnretryable_exceptionsr   )r   )r   zazure.storage.blob)N_environr2   r   r   r   r   r   r   updateretry_uploadsr!   r~   	_settingsr/   settingsgitdynamic_settingsjsonloadsrj   r&   r   access_tokenr   rf   r   r'   
user_agentr   get_usernameget_user_emailHTTP_TIMEOUTr   r   r,   Retryexecuter   no_retry_authr   requestsRequestException
_retry_gql_current_run_id_file_stream_apiSession_upload_file_sessionFILE_PUSHER_TIMEOUT	functoolspartialputr   r   	retriableupload_fileupload_file_retryupload_multipart_file_chunk!upload_multipart_file_chunk_retry_client_id_mapping
get_module_azure_blob_modulequery_typesmutation_typesserver_info_typesserver_use_artifact_input_info!server_create_artifact_input_infoserver_artifact_fields_info$server_organization_type_fields_info0server_supports_enabling_artifact_usage_tracking_max_cli_version_server_settings_typefail_run_queue_item_input_infocreate_launch_agent_input_info$server_create_run_queue_supports_drc)server_create_run_queue_supports_priority"server_supports_template_variables*server_push_to_run_queue_supports_priority_server_features_cache)	r   r   r   r   r}   r   rf   r   r   rE   rE   rF   r      s   








zApi.__init__rs   kwargsc                 O   s   | j |d| jji|}|S )Nretry_cancel_event)r   r2   cancel_event)r   rs   r   retrE   rE   rF   r   p  s   zApi.gqlapi_contextc                 C   s   || j _d S r   r   r2   )r   r   rE   rE   rF   set_local_contextx     zApi.set_local_contextc                 C   s   d | j _d S r   r   r   rE   rE   rF   clear_local_context{  r   zApi.clear_local_contextc                 C   s   | j jp| jS r   )r   r2   r   r   rE   rE   rF   r2   ~     zApi.contextc                 C   s   d| j pdf| jjj_dS )z3Ensure the current api key is set in the transport.r   r   N)rf   r   r   sessionr   r   rE   rE   rF   reauth     z
Api.reauthc                 C   s   d | d| jj_dS )z2Ensure the current api points to the right server.z
{}/graphqlrd   N)formatr   r   r   r   r   rE   rE   rF   relocate  r  zApi.relocate	_Responsec                 O   sv   z
| j j|i |W S  tjjy: } z"|j}|dusJ td t|D ]}t	
d| d| d q& d}~ww )z5Wrapper around execute that logs in cases of failure.NzError executing GraphQL.zError while calling W&B API: z ())r   r   r   
exceptions	HTTPErrorresponselogger	exceptionr   r{   	termerror)r   rs   r   errr  errorrE   rE   rF   r     s   
zApi.executec                 C   s"   |  td}|duo|d duS )z>Returns whether the API key stored on initialization is valid.zquery { viewer { id } }Nviewer)r   r   )r   resrE   rE   rF   validate_api_key  s   zApi.validate_api_keyrun_idc                 C   s
   || _ d S r   r   )r   r  rE   rE   rF   set_current_run_id  r   zApi.set_current_run_idc                 C   s   | j S r   r  r   rE   rE   rF   current_run_id  s   zApi.current_run_idc                 C   s   dt j S )NzW&B Internal Client )r{   __version__r   rE   rE   rF   r     s   zApi.user_agentc                 C   sb   t jrt jS tj| j}d }|r|d }| jtj	}t
 tj	}| jd}|p0|p0|p0|S )Nrf   )r&   rf   r   utilsget_netrc_authapi_urlr   r~   r   API_KEYr    r   )r   r   keyenv_keysagemaker_keydefault_keyrE   rE   rF   rf     s   zApi.api_keyc                 C   s`   | j tj}|sdS t|}| std| | d}tt	t
j| j }t
|||S )aR  Retrieves an access token for authentication.

        This function attempts to exchange an identity token for a temporary
        access token from the server, and save it to the credentials file.
        It uses the path to the identity token as defined in the environment
        variables. If the environment variable is not set, it returns None.

        Returns:
            Optional[str]: The access token if available, otherwise None if
            no identity token is supplied.
        Raises:
            AuthenticationError: If the path to the identity token is not found.
        NzIdentity token file not found: rd   )r   r~   r   IDENTITY_TOKEN_FILEr   existsr   r   get_credentials_filerB   r+   DEFAULT_WANDB_CREDENTIALS_FILEr   )r   token_file_str
token_filerd   credentials_filerE   rE   rF   r     s   
zApi.access_tokenc                 C   s
   |  dS )Nrd   )r   r   rE   rE   rF   r    s   
zApi.api_urlc                 C   s   t j| jS r   )r{   r   app_urlr  r   rE   rE   rF   r&    r   zApi.app_urlc                 C   s   |   dS )Nrg   )r  r~   r   rE   rE   rF   default_entity  r   zApi.default_entityr  ra   c                 C   s   | j  }|| jj|d |tj| jjtj	d|dd| j
dtj| jjtj	d|dd| j
dtj| jjtj	d|dd| j
dtj| jjtj	d|dd| j
dtj| jjtj	d|dd| j
dd	 |d
u ru|S || S )a,  The settings overridden from the wandb/settings file.

        Args:
            key (str, optional): If provided only this setting is returned
            section (str, optional): If provided this section of the setting file is
            used, defaults to "default"

        Returns:
            A dict with the current settings

                {
                    "entity": "models",
                    "base_url": "https://api.wandb.ai",
                    "project": None,
                    "organization": "my-org",
                }
        )ra   rg   )fallbackr   rh   ri   rd   rc   )rg   rh   ri   rd   rc   N)r   copyr   r   itemsr   
get_entityr~   r!   DEFAULT_SECTIONr   get_organizationget_projectget_base_url
get_ignore)r   r  ra   resultrE   rE   rF   r     s\   
-zApi.settingsFgloballypersistc                 C   s   | j jtj|||d d S )Nr2  r3  )r   clearr!   r,  )r   r  r2  r3  rE   rE   rF   clear_setting!  s   

zApi.clear_settingvaluec                 C   sh   | j jtj||||d |dkrtj|| jd d S |dkr(tj|| jd d S |dkr2|   d S d S )Nr4  rg   r   ri   rd   )	r   setr!   r,  r   
set_entityr   set_projectr  )r   r  r7  r2  r3  rE   rE   rF   set_setting(  s   zApi.set_settingslugri   runc                 C   s   |rd|v r| d}|d }|d }||fS |p|  d}|du r(td|p5|p5| jp5tj| jd}|s<J d||fS )	a  Parse a slug into a project and run.

        Args:
            slug (str): The slug to parse
            project (str, optional): The project to use, if not provided it will be
            inferred from the slug
            run (str, optional): The run to use, if not provided it will be inferred
            from the slug

        Returns:
            A dict with the project and run
        /r   r0   ri   NzNo default project configured.r   run must be specified)splitr   r~   r   r  r   get_runr   )r   r<  ri   r=  partsrE   rE   rF   
parse_slug5  s   
zApi.parse_slugc                 C   s   d}| j d u s| jd u s| jd u rMt|}| |}dd |di di gD | _ dd |di di gD | _dd |d	i di gD | _| j | j| jfS )
Na  
           query ProbeServerCapabilities {
               QueryType: __type(name: "Query") {
                   ...fieldData
                }
                MutationType: __type(name: "Mutation") {
                   ...fieldData
                }
               ServerInfoType: __type(name: "ServerInfo") {
                   ...fieldData
                }
            }

            fragment fieldData on __Type {
                fields {
                    name
                }
            }
        c                 S      g | ]}| d dqS r9   r   r~   .0fieldrE   rE   rF   
<listcomp>m      
z1Api.server_info_introspection.<locals>.<listcomp>	QueryTypefieldsc                 S   rD  rE  rF  rG  rE   rE   rF   rJ  q  rK  MutationTypec                 S   rD  rE  rF  rG  rE   rE   rF   rJ  u  rK  ServerInfoType)r   r   r   r   r~   r   query_stringqueryr  rE   rE   rF   server_info_introspectionP  s    



zApi.server_info_introspectionc                 C   sR   d}| j d u r't|}| |}|r"dd |di di gD ng | _ d S d S )Na2  
           query ProbeServerSettings {
               ServerSettingsType: __type(name: "ServerSettings") {
                   ...fieldData
                }
            }

            fragment fieldData on __Type {
                fields {
                    name
                }
            }
        c                 S   rD  rE  rF  rG  rE   rE   rF   rJ    rK  z5Api.server_settings_introspection.<locals>.<listcomp>ServerSettingsTyperM  )r   r   r~   rP  rE   rE   rF   server_settings_introspection{  s   

z!Api.server_settings_introspectionc                 C   sH   d}| j d u r!t|}| |}dd |di di gD | _ | j S )Na  
           query ProbeServerUseArtifactInput {
               UseArtifactInputInfoType: __type(name: "UseArtifactInput") {
                   name
                   inputFields {
                       name
                   }
                }
            }
        c                 S   rD  rE  rF  rG  rE   rE   rF   rJ    rK  z?Api.server_use_artifact_input_introspection.<locals>.<listcomp>UseArtifactInputInfoTypeinputFields)r   r   r~   rP  rE   rE   rF   'server_use_artifact_input_introspection  s   

z+Api.server_use_artifact_input_introspectionc                 C   s    t d}|  |}|dpd S )Nz
            query LaunchAgentIntrospection {
                LaunchAgentType: __type(name: "LaunchAgent") {
                    name
                }
            }
        LaunchAgentTyper   r~   r   rR  r  rE   rE   rF   launch_agent_introspection  s
   

zApi.launch_agent_introspectionc                 C   s   |   \}}}d}| jd u s| jd u rJt|}| |}|d u r$tdddd |di di gD v | _dd	d |di di gD v | _d
|v | j| jfS )Na  
           query ProbeCreateRunQueueInput {
               CreateRunQueueInputType: __type(name: "CreateRunQueueInput") {
                   name
                   inputFields {
                       name
                   }
                }
            }
        z,Could not get CreateRunQueue input from GQL.defaultResourceConfigIDc                 S      g | ]}|d  qS r9   rE   rH  xrE   rE   rF   rJ        z6Api.create_run_queue_introspection.<locals>.<listcomp>CreateRunQueueInputTyperW  prioritizationModec                 S   r^  r_  rE   r`  rE   rE   rF   rJ    rb  createRunQueue)rS  r   r   r   r   r~   )r   _	mutationsrQ  rR  r  rE   rE   rF   create_run_queue_introspection  s$   




z"Api.create_run_queue_introspectionc                 C      |   \}}}d|v S )NupsertRunQueuerS  r   rf  rg  rE   rE   rF   upsert_run_queue_introspection     z"Api.upsert_run_queue_introspectionc                 C   s   d}| j d u s| jd u r;t|}| |}ddd |di di gD v | _ ddd |di di gD v | _| j | jfS )	Na  
            query ProbePushToRunQueueInput {
                PushToRunQueueInputType: __type(name: "PushToRunQueueInput") {
                    name
                    inputFields {
                        name
                    }
                }
            }
        templateVariableValuesc                 S   r^  r_  rE   r`  rE   rE   rF   rJ    rb  z7Api.push_to_run_queue_introspection.<locals>.<listcomp>PushToRunQueueInputTyperW  priorityc                 S   r^  r_  rE   r`  rE   rE   rF   rJ    rb  )r   r   r   r~   rP  rE   rE   rF   push_to_run_queue_introspection  s   




z#Api.push_to_run_queue_introspectionc                 C   ri  )NcreateDefaultResourceConfigrk  rl  rE   rE   rF   ,create_default_resource_config_introspection  rn  z0Api.create_default_resource_config_introspectionc                 C   ri  )NfailRunQueueItemrk  rl  rE   rE   rF   !fail_run_queue_item_introspection  rn  z%Api.fail_run_queue_item_introspectionc                 C   J   | j r| j S d}t|}| |}dd |di di gD | _ | j S )Na  
           query ProbeServerFailRunQueueItemInput {
                FailRunQueueItemInputInfoType: __type(name:"FailRunQueueItemInput") {
                    inputFields{
                        name
                    }
                }
            }
        c                 S   rD  rE  rF  rG  rE   rE   rF   rJ  (  rK  z@Api.fail_run_queue_item_fields_introspection.<locals>.<listcomp>FailRunQueueItemInputInfoTyperW  )r   r   r~   rP  rE   rE   rF   (fail_run_queue_item_fields_introspection     

z,Api.fail_run_queue_item_fields_introspectionrun_queue_item_idmessagestage
file_pathsc           
      C   sp   |   sdS d|i}d|  v r#|||d |d ur ||d< d}nd}t|}| j||d}|d	 d
 }	|	S )NFrunQueueItemIdr|  )r|  r}  	filePathsa  
            mutation failRunQueueItem($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
                failRunQueueItem(
                    input: {
                        runQueueItemId: $runQueueItemId
                        message: $message
                        stage: $stage
                        filePaths: $filePaths
                    }
                ) {
                    success
                }
            }
            a(  
            mutation failRunQueueItem($runQueueItemId: ID!) {
                failRunQueueItem(
                    input: {
                        runQueueItemId: $runQueueItemId
                    }
                ) {
                    success
                }
            }
            variable_valuesru  success)rv  ry  r   r   )
r   r{  r|  r}  r~  r  mutation_stringmutationr  r1  rE   rE   rF   fail_run_queue_item0  s   zApi.fail_run_queue_itemc                 C   ri  )NupdateRunQueueItemWarningrk  rl  rE   rE   rF   +update_run_queue_item_warning_introspectiona  rn  z/Api.update_run_queue_item_warning_introspectionc              
   C   s   t t}z|  |}W n ty* } zdt|v ri | _n W Y d }~| jS d }~ww t|j}|rC|j }rCdd |D | _| jS i | _| jS )Nz3Cannot query field "features" on type "ServerInfo".c                 S   s   i | ]	}|r|j |jqS rE   )r9   
is_enabled)rH  frE   rE   rF   
<dictcomp>w      z(Api._server_features.<locals>.<dictcomp>)	r   r$   	ExceptionrB   r   r%   model_validateserver_infofeatures)r   rR  r  einfofeatsrE   rE   rF   _server_featuresf  s"   
	zApi._server_featuresfeaturec                 C   s*   t |tr
t|n|}|  |pdS )a"  Return whether the current server supports the given feature.

        This also caches the underlying lookup of server feature flags,
        and it maps {feature_name (str) -> is_enabled (bool)}.

        Good to use for features that have a fallback mechanism for older servers.
        F)
isinstancerY   r"   Namer  r~   )r   r  r  rE   rE   rF   _server_supports|  s   zApi._server_supportsc                 C   s<   |   sdS td}| j|||||dd}|d d }|S )NFa  
        mutation updateRunQueueItemWarning($runQueueItemId: ID!, $message: String!, $stage: String!, $filePaths: [String!]) {
            updateRunQueueItemWarning(
                input: {
                    runQueueItemId: $runQueueItemId
                    message: $message
                    stage: $stage
                    filePaths: $filePaths
                }
            ) {
                success
            }
        }
        )r  r|  r}  r  r  r  r  )r  r   )r   r{  r|  r}  r~  r  r  r1  rE   rE   rF   update_run_queue_item_warning  s   	z!Api.update_run_queue_item_warningc                 C   s    t d}|  |}|dpi S )Na[  
        query Viewer{
            viewer {
                id
                entity
                username
                flags
                teams {
                    edges {
                        node {
                            name
                        }
                    }
                }
            }
        }
        r  rZ  r[  rE   rE   rF   r    s
   
z
Api.viewerc                 C   s\   | j d ur| j S |  \}}}d|v od|v }|sd S |  \}}|di d| _ | j S )N
serverInfocliVersionInfomax_cli_version)r   rS  viewer_server_infor~   )r   r   r   rf  cli_version_existsr  rE   rE   rF   r    s   
zApi.max_cli_versionc                 C   s   d}d}d}|   \}}}d|v od|v }d|v od|v }|s!dn|}	|s'dn|}
|d|	d	|
}t|}| |}|d
pBi |dpHi fS )Nz
            latestLocalVersionInfo {
                outOfDate
                latestVersionString
                versionOnThisInstanceString
            }
        zm
            serverInfo {
                cliVersionInfo
                _LOCAL_QUERY_
            }
        a  
        query Viewer{
            viewer {
                id
                entity
                username
                email
                flags
                teams {
                    edges {
                        node {
                            name
                        }
                    }
                }
            }
            _CLI_QUERY_
        }
        r  r  latestLocalVersionInfor   _CLI_QUERY__LOCAL_QUERY_r  )rS  replacer   r~   )r   local_query	cli_queryquery_templater   r   rf  r  local_version_existscli_query_stringlocal_query_stringrQ  rR  r  rE   rE   rF   r    s"   
zApi.viewer_server_inforg   c                 C   s2   t d}| | j |d|p| didd }|S )zList projects in W&B scoped by entity.

        Args:
            entity (str, optional): The entity to scope this project to.

        Returns:
                [{"id","name","description"}]
        a=  
        query EntityProjects($entity: String) {
            models(first: 10, entityName: $entity) {
                edges {
                    node {
                        id
                        name
                        description
                    }
                }
            }
        }
        rg   r  modelsr   _flatten_edgesr   )r   rg   rR  project_listrE   rE   rF   list_projects  s   
zApi.list_projectsc                 C   s$   t d}| j |||ddd }|S )a  Retrieve project.

        Args:
            project (str): The project to get details for
            entity (str, optional): The entity to scope this project to.

        Returns:
                [{"id","name","repo","dockerImage","description"}]
        a  
        query ProjectDetails($entity: String, $project: String) {
            model(name: $project, entityName: $entity) {
                id
                name
                repo
                dockerImage
                description
            }
        }
        )rg   ri   r  modelr   )r   ri   rg   rR  r  rE   rE   rF   ri   3  s   
zApi.projectsweepspecsc                 C   s   t d}|p
| d}|p| d}| j |||||dd}|d du s,|d d du r:td| d	| d	| d
|d d }|rK| |d |d< |S )ai  Retrieve sweep.

        Args:
            sweep (str): The sweep to get details for
            specs (str): history specs
            project (str, optional): The project to scope this sweep to.
            entity (str, optional): The entity to scope this sweep to.

        Returns:
                [{"id","name","repo","dockerImage","description"}]
        a  
        query SweepWithRuns($entity: String, $project: String, $sweep: String!, $specs: [JSONString!]!) {
            project(name: $project, entityName: $entity) {
                sweep(sweepName: $sweep) {
                    id
                    name
                    method
                    state
                    description
                    config
                    createdAt
                    heartbeatAt
                    updatedAt
                    earlyStopJobRunning
                    bestLoss
                    controller
                    scheduler
                    runs {
                        edges {
                            node {
                                name
                                state
                                config
                                exitcode
                                heartbeatAt
                                shouldStop
                                failed
                                stopped
                                running
                                summaryMetrics
                                sampledHistory(specs: $specs)
                            }
                        }
                    }
                }
            }
        }
        rg   ri   )rg   ri   r  r  r  Nr  zSweep r>  
 not foundruns)r   r   r   r  )r   r  r  ri   rg   rR  r  datarE   rE   rF   r  P  s&   (	z	Api.sweepc                 C   s>   t d}| | j ||p| d|p| dddd d S )a  List runs in W&B scoped by project.

        Args:
            project (str): The project to scope the runs to
            entity (str, optional): The entity to scope this project to.  Defaults to public models

        Returns:
                [{"id","name","description"}]
        a  
        query ProjectRuns($model: String!, $entity: String) {
            model(name: $model, entityName: $entity) {
                buckets(first: 10) {
                    edges {
                        node {
                            id
                            name
                            displayName
                            description
                        }
                    }
                }
            }
        }
        rg   ri   )rg   r  r  r  bucketsr  )r   ri   rg   rR  rE   rE   rF   	list_runs  s   zApi.list_runsc              	   C   s"  t   td}|||dd}d}i }d}i }	ttfD ]p}
|
|d< | j||d}|d du r;td	| d
| d
| d|d d }|d rV|d }t|d pPd}d|d< |d dur|d d D ]'}|d d }|d d }t|}|	  |tkr| }	qb|tkr|j
}qbq||||	fS )a  Get the relevant configs for a run.

        Args:
            project (str): The project to download, (can include bucket)
            run (str, optional): The run to download
            entity (str, optional): The entity to scope this project to.
        aW  
        query RunConfigs(
            $name: String!,
            $entity: String,
            $run: String!,
            $pattern: String!,
            $includeConfig: Boolean!,
        ) {
            model(name: $name, entityName: $entity) {
                bucket(name: $run) {
                    config @include(if: $includeConfig)
                    commit @include(if: $includeConfig)
                    files(pattern: $pattern) {
                        pageInfo {
                            hasNextPage
                            endCursor
                        }
                        edges {
                            node {
                                name
                                directUrl
                            }
                        }
                    }
                }
            }
        }
        T)r9   r=  rg   includeConfigr   Npatternr  r  zRun r>  r  bucketr  commitconfigr   Ffilesedgesnoder9   	directUrl)r   r   r-   r.   r   r   r   r   r~   raise_for_statustext)r   ri   r=  rg   rR  r  r  r  patchmetadatafilenamer  run_obj	file_edger9   r   r  rE   rE   rF   
run_config  sF    

zApi.run_configproject_namer9   c                 C   sv   t d}| j ||||dd}d|vsd|d pi vrdS |d }| d| d|v r5| d|d d	  |d }|S )
a  Check if a run exists and get resume information.

        Args:
            entity (str): The entity to scope this project to.
            project_name (str): The project to download, (can include bucket)
            name (str): The run to download
        a  
        query RunResumeStatus($project: String, $entity: String, $name: String!) {
            model(name: $project, entityName: $entity) {
                id
                name
                entity {
                    id
                    name
                }

                bucket(name: $name, missingOk: true) {
                    id
                    name
                    summaryMetrics
                    displayName
                    logLineCount
                    historyLineCount
                    eventsLineCount
                    historyTail
                    eventsTail
                    config
                    tags
                    wandbConfig(keys: ["t"])
                }
            }
        }
        )rg   ri   r9   r  r  r  Nri   rg   r9   )r   r;  )r   rg   r  r9   rR  r  ri   r1  rE   rE   rF   run_resume_status  s$   	zApi.run_resume_statusr   c           	      C   sR   t d}| j ||||dd}|dd }|sdS |dd }|s#dS |d }|S )Na  
        query RunStoppedStatus($projectName: String, $entityName: String, $runId: String!) {
            project(name:$projectName, entityName:$entityName) {
                run(name:$runId) {
                    stopped
                }
            }
        }
        )projectName
entityNamerunIdr  ri   Fr=  stoppedrZ  )	r   r  r   r  rR  r  ri   r=  statusrE   rE   rF   check_stop_requested^  s$   	zApi.check_stop_requestedc                 C   s   t dd| dS )Nz\W+-z-_)resublowerstripr   ri   rE   rE   rF   format_project  s   zApi.format_projectrI   descriptionc                 C   s@   t d}| j || ||p| d||dd}|d d }|S )zCreate a new project.

        Args:
            project (str): The project to create
            description (str, optional): A description of this project
            entity (str, optional): The entity to scope this project to.
        ap  
        mutation UpsertModel($name: String!, $id: String, $entity: String!, $description: String, $repo: String)  {
            upsertModel(input: { id: $id, name: $name, entityName: $entity, description: $description, repo: $repo }) {
                model {
                    name
                    description
                }
            }
        }
        rg   )r9   rg   r  rI   r  upsertModelr  )r   r  r   )r   ri   rI   r  rg   r  r  r1  rE   rE   rF   upsert_project  s   zApi.upsert_projectc                 C   sJ   t d}d|i}|  ||}|dd u rtd| d|d d }|S )Nz
            query EntityIsTeam($entity: String!) {
                entity(name: $entity) {
                    id
                    isTeam
                }
            }
            rg   zError fetching entity z* check that you have access to this entityisTeamr   r~   r  )r   rg   rR  r  r  is_teamrE   rE   rF   entity_is_team  s   
zApi.entity_is_teamc                 C   sr   t d}||d}|  ||}|dd u r1|dkr$d| d}t|d| d| d}t||d d }|S )	Na@  
        query ProjectRunQueues($entity: String!, $projectName: String!){
            project(entityName: $entity, name: $projectName) {
                runQueues {
                    id
                    name
                    createdBy
                    access
                }
            }
        }
        )r  rg   ri   r4   zError fetching run queues for z6 check that you have access to this entity and projectr>  	runQueuesr  )r   rg   ri   rR  r  r  msgproject_run_queuesrE   rE   rF   get_project_run_queues  s"   

zApi.get_project_run_queuesresourcer  template_variablesc                 C   s   |   st |  \}}d}d}|r|d7 }|d7 }n|d ur$td|||d}	|r<|d ur8t||	d< nd|	d< td	| d
| d}
| |
|	d }|S )Nzl
            $entityName: String!,
            $resource: String!,
            $config: JSONString!
        zk
            entityName: $entityName,
            resource: $resource,
            config: $config
        z , $templateVariables: JSONStringz', templateVariables: $templateVariablesSserver does not support template variables, please update server instance to >=0.46)r  r  r  templateVariablesr   z;
        mutation createDefaultResourceConfig(
            z[
        ) {
            createDefaultResourceConfig(
            input: {
                zw
            }
            ) {
            defaultResourceConfigID
            success
            }
        }
        rs  )rt  r  rr  r   r   dumpsr   )r   rg   r  r  r  supports_template_varsrf  mutation_paramsmutation_inputsr  rR  r1  rE   rE   rF   create_default_resource_config  s>   

z"Api.create_default_resource_config
queue_nameaccessprioritization_mode	config_idc                 C   s   |   \}}}	|std|s|d urtd|	s!|d ur!td|	r1td}
||||||d}ntd}
|||||d}| |
|d }|S )	Nzmrun queue creation is not supported by this version of wandb server. Consider updating to the latest version.z{default resource configurations are not supported by this version of wandb server. Consider updating to the latest version.zplaunch prioritization is not supported by this version of wandb server. Consider updating to the latest version.aF  
            mutation createRunQueue(
                $entity: String!,
                $project: String!,
                $queueName: String!,
                $access: RunQueueAccessType!,
                $prioritizationMode: RunQueuePrioritizationMode,
                $defaultResourceConfigID: ID,
            ) {
                createRunQueue(
                    input: {
                        entityName: $entity,
                        projectName: $project,
                        queueName: $queueName,
                        access: $access,
                        prioritizationMode: $prioritizationMode
                        defaultResourceConfigID: $defaultResourceConfigID
                    }
                ) {
                    success
                    queueID
                }
            }
            )rg   ri   	queueNamer  rd  r]  a  
            mutation createRunQueue(
                $entity: String!,
                $project: String!,
                $queueName: String!,
                $access: RunQueueAccessType!,
                $defaultResourceConfigID: ID,
            ) {
                createRunQueue(
                    input: {
                        entityName: $entity,
                        projectName: $project,
                        queueName: $queueName,
                        access: $access,
                        defaultResourceConfigID: $defaultResourceConfigID
                    }
                ) {
                    success
                    queueID
                }
            }
            )rg   ri   r  r  r]  re  )rh  r   r   )r   rg   ri   r  r  r  r  create_run_queuesupports_drcsupports_prioritizationrR  r  r1  rE   rE   rF   r  0  sR   	
zApi.create_run_queueresource_typeresource_configexternal_linksc	              
   C   sd   |   stdtd}	||||t||rt|nd ||r$t|nd d}
| |	|
}|d S )Nzoupserting run queues is not supported by this version of wandb server. Consider updating to the latest version.a  
            mutation upsertRunQueue(
                $entityName: String!
                $projectName: String!
                $queueName: String!
                $resourceType: String!
                $resourceConfig: JSONString!
                $templateVariables: JSONString
                $prioritizationMode: RunQueuePrioritizationMode
                $externalLinks: JSONString
                $clientMutationId: String
            ) {
                upsertRunQueue(
                    input: {
                        entityName: $entityName
                        projectName: $projectName
                        queueName: $queueName
                        resourceType: $resourceType
                        resourceConfig: $resourceConfig
                        templateVariables: $templateVariables
                        prioritizationMode: $prioritizationMode
                        externalLinks: $externalLinks
                        clientMutationId: $clientMutationId
                    }
                ) {
                    success
                    configSchemaValidationErrors
                }
            }
            )r  r  r  resourceTyperesourceConfigr  rd  externalLinksrj  )rm  r   r   r   r  )r   r  rg   r  r  ri   r  r  r  rR  r  r1  rE   rE   rF   upsert_run_queue  s$   !zApi.upsert_run_queuerun_specrq  c              
   C   s~  |    	 d}d}||||d}	| jr$|d ur#||	d< |d7 }|d7 }n|d ur,td| jrF|d urE|	dt|i |d	7 }|d
7 }n|d urNtdtd| d| d}
z&| j|
|	tj	d
d}|skW d S |
dr}tt|d }||d< |W S  ty } zdt|vrW Y d }~d S W Y d }~nd }~ww td}z| j||	tj	d
d}W |S  ty   d }Y |S w )Nz
            $entityName: String!,
            $projectName: String!,
            $queueName: String!,
            $runSpec: JSONString!
        z
            entityName: $entityName,
            projectName: $projectName,
            queueName: $queueName,
            runSpec: $runSpec
        )r  r  r  runSpecrq  z, $priority: Intz, priority: $priorityzIserver does not support priority, please update server instance to >=0.46ro  %, $templateVariableValues: JSONString1, templateVariableValues: $templateVariableValuesr  z2
        mutation pushToRunQueueByName(
          z\
        ) {
            pushToRunQueueByName(
                input: {
                    zz
                }
            ) {
                runQueueItemId
                runSpec
            }
        }
        )r   pushToRunQueueByNamer  zBCannot query field "runSpec" on type "PushToRunQueueByNamePayload"a  
        mutation pushToRunQueueByName(
            $entityName: String!,
            $projectName: String!,
            $queueName: String!,
            $runSpec: JSONString!,
        ) {
            pushToRunQueueByName(
                input: {
                    entityName: $entityName,
                    projectName: $projectName,
                    queueName: $queueName,
                    runSpec: $runSpec
                }
            ) {
                runQueueItemId
            }
        }
        )rr  r   r   r   r   r   r  r   r   no_retry_4xxr~   r   rB   r  )r   rg   ri   r  r  r  rq  r  mutation_input	variablesr  r1  r  mutation_no_runspecrE   rE   rF   push_to_run_queue_by_name  s   

zApi.push_to_run_queue_by_namelaunch_specproject_queuec                    s     |dp|d }t|}|| |||}|r |S |d ur&d S 	 ||}	 fdd|	D }
|
s dkrrtd| d| d j|d | d	d
}|d u s_|dd u rmt	d| d| d d S |d }n2|dkr}d  d}n	d| d  d}t
| d S t|
dkrt	d  d d S |
d d }t|}||d}d}d}jr|d ur|d7 }|d7 }|dt|i n|d urtdtd| d| d }j||d!}|d"std#  d$|d" }|S )%Nqueue_entityrg   c                    s6   g | ]}|d   kr|d dv s|d j kr|qS )r9   r  )PROJECTUSER	createdBy)r'  rH  qr  r   rE   rF   rJ  n  s    z)Api.push_to_run_queue.<locals>.<listcomp>r   z&No default queue existing for entity: z in project: z, creating one.r  r  queueIDz+Unable to create default queue for entity: z on project: z#. Run could not be added to a queuer4   zUnable to push to run queue z. Queue not found.r>  r0   z+. More than one queue found with this name.r   rI   )r  r  zF
            $queueID: ID!,
            $runSpec: JSONString!
        zF
            queueID: $queueID,
            runSpec: $runSpec
        r  r  ro  r  z.
        mutation pushToRunQueue(
            zE
            ) {
            pushToRunQueue(
                input: {zQ}
            ) {
                runQueueItemId
            }
        }
        r  pushToRunQueuez&Error pushing run queue item to queue .)rr  r~   r   r  r  r  r{   termlogr  r  termwarnr   r   r   r   r   r   )r   r  r  r  r  rq  rg   r  push_resultqueues_foundmatching_queuesr  queue_id_msg	spec_jsonr  r  r   r  r  r1  rE   r  rF   push_to_run_queueT  s   	






zApi.push_to_run_queueagent_idc                 C   s,   t d}| j |||||dd}|d }|S )Na  
        mutation popFromRunQueue($entity: String!, $project: String!, $queueName: String!, $launchAgentId: ID)  {
            popFromRunQueue(input: {
                entityName: $entity,
                projectName: $project,
                queueName: $queueName,
                launchAgentId: $launchAgentId
            }) {
                runQueueItemId
                runSpec
            }
        }
        )rg   ri   r  launchAgentIdr  popFromRunQueuer  )r   r  rg   ri   r  r  r  r1  rE   rE   rF   pop_from_run_queue  s   	zApi.pop_from_run_queueitem_idc                 C   sD   t d}| j ||t|dd}|d d std|d d }|S )Nz
        mutation ackRunQueueItem($itemId: ID!, $runId: String!)  {
            ackRunQueueItem(input: { runQueueItemId: $itemId, runName: $runId }) {
                success
            }
        }
        )itemIdr  r  ackRunQueueItemr  zWError acking run queue item. Item may have already been acknowledged by another process)r   rB   r   )r   r  r  r  r  r1  rE   rE   rF   ack_run_queue_item  s   	zApi.ack_run_queue_itemc                 C   rw  )Na
  
           query ProbeServerCreateLaunchAgentInput {
                CreateLaunchAgentInputInfoType: __type(name:"CreateLaunchAgentInput") {
                    inputFields{
                        name
                    }
                }
            }
        c                 S   rD  rE  rF  rG  rE   rE   rF   rJ    rK  z@Api.create_launch_agent_fields_introspection.<locals>.<listcomp>CreateLaunchAgentInputInfoTyperW  )r   r   r~   rP  rE   rE   rF   (create_launch_agent_fields_introspection   rz  z,Api.create_launch_agent_fields_introspectionqueuesagent_configversiongorilla_agent_supportc                    sN  |  ||}|s/| j||ddd}|d u s|dd u r'td| d| d|d ddg} fd	d
|D }	t|	t krUtdd  dddd
 |D  |s\dd dS t }
|||	|
d}d}d}d|  v rt	
||d< |d7 }|d7 }d|  v r||d< |d7 }|d7 }td| d| d}| ||d }|S )Nr   r  r  r  z#Unable to create default queue for r>  z. No queues for agent to poll)rI   r9   c                    s    g | ]}|d   v r|d qS )r9   rI   rE   r
  r$  rE   rF   rJ  .  s    z+Api.create_launch_agent.<locals>.<listcomp>z;Could not start launch agent: Not all of requested queues (, z,) found. Available queues for this project: ,c                 S   r^  r_  rE   r
  rE   rE   rF   rJ  4      T)r  r  )rg   ri   r$  hostnamez
            $entity: String!,
            $project: String!,
            $queues: [ID!]!,
            $hostname: String!
        z
            entityName: $entity,
            projectName: $project,
            runQueues: $queues,
            hostname: $hostname
        agentConfigz, $agentConfig: JSONStringz, agentConfig: $agentConfigr&  z, $version: Stringz, version: $versionz9
            mutation createLaunchAgent(
                zi
            ) {
                createLaunchAgent(
                    input: {
                        zy
                    }
                ) {
                    launchAgentId
                }
            }
            createLaunchAgent)r  r  r~   r   r   rw   socketgethostnamer#  r   r  r   )r   rg   ri   r$  r%  r&  r'  project_queuesr   polling_queue_idsr,  r  r  r   r  r1  rE   r(  rF   create_launch_agent  s`   

zApi.create_launch_agentr  c                 C   s2   |sddiS t d}||d}|  ||d }|S )Nr  Tab  
            mutation updateLaunchAgent($agentId: ID!, $agentStatus: String){
                updateLaunchAgent(
                    input: {
                        launchAgentId: $agentId
                        agentStatus: $agentStatus
                    }
                ) {
                    success
                }
            }
            )agentIdagentStatusupdateLaunchAgentr  )r   r  r  r'  r  r  r1  rE   rE   rF   update_launch_agent_statusp  s   zApi.update_launch_agent_statusc                 C   s4   |sd dddS t d}d|i}|  ||d }|S )Nr   F)rI   r9   stopPollingaS  
            query LaunchAgent($agentId: ID!) {
                launchAgent(id: $agentId) {
                    id
                    name
                    runQueues
                    hostname
                    agentStatus
                    stopPolling
                    heartbeatAt
                }
            }
            r4  launchAgentr  )r   r  r'  rR  r  r1  rE   rE   rF   get_launch_agent  s   zApi.get_launch_agenthostgrouptagsstater   notesrepojob_typeprogram_pathr  
sweep_namesummary_metricsnum_retriesc                  C   s  d}|    | jrdnd}|d|}t|}|rt|nd}|r&| r(d}i }|dur2||d< i d|d|	p=| dd	|d
|pHt	|d|d|d|d|d|d|d|d|  
ddv rjdn|dtj| jdd|d|d|d|
||d}tjtjtjddtjd}| j|f||d|}|d  d! }|
d
i }|r| d
|d	  |
di }|r| d|d	  d}| jr|d  
d"i 
d#g }|d  d! |d  d$ |fS )%a  Update a run.

        Args:
            id (str, optional): The existing run to update
            name (str, optional): The name of the run to create
            group (str, optional): Name of the group this run is a part of
            project (str, optional): The name of the project
            host (str, optional): The name of the host
            tags (list, optional): A list of tags to apply to the run
            config (dict, optional): The latest config params
            description (str, optional): A description of this project
            entity (str, optional): The entity to scope this project to.
            display_name (str, optional): The display name of this project
            notes (str, optional): Notes about this run
            repo (str, optional): Url of the program's repository.
            state (str, optional): State of the program.
            job_type (str, optional): Type of job, e.g 'train'.
            program_path (str, optional): Path to the program.
            commit (str, optional): The Git SHA to associate the run with
            sweep_name (str, optional): The name of the sweep this run is a part of
            summary_metrics (str, optional): The JSON summary metrics
            num_retries (int, optional): Number of retries
        ad  
        mutation UpsertBucket(
            $id: String,
            $name: String,
            $project: String,
            $entity: String,
            $groupName: String,
            $description: String,
            $displayName: String,
            $notes: String,
            $commit: String,
            $config: JSONString,
            $host: String,
            $debug: Boolean,
            $program: String,
            $repo: String,
            $jobType: String,
            $state: String,
            $sweep: String,
            $tags: [String!],
            $summaryMetrics: JSONString,
        ) {
            upsertBucket(input: {
                id: $id,
                name: $name,
                groupName: $groupName,
                modelName: $project,
                entityName: $entity,
                description: $description,
                displayName: $displayName,
                notes: $notes,
                config: $config,
                commit: $commit,
                host: $host,
                debug: $debug,
                jobProgram: $program,
                jobRepo: $repo,
                jobType: $jobType,
                state: $state,
                sweep: $sweep,
                tags: $tags,
                summaryMetrics: $summaryMetrics,
            }) {
                bucket {
                    id
                    name
                    displayName
                    description
                    config
                    sweepName
                    project {
                        id
                        name
                        entity {
                            id
                            name
                        }
                    }
                    historyLineCount
                }
                inserted
                _Server_Settings_
            }
        }
        z
        serverSettings {
                serverMessages{
                    utfText
                    plainText
                    htmlText
                    messageType
                    messageLevel
                }
         }
        r   _Server_Settings_NrE  rI   rg   r9   ri   	groupNamer=  r  r  r  rJ   r?  r;  	anonymous)allowmustdebugr   r@  programjobTyper>  )r  summaryMetricsr*   minutescheck_fncheck_timedeltafallback_retry_fnr  r   upsertBucketr  serverSettingsserverMessagesinserted)rU  r   r  r   r   r  isspacer   r   auto_project_namer~   r   is_debugr   make_check_retry_fncheck_retry_conflict_or_gonedatetime	timedeltar   r;  ) r   rI   r9   ri   r;  r<  r=  r  r  rg   r>  r   r?  r@  rA  rB  r  rC  rD  rE  rQ  server_settings_stringr  
config_strr   r  r   r  r  project_obj
entity_objserver_messagesrE   rE   rF   
upsert_run  s   .A	



zApi.upsert_runrun_namemetric_namemetric_valuec                 C   s   d}t |}	i }
|dur||
d< ||p| d|pt|||d}tjtjtjddtjd}| j |	f||d	|
}|	d
i 	di }|	di }|rf| 
d|d  |	di }|rf| 
d|d  |S )a  Rewinds a run to a previous state.

        Args:
            run_name (str): The name of the run to rewind
            metric_name (str): The name of the metric to rewind to
            metric_value (float): The value of the metric to rewind to
            program_path (str, optional): Path to the program
            entity (str, optional): The entity to scope this project to
            project (str, optional): The name of the project
            num_retries (int, optional): Number of retries

        Returns:
            A dict with the rewound run

                {
                    "id": "run_id",
                    "name": "run_name",
                    "displayName": "run_display_name",
                    "description": "run_description",
                    "config": "stringified_run_config_json",
                    "sweepName": "run_sweep_name",
                    "project": {
                        "id": "project_id",
                        "name": "project_name",
                        "entity": {
                            "id": "entity_id",
                            "name": "entity_name"
                        }
                    },
                    "historyLineCount": 100,
                }
        a  
        mutation RewindRun($runName: String!, $entity: String, $project: String, $metricName: String!, $metricValue: Float!) {
            rewindRun(input: {runName: $runName, entityName: $entity, projectName: $project, metricName: $metricName, metricValue: $metricValue}) {
                rewoundRun {
                    id
                    name
                    displayName
                    description
                    config
                    sweepName
                    project {
                        id
                        name
                        entity {
                            id
                            name
                        }
                    }
                    historyLineCount
                }
            }
        }
        NrE  rg   )runNamerg   ri   
metricNamemetricValuer*   rO  rQ  rU  	rewindRun
rewoundRunri   r9   )r   r   r   r[  r]  r^  r_  r`  r   r~   r;  )r   rg  rh  ri  rB  rg   ri   rE  rQ  r  r   r  r   r  r  rc  rd  rE   rE   rF   
rewind_runx	  sH   +	
zApi.rewind_runc                 C   s   t d}|||d}|  ||}|dd u r%td| d| d| d|d dd u r<td| d| d| d|d d d	 }|S )
Na  
        query RunInfo($project: String!, $entity: String!, $name: String!) {
            project(name: $project, entityName: $entity) {
                run(name: $name) {
                    runInfo {
                        program
                        args
                        os
                        python
                        colab
                        executable
                        codeSaved
                        cpuCount
                        gpuCount
                        gpu
                        git {
                            remote
                            commit
                        }
                    }
                }
            }
        }
        ri   rg   r9   ri   zError fetching run info for r>  O. Check that this project exists and you have access to this entity and projectr=  z. Check that this run id existsrunInfor   r~   r   )r   rg   ri   r9   rR  r  r  run_inforE   rE   rF   get_run_info	  s   zApi.get_run_infoc                 C   sp   t d}|||d}|  ||}|dd u s |d dd u r.td| d| d| d|d d d }|S )	Na  
        query RunState(
            $project: String!,
            $entity: String!,
            $name: String!) {
            project(name: $project, entityName: $entity) {
                run(name: $name) {
                    state
                }
            }
        }
        rp  ri   r=  zError fetching run state for r>  r  r>  rs  )r   rg   ri   r9   rR  r  r  	run_staterE   rE   rF   get_run_state
  s    zApi.get_run_statec                 C   ri  )NcreateRunFilesrk  rl  rE   rE   rF   create_run_files_introspection,
  rn  z"Api.create_run_files_introspectionr  c                 C   s   |p| j }|sJ d|p| d}|sJ d|  }|s'| |||||S td}| j||||dd |D dd}	|	d	 }
|
d
 }|sTtd| d| d| ddd |
d D }||
d |fS )a  Generate temporary resumable upload urls.

        Args:
            project (str): The project to download
            files (list or dict): The filenames to upload
            run (str, optional): The run to upload to
            entity (str, optional): The entity to scope this project to.
            description (str, optional): description

        Returns:
            (run_id, upload_headers, file_info)
            run_id: id of run we uploaded files to
            upload_headers: A list of headers to use when uploading files.
            file_info: A dict of filenames and urls.
                {
                    "run_id": "run_id",
                    "upload_headers": [""],
                    "file_info":  [
                        { "weights.h5": { "uploadUrl": "https://weights.url" } },
                        { "model.json": { "uploadUrl": "https://model.json" } }
                    ]
                }
        r?  rg   zentity must be specifieda  
        mutation CreateRunFiles($entity: String!, $project: String!, $run: String!, $files: [String!]!) {
            createRunFiles(input: {entityName: $entity, projectName: $project, runName: $run, files: $files}) {
                runID
                uploadHeaders
                files {
                    name
                    uploadUrl
                }
            }
        }
        c                 S      g | ]}|qS rE   rE   rH  filerE   rE   rF   rJ  o
      z#Api.upload_urls.<locals>.<listcomp>)ri   r=  rg   r  r  rx  runIDzError uploading files to r>  rq  c                 S      i | ]}|d  |qS r_  rE   r{  rE   rE   rF   r  y
  s    z#Api.upload_urls.<locals>.<dictcomp>r  rL   )r  r   ry  legacy_upload_urlsr   r   )r   ri   r  r=  rg   r  rg  has_create_run_files_mutationrR  query_resultr1  r  file_name_urlsrE   rE   rF   upload_urls1
  s4   
 
zApi.upload_urlsc                 C   s   t d}|p| j}|sJ d|p| d}| j ||||dd |D |dd}|d d	 }	|	rc|	d
 d D ]}
|
d }d|v rKd|vrK|d|d< q6dd | |	d
 D }|	d |	d
 d |fS td| d| d| d)zGenerate temporary resumable upload urls.

        A new mutation createRunFiles was introduced after 0.15.4.
        This function is used to support older versions.
        a  
        query RunUploadUrls($name: String!, $files: [String]!, $entity: String, $run: String!, $description: String) {
            model(name: $name, entityName: $entity) {
                bucket(name: $run, desc: $description) {
                    id
                    files(names: $files) {
                        uploadHeaders
                        edges {
                            node {
                                name
                                url(upload: true)
                                updatedAt
                            }
                        }
                    }
                }
            }
        }
        r?  rg   c                 S   rz  rE   rE   r{  rE   rE   rF   rJ  
  r}  z*Api.legacy_upload_urls.<locals>.<listcomp>)r9   r=  rg   r  r  r  r  r  r  r  r  r   rK   c                 S   r  r_  rE   r{  rE   rE   rF   r  
  s    
z*Api.legacy_upload_urls.<locals>.<dictcomp>rI   rL   Run does not exist r>  r  )r   r  r   popr  r   )r   ri   r  r=  rg   r  rR  r  r  r  	file_noder|  r1  rE   rE   rF   r  |
  s6   
zApi.legacy_upload_urlsc                 C   s   t d}|p| j}|sJ d|p| d}| j ||||dd}|d du r5td| d	| d	| d
| |d d d }dd |D S )ao  Generate download urls.

        Args:
            project (str): The project to download
            run (str): The run to upload to
            entity (str, optional): The entity to scope this project to.  Defaults to wandb models

        Returns:
            A dict of extensions and urls

                {
                    'weights.h5': { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' },
                    'model.json': { "url": "https://model.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }
                }
        a#  
        query RunDownloadUrls($name: String!, $entity: String, $run: String!)  {
            model(name: $name, entityName: $entity) {
                bucket(name: $run) {
                    files {
                        edges {
                            node {
                                name
                                url
                                md5
                                updatedAt
                            }
                        }
                    }
                }
            }
        }
        r?  rg   )r9   r=  rg   r  r  Nr  r>  r  r  r  c                 S   s   i | ]	}|r|d  |qS r_  rE   r{  rE   rE   rF   r  
  r  z%Api.download_urls.<locals>.<dictcomp>)r   r  r   r   r  )r   ri   r=  rg   rR  r  r  rE   rE   rF   download_urls
  s"   
zApi.download_urls	file_namec                 C   s   t d}|p| j}|sJ d| j |||||p| ddd}|d rB| |d d d }t|d	kr@|d	 d
r@|d	 S dS dS )a  Generate download urls.

        Args:
            project (str): The project to download
            file_name (str): The name of the file to download
            run (str): The run to upload to
            entity (str, optional): The entity to scope this project to.  Defaults to wandb models

        Returns:
            A dict of extensions and urls

                { "url": "https://weights.url", "updatedAt": '2013-04-26T22:22:23.832Z', 'md5': 'mZFLkyvTelC5g8XnyQrpOw==' }

        aJ  
        query RunDownloadUrl($name: String!, $fileName: String!, $entity: String, $run: String!)  {
            model(name: $name, entityName: $entity) {
                bucket(name: $run) {
                    files(names: [$fileName]) {
                        edges {
                            node {
                                name
                                url
                                md5
                                updatedAt
                            }
                        }
                    }
                }
            }
        }
        r?  rg   )r9   r=  fileNamerg   r  r  r  r  r   	updatedAtN)r   r  r   r  r   r~   )r   ri   r  r=  rg   rR  r  r  rE   rE   rF   download_url
  s"   
	&zApi.download_urlr   c                 C   s   t   tjpi }d}| jdurd| j |d< ntjdu r$d| jp"df}tj||tjp,i |dd}|  t	|jdd	|fS )
zInitiate a streaming download.

        Args:
            url (str): The url to download

        Returns:
            A tuple of the content length and the streaming response
        Nr   r   r   r   T)r   r   r   streamzcontent-lengthr   )
r   r&   r   r   r   rf   r   r~   r  rY   )r   r   http_headersr   r  rE   rE   rF   download_file1  s    



zApi.download_filer  out_dirc           	      C   s   |d }t j|p| d|}| |t|d r|dfS | |d \}}t|d}|j	ddD ]}|
| q4W d   ||fS 1 sIw   Y  ||fS )	a  Download a file from a run and write it to wandb/.

        Args:
            metadata (obj): The metadata object for the file to download. Comes from Api.download_urls().
            out_dir (str, optional): The directory to write the file to. Defaults to wandb/

        Returns:
            A tuple of the file's local path and the streaming response. The streaming response is None if the file
            already existed and was up-to-date.
        r9   	wandb_dirr:   Nr   wbi   )
chunk_size)r|   pathrw   r   file_currentr(   r  r   
fsync_openiter_contentwrite)	r   r  r  r  r  sizer  r|  r  rE   rE   rF   download_write_fileO  s   
zApi.download_write_filer|  extra_headersc           
   
   C   s   ddl m} | jjj|| jjddd}z+|ddur$t|d }nd}| jj	||dd}|j
|d	t|d
|d W dS  |yo } z$t|drdtj }	|jj|	_|jj|	_tjj|j|	dtj|jd}~ww )zUpload a file to azure.r   )
AzureError)retry_total)retry_policyzContent-MD5NzContent-Type)content_md5content_type   T)max_concurrencylength	overwritecontent_settingsr  )r  )azure.core.exceptionsr  r   
BlobClientfrom_blob_urlLinearRetryr~   base64	b64decodeContentSettingsupload_blobr   hasattrr   r  Responser  status_coder   r  r   r|  ConnectionError)
r   r   r|  r  r  r   r:   r  r  r  rE   rE   rF   upload_file_azurel  s8   



zApi.upload_file_azureupload_chunkc           
   
   C   s"  t   z*tj| jdrtd| | jj|||d}tj| jdr'td| |  W |S  t	j
jy } zUtd| |jdurH|jjnd}|jdurS|jjnd}|d	ko^d
t|v }|dv spt|t	j
jt	j
jfsp|rtj|d}	|	t d tj| W Y d}~|S d}~ww )aH  Upload a file chunk to S3 with failure resumption.

        Args:
            url: The url to download
            upload_chunk: The path to the file you want to upload
            extra_headers: A dictionary of extra headers to send with the request

        Returns:
            The `requests` library response object
        r   upload_file: %sr  r   upload_file: %s completeupload_file exception for url=Nr   r     RequestTimeouti4  i  i  i  i  i  i  i  excr*   )r   r   r\  r   r	  rK  r   r   r  r   r  r   r
  r  contentr  rB   r  Timeoutr  r,   TransientErrorwith_tracebacksysexc_infor{   _sentryreraise)
r   r   r  r  r  r  response_contentr  is_aws_retryable_erE   rE   rF   r     s@   
zApi.upload_multipart_file_chunkcallbackr6   c              
   C   s  t   |r	| ni }d}t||d}zFd|v r%| jr%| ||| W |S d|v r0tjddd tj| j	dr=t
d| | jj|||d	}tj| j	drSt
d
| |  W |S  tjjy } z]t
d| |jdurt|jjnd}|jdur|jjnd}	d|v o|	dkodt|v }
|  |	dv st|tjjtjjfs|
rtj|d}|t d tj !| W Y d}~|S d}~ww )a  Upload a file to W&B with failure resumption.

        Args:
            url: The url to download
            file: The path to the file you want to upload
            callback: A callback which is passed the number of
            bytes uploaded since the last time it was called, used to report progress
            extra_headers: A dictionary of extra headers to send with the request

        Returns:
            The `requests` library response object
        N)r  zx-ms-blob-typezUAzure uploads over 256MB require the azure SDK, install with pip install wandb[azure]F)repeatr   r  r  r  r  r   r   zx-amz-meta-md5r  r  r  r  r*   )"r   r)  r3   r   r  r{   r  r   r\  r   r	  rK  r   r   r  r   r  r   r
  r  r  r  rB   rewindr  r  r  r,   r  r  r  r  r  r  )r   r   r|  r  r  r  progressr  r  r  r  r  rE   rE   rF   r     s\   )

zApi.upload_filesweep_idc                 C   sX   t d}|du r| d}|du r| d}| j |||||dtjd}|d d }|S )	zRegister a new agent.

        Args:
            host (str): hostname
            sweep_id (str): sweep id
            project_name: (str): model that contains sweep
            entity: (str): entity that contains sweep
        a  
        mutation CreateAgent(
            $host: String!
            $projectName: String,
            $entityName: String,
            $sweep: String!
        ) {
            createAgent(input: {
                host: $host,
                projectName: $projectName,
                entityName: $entityName,
                sweep: $sweep,
            }) {
                agent {
                    id
                }
            }
        }
        Nrg   ri   )r;  r  r  r  rU  createAgentagent)r   r   r   r  )r   r;  r  r  rg   r  r  r1  rE   rE   rF   register_agent  s$   


zApi.register_agentmetrics
run_statesc                 C   sx   t d}|du rtdz| j ||t|t|ddd}W n ty0   td g  Y S w t|d d	 }|S )
a	  Notify server about agent state, receive commands.

        Args:
            agent_id (str): agent_id
            metrics (dict): system metrics
            run_states (dict): run_id: state mapping
        Returns:
            List of commands to execute.
        a  
        mutation Heartbeat(
            $id: ID!,
            $metrics: JSONString,
            $runState: JSONString
        ) {
            agentHeartbeat(input: {
                id: $id,
                metrics: $metrics,
                runState: $runState
            }) {
                agent {
                    id
                }
                commands
            }
        }
        Nz1Cannot call heartbeat with an unregistered agent.)rI   r  runState<   r  r   zError communicating with W&B.agentHeartbeatcommands)r   r   r   r  r  r	  r
  r   )r   r  r  r  r  r  r1  rE   rE   rF   agent_heartbeat;  s,   
	

zApi.agent_heartbeatc                 C   s   t | } t| } d| vr| S | d D ]B}| d | }d|v rTd|v rTd|vrTt|d tr9t|d tr9d|d< qt|d trLt|d trLd|d< qtd| dq| S )	N
parametersminmaxdistributionint_uniformuniformz
Parameter z is ambiguous, please specify bounds as both floats (for a float_uniform distribution) or ints (for an int_uniform distribution).)r   dictr  rY   floatr   )r  parameter_name	parameterrE   rE   rF   &_validate_config_and_fill_distributionr  s*   	


z*Api._validate_config_and_fill_distribution
controllerlaunch_scheduler	schedulerobj_id
prior_runstemplate_variable_valuesc                 C   s  d}d}t |ddddd|}t |dddd	d|}t |d|}t |d|d
d}t |ddd
d}|||||g}| |}tjtt|tj	d}d}|	rntddd |	D i}d}|D ]N}z.|||
d|p| d|p| d||t|
||d
}|r||d< | j ||tjd}W n ty     ty } z|}W Y d}~qrd}~ww d} |r||d d }|
di }|r| d|d  |
di }|r| d|d  |d 
d
g }|d d d |fS )a/  Upsert a sweep object.

        Args:
            config (dict): sweep config (will be converted to yaml)
            controller (str): controller to use
            launch_scheduler (str): launch scheduler to use
            scheduler (str): scheduler to use
            obj_id (str): object id
            project (str): project to use
            entity (str): entity to use
            state (str): state
            prior_runs (list): IDs of existing runs to add to the sweep
            template_variable_values (dict): template variable values
        z
            project {
                id
                name
                entity {
                    id
                    name
                }
            }
        a  
        mutation UpsertSweep(
            $id: ID,
            $config: String,
            $description: String,
            $entityName: String,
            $projectName: String,
            $controller: JSONString,
            $scheduler: JSONString,
            $state: String,
            $priorRunsFilters: JSONString,
        ) {
            upsertSweep(input: {
                id: $id,
                config: $config,
                description: $description,
                entityName: $entityName,
                projectName: $projectName,
                controller: $controller,
                scheduler: $scheduler,
                state: $state,
                priorRunsFilters: $priorRunsFilters,
            }) {
                sweep {
                    name
                    _PROJECT_QUERY_
                }
                configValidationWarnings
            }
        }
        z$controller: JSONString,zZ$controller: JSONString,$launchScheduler: JSONString, $templateVariableValues: JSONString,zcontroller: $controller,zjcontroller: $controller,launchScheduler: $launchScheduler,templateVariableValues: $templateVariableValues,_PROJECT_QUERY_z5$controller: JSONString,$launchScheduler: JSONString,z9controller: $controller,launchScheduler: $launchSchedulerconfigValidationWarningsr   )DumperNz$orc                 S   s   g | ]}d |iqS r_  rE   )rH  rrE   rE   rF   rJ    r+  z$Api.upsert_sweep.<locals>.<listcomp>r  rg   ri   )
rI   r  r  r  r  r  launchSchedulerro  r  priorRunsFiltersr>  rU  upsertSweepr  r9   )r   r  r  yamldumpr   r   r  r   NonOctalStringDumperr~   r   r  r   r  r;  )r   r  r  r  r  r  ri   rg   r>  r  r  project_querymutation_str
mutation_5
mutation_4
mutation_3
mutation_2
mutation_1rg  rb  filtersr  r  r  r  r  r  rc  rd  warningsrE   rE   rF   upsert_sweep  s   
!

zApi.upsert_sweepc                 C   s.   t d}| j |i d}t|d d d }|S )z7Create a new API key belonging to a new anonymous user.z
        mutation CreateAnonymousApiKey {
            createAnonymousEntity(input: {}) {
                apiKey {
                    name
                }
            }
        }
        r  createAnonymousEntityapiKeyr9   )r   rB   )r   r  r  r  rE   rE   rF   create_anonymous_api_key@  s   zApi.create_anonymous_api_keyfnamer:   c                 C   s   t j| ot| |kS )z7Checksum a file and compare the md5 with the known md5.)r|   r  isfiler)   )r   r:   rE   rE   rF   r  S  s   zApi.file_currentzList[requests.Response]c           	      C   sR   | j ||d\}}| |||}g }|D ]}| || \}}|r&|| q|S )aA  Download files from W&B.

        Args:
            project (str): The project to download
            run (str, optional): The run to upload to
            entity (str, optional): The entity to scope this project to.  Defaults to wandb models

        Returns:
            The `requests` library response object
        )r=  )rC  r  r  append)	r   ri   r=  rg   urls	responsesr  rf  r  rE   rE   rF   pullX  s   
zApi.pullc                 C   s   | j dp
| d}|S )Nri   )r   r~   r   r  rE   rE   rF   r.  p  s   zApi.get_projectforcer  z!List[Optional[requests.Response]]c              
      s  |du r|   }|du rtd|du r| j}| ||||\}}	}
i }|	D ]}|dd\}}|||< q&g }|
 D ]\}}|d }|drO| j | }ztj	j
|d }t|trb|| nt|d}W n tyx   t| d Y q;w |d	u r|| j|d ||d
 nJt|r|| j||||d
 n9t| j}tj||d| tjdddd || j|| fdd|d
 W d   n1 sw   Y  |  q;|S )a/  Uploads multiple files to W&B.

        Args:
            files (list or dict): The filenames to upload, when dict the values are open files
            run (str, optional): The run to upload to
            entity (str, optional): The entity to scope this project to.  Defaults to wandb models
            project (str, optional): The name of the project to upload to. Defaults to the one in settings.
            description (str, optional): The description of the changes
            force (bool, optional): Whether to prevent push if git has uncommitted changes
            progress (callable, or stream): If callable, will be called with (chunk_bytes,
                total_bytes) as argument. If TextIO, renders a progress bar to it.

        Returns:
            A list of `requests.Response` objects
        NzNo project configured.:r0   rK   r>  rbz does not existF)r  zUploading file: &green)fg)r|  r  label	fill_charc                    s
     | S r   )r   )bitesrf  barrE   rF   <lambda>  s   
 zApi.push.<locals>.<lambda>)r.  r   r  r  r@  r*  
startswithr  r|   r  rw   r  r  openOSErrorr   r  r   callablefstatfilenost_sizeclickprogressbarstyleclose)r   r  r=  rg   ri   r  r  r  rf  upload_headersr1  r  upload_headerr  valr  r  	file_infofile_urlnormal_name	open_filer  rE   r  rF   pusht  s|   






zApi.push	client_id	server_idportfolio_namealiasesrh   c              
      s   dd}t |r&z	| j||d}W n ty% }	 ztt|	  d }	~	ww dtdtdd ffdd}
|r@|
d	d
 |
dd n|rL|
d	d |
dd || |pR|| fdd|D d}t}| j||d}|d }|S )Na  
                mutation LinkArtifact(
                    $artifactPortfolioName: String!,
                    $entityName: String!,
                    $projectName: String!,
                    $aliases: [ArtifactAliasInput!],
                    ID_TYPE
                    ) {
                        linkArtifact(input: {
                            artifactPortfolioName: $artifactPortfolioName,
                            entityName: $entityName,
                            projectName: $projectName,
                            aliases: $aliases,
                            ID_VALUE
                        }) {
                            versionIndex
                        }
                    }
            r   )rg   rh   abrr   c                    s     | | d S r   r  )r)  r*  )templaterE   rF   r    s   z"Api.link_artifact.<locals>.replaceID_TYPEz$artifactID: IDID_VALUEartifactID: $artifactIDz$clientID: IDzclientID: $clientIDc                    s   g | ]}| d qS ))aliasartifactCollectionNamerE   )rH  r0  )r'  rE   rF   rJ    s    z%Api.link_artifact.<locals>.<listcomp>)clientIDr8   artifactPortfolioNamer  r  r(  r  linkArtifact)r#   _resolve_org_entity_namer   r{   r  rB   r   )r   r%  r&  r'  rg   ri   r(  rh   
org_entityr  r  r  r  r  link_artifactrE   )r'  r,  rF   r7    s@   





zApi.link_artifactr   c                 C   sr   |st d|  }d|v }|s|st d|s|S | |}|r&t||S t|dkr4t d|d|d jS )Nz3Entity name is required to resolve org entity name.	orgEntityzFetching Registry artifacts without inputting an organization is unavailable for your server version. Please upgrade your server to 0.50.0 or later.r0   zPersonal entity z belongs to multiple organizations and cannot be used without specifying the organization name. Please specify the organization in the Registry path or use a team entity in the entity settings.r   )r   &server_organization_type_introspection(_fetch_orgs_and_org_entities_from_entityr   r   r   )r   rg   rh   
org_fieldscan_shorthand_org_entityorgs_from_entityrE   rE   rF   r5    s$   




zApi._resolve_org_entity_namec           
      C   s   t d}| j |d|id}|d d }|d d }|r?|d}|do+|d d}|r0|s8td	|d
t||dgS |rZ|dg }dd |D }	|	sXtd|d|	S td	|d
)a  Fetches organization entity names and display names for a given entity.

        Args:
            entity (str): Entity name to lookup. Can be either a personal or team entity.

        Returns:
            List[_OrgNames]: List of _OrgNames tuples. (_OrgNames(entity_name, display_name))

        Raises:
        ValueError: If entity is not found, has no organizations, or other validation errors.
        aP  
            query FetchOrgEntityFromEntity($entityName: String!) {
                entity(name: $entityName) {
                    organization {
                        name
                        orgEntity {
                            name
                        }
                    }
                    user {
                        organizations {
                            name
                            orgEntity {
                                name
                            }
                        }
                    }
                }
            }
            r  r  rg   rh   userr9   r8  z,Unable to find an organization under entity r  r   r   organizationsc                 S   s8   g | ]}| d r| drt|d  d |d dqS )r8  r9   r?  )r~   r   )rH  orgrE   rE   rF   rJ  }  s    z@Api._fetch_orgs_and_org_entities_from_entity.<locals>.<listcomp>zCUnable to resolve an organization associated with personal entity: z. This could be because its a personal entity that doesn't belong to any organizations. Please specify the organization in the Registry path or use a team entity in the entity settings.)r   r~   r   r   )
r   rg   rR  r  entity_resp	user_resporg_nameorg_entity_namer   org_entities_returnrE   rE   rF   r:  C  sB   


z,Api._fetch_orgs_and_org_entities_from_entityartifact_iduse_asartifact_entity_nameartifact_project_namec                 C   s   g d}g d}	|   }
d|
v r|r|d |	d |p"| d}|p)| d}|p.| j}|||||d}| tj}|rU|d	d
g |	ddg ||d< ||d< d|}d|	}t	d| d| d}||fS )N)z$entityName: String!z$projectName: String!z$runName: String!z$artifactID: ID!)zentityName: $entityNamezprojectName: $projectNamezrunName: $runNamer/  usedAsz$usedAs: StringzusedAs: $usedAsrg   ri   )r  r  rj  r8   rK  z$artifactEntityName: Stringz$artifactProjectName: Stringz'artifactEntityName: $artifactEntityNamez)artifactProjectName: $artifactProjectNameartifactEntityNameartifactProjectNamer)  z"
            mutation UseArtifact(z() {
                useArtifact(input: {a%  }) {
                    artifact {
                        id
                        digest
                        description
                        state
                        createdAt
                        metadata
                    }
                }
            }
            )
rX  r  r   r  r  r"   0USE_ARTIFACT_WITH_ENTITY_AND_PROJECT_INFORMATIONextendrw   r   )r   rG  r   r  rg  rH  rI  rJ  
query_vars
query_argsartifact_typesr  (server_allows_entity_project_informationvars_strargs_strrR  rE   rE   rF   _construct_use_artifact_query  sR   





z!Api._construct_use_artifact_queryc              	   C   sF   |  |||||||\}}	| ||	}
|
d d r!|
d d }|S d S )NuseArtifactrQ   )rV  r   )r   rG  r   r  rg  rI  rJ  rH  rR  r  r  rQ   rE   rE   rF   use_artifact  s   
	zApi.use_artifactc                 C   L   d}| j d u r#t|}| |}|di di g}dd |D | _ | j S )Nz
            query ProbeServerOrganization {
                OrganizationInfoType: __type(name:"Organization") {
                    fields {
                        name
                    }
                }
            }
        OrganizationInfoTyperM  c                 S      g | ]
}d |v r|d  qS r_  rE   rG  rE   rE   rF   rJ        z>Api.server_organization_type_introspection.<locals>.<listcomp>)r   r   r~   r   rQ  rR  r  input_fieldsrE   rE   rF   r9       


z*Api.server_organization_type_introspectionc                 C   sj   | j d ur| j S d}t|}| |}|di di g}tdd |D g }tdd |D | _ | j S )Na8  
            query ProbeServerProjectInfo {
                ProjectInfoType: __type(name:"Project") {
                    fields {
                        name
                        args {
                            name
                        }
                    }
                }
            }
        ProjectInfoTyperM  c                 s   s*    | ]}| d dkr| dg V  qdS )r9   rQ   rs   NrF  rG  rE   rE   rF   	<genexpr>$  s    
z8Api.server_project_type_introspection.<locals>.<genexpr>c                 s   s    | ]
}| d dkV  qdS )r9   enableTrackingNrF  )rH  argrE   rE   rF   ra  +  s    
)r   r   r~   nextany)r   rQ  rR  r  r^  artifact_argsrE   rE   rF   !server_project_type_introspection  s    


z%Api.server_project_type_introspectionartifact_type_namec                 C   sP   t d}|p
| d}|p| d}| j |||||dd}|d d d }|S )	Na  
        mutation CreateArtifactType(
            $entityName: String!,
            $projectName: String!,
            $artifactTypeName: String!,
            $description: String
        ) {
            createArtifactType(input: {
                entityName: $entityName,
                projectName: $projectName,
                name: $artifactTypeName,
                description: $description
            }) {
                artifactType {
                    id
                }
            }
        }
        rg   ri   )r  r  artifactTypeNamer  r  createArtifactTypeartifactTyperI   )r   r   )r   rh  r   r  r  r  r  _idrE   rE   rF   create_artifact_type1  s   	zApi.create_artifact_typec                 C   rY  )Nz
            query ProbeServerArtifact {
                ArtifactInfoType: __type(name:"Artifact") {
                    fields {
                        name
                    }
                }
            }
        ArtifactInfoTyperM  c                 S   r[  r_  rE   rG  rE   rE   rF   rJ  j  r\  z5Api.server_artifact_introspection.<locals>.<listcomp>)r   r   r~   r]  rE   rE   rF   server_artifact_introspection[  r_  z!Api.server_artifact_introspectionc                 C   rY  )Na  
            query ProbeServerCreateArtifactInput {
                CreateArtifactInputInfoType: __type(name:"CreateArtifactInput") {
                    inputFields{
                        name
                    }
                }
            }
        CreateArtifactInputInfoTyperW  c                 S   r[  r_  rE   rG  rE   rE   rF   rJ    r\  z<Api.server_create_artifact_introspection.<locals>.<listcomp>)r   r   r~   r]  rE   rE   rF   $server_create_artifact_introspectionp  s   


z(Api.server_create_artifact_introspectionrM  history_stepdistributed_idc                 C   s   d}d}d|v r|dvr|d7 }|d7 }|r|d7 }|d7 }d|v r*|d	7 }|d
7 }d|v r6|d7 }|d7 }d|v r>|d7 }d|v rJ|d7 }|d7 }d|v rV|d7 }|d7 }d}| d| d|S )Nr   historyStep)r   Nz$historyStep: Int64!,zhistoryStep: $historyStep,z$distributedID: String,zdistributedID: $distributedID,r2  z$clientID: ID,zclientID: $clientID,sequenceClientIDz$sequenceClientID: ID,z$sequenceClientID: $sequenceClientID,enableDigestDeduplicationz enableDigestDeduplication: true,ttlDurationSecondsz$ttlDurationSeconds: Int64,z(ttlDurationSeconds: $ttlDurationSeconds,r=  z$tags: [TagInput!],ztags: $tags,a  
            mutation CreateArtifact(
                $artifactTypeName: String!,
                $artifactCollectionNames: [String!],
                $entityName: String!,
                $projectName: String!,
                $runName: String,
                $description: String,
                $digest: String!,
                $aliases: [ArtifactAliasInput!],
                $metadata: JSONString,
                _CREATE_ARTIFACT_ADDITIONAL_TYPE_
            ) {
                createArtifact(input: {
                    artifactTypeName: $artifactTypeName,
                    artifactCollectionNames: $artifactCollectionNames,
                    entityName: $entityName,
                    projectName: $projectName,
                    runName: $runName,
                    description: $description,
                    digest: $digest,
                    digestAlgorithm: MANIFEST_MD5,
                    aliases: $aliases,
                    metadata: $metadata,
                    _CREATE_ARTIFACT_ADDITIONAL_VALUE_
                }) {
                    artifact {
                        id
                        state
                        artifactSequence {
                            id
                            latestArtifact {
                                id
                                versionIndex
                            }
                        }
                    }
                }
            }
        !_CREATE_ARTIFACT_ADDITIONAL_TYPE_"_CREATE_ARTIFACT_ADDITIONAL_VALUE_r+  )r   rM  rr  rs  typesvaluesr  rE   rE   rF   _get_create_artifact_mutation  s8   )z!Api._get_create_artifact_mutationartifact_collection_namer_   sequence_client_idttl_duration_secondsis_user_createdc                 C   s   |   }|  }d|vr|rtd d }d|vr |r td | |||}|p-| d}|p4| d}|s<|p;| j}t|}| j||||||g||||	t|pQg t|pVg |
rat	
t|
nd |||dd}|d	 d
 }|d	 d
 d d}||fS )NttlIsInheritedz_Server not compatible with setting Artifact TTLs, please upgrade the server to use Artifact TTLr=  zmServer not compatible with Artifact tags. To use Artifact tags, please upgrade the server to v0.85 or higher.rg   ri   )r  r  rj  ri  artifactCollectionNamesr2  ru  r_   r  r(  r=  r  rw  distributedIDrt  r  createArtifactrQ   artifactSequencelatestArtifact)rq  ro  r{   r  r|  r   r  r   listr   r  r   make_safe_for_jsonr~   )r   rh  r}  r_   r%  r~  r   r  rg  r  r  r  r(  r=  rs  r  rr  rM  artifact_fieldsr  r  r  avlatestrE   rE   rF   create_artifact  sZ   


zApi.create_artifactc                 C   s    t d}| j |d|idd}|S )Na)  
        mutation CommitArtifact(
            $artifactID: ID!,
        ) {
            commitArtifact(input: {
                artifactID: $artifactID,
            }) {
                artifact {
                    id
                    digest
                }
            }
        }
        r8   r  r  r  )r   rG  r  r  rE   rE   rF   commit_artifact  s   zApi.commit_artifactCompletestorage_pathcompleted_parts	upload_idcomplete_multipart_actionc           	      C   s2   t d}| j ||||||dd}|d d }|S )Na  
        mutation CompleteMultipartUploadArtifact(
            $completeMultipartAction: CompleteMultipartAction!,
            $completedParts: [UploadPartsInput!]!,
            $artifactID: ID!
            $storagePath: String!
            $uploadID: String!
        ) {
        completeMultipartUploadArtifact(
            input: {
                completeMultipartAction: $completeMultipartAction,
                completedParts: $completedParts,
                artifactID: $artifactID,
                storagePath: $storagePath
                uploadID: $uploadID
            }
            ) {
                digest
            }
        }
        )r\   r8   rO   r]   rW   r  completeMultipartUploadArtifactr_   r  )	r   rG  r  r  r  r  r  r  r_   rE   rE   rF   "complete_multipart_upload_artifact8  s   
z&Api.complete_multipart_upload_artifactFULLbase_artifact_idinclude_uploadtypec
                 C   s   t d|	dkr	dnd|	dkrdnd}
|p| d}|p!| d}|p&| j}| j |
|||||||||	d	d	}|d
 d d |d
 d d fS )Na,  
        mutation CreateArtifactManifest(
            $name: String!,
            $digest: String!,
            $artifactID: ID!,
            $baseArtifactID: ID,
            $entityName: String!,
            $projectName: String!,
            $runName: String!,
            $includeUpload: Boolean!,
            {}
        ) {{
            createArtifactManifest(input: {{
                name: $name,
                digest: $digest,
                artifactID: $artifactID,
                baseArtifactID: $baseArtifactID,
                entityName: $entityName,
                projectName: $projectName,
                runName: $runName,
                {}
            }}) {{
                artifactManifest {{
                    id
                    file {{
                        id
                        name
                        displayName
                        uploadUrl @include(if: $includeUpload)
                        uploadHeaders @include(if: $includeUpload)
                    }}
                }}
            }}
        }}
        r  z"$type: ArtifactManifestType = FULLr   ztype: $typerg   ri   )	r9   r_   r8   baseArtifactIDr  r  rj  includeUploadr  r  createArtifactManifestartifactManifestrI   r|  )r   r  r   r  )r   r9   r_   rG  r  rg   ri   r=  r  r  r  r   r  rg  r  rE   rE   rF   create_artifact_manifestd  s4   ")
zApi.create_artifact_manifestartifact_manifest_idc                 C   s@   t d}| j |||||dd}|d d d |d d d fS )Na  
        mutation UpdateArtifactManifest(
            $artifactManifestID: ID!,
            $digest: String,
            $baseArtifactID: ID,
            $includeUpload: Boolean!,
        ) {
            updateArtifactManifest(input: {
                artifactManifestID: $artifactManifestID,
                digest: $digest,
                baseArtifactID: $baseArtifactID,
            }) {
                artifactManifest {
                    id
                    file {
                        id
                        name
                        displayName
                        uploadUrl @include(if: $includeUpload)
                        uploadHeaders @include(if: $includeUpload)
                    }
                }
            }
        }
        )r<   r_   r  r  r  updateArtifactManifestr  rI   r|  r  )r   r  r  r_   r  r  r  rE   rE   rF   update_artifact_manifest  s   zApi.update_artifact_manifestc                 C   s.   t d}| j ||t|dd}|d d S )z/Set the metadata of the given artifact version.aV  
        mutation UpdateArtifact(
            $artifactID: ID!,
            $metadata: JSONString,
        ) {
            updateArtifact(input: {
                artifactID: $artifactID,
                metadata: $metadata,
            }) {
                artifact {
                    id
                }
            }
        }
        )r8   r  r  updateArtifactrQ   )r   r   r  )r   rG  r  r  r  rE   rE   rF   update_artifact_metadata  s   zApi.update_artifact_metadatac                 C   sl   || j v r
| j | S td}| j|d|id}d }|d ur4|d}|d ur4|d}|d ur4|| j |< |S )Nz
            query ClientIDMapping($clientID: ID!) {
                clientIDMapping(clientID: $clientID) {
                    serverID
                }
            }
        r2  r  clientIDMappingserverID)r   r   r~   )r   r%  rR  r  r&  client_id_mappingrE   rE   rF   _resolve_client_id   s$   

	


zApi._resolve_client_idc                 C   s:   d}t |}|  |}dd |di di gD }|S )Na  
           query ProbeServerCreateArtifactFileSpecInput {
                CreateArtifactFileSpecInputInfoType: __type(name:"CreateArtifactFileSpecInput") {
                    inputFields{
                        name
                    }
                }
            }
        c                 S   rD  rE  rF  rG  rE   rE   rF   rJ  ,  rK  zLApi.server_create_artifact_file_spec_input_introspection.<locals>.<listcomp>#CreateArtifactFileSpecInputInfoTyperW  rZ  )r   rQ  rR  r  $create_artifact_file_spec_input_inforE   rE   rF   4server_create_artifact_file_spec_input_introspection  s   

z8Api.server_create_artifact_file_spec_input_introspectionartifact_filesr7   rH   c                 C   s   d}d}d}t  rd}|  }d|v r|d|}n|dd}t|}| j||dd	 |D d
d}i }|d d d D ]}	|	d }
|
||
d < q>|S )NaE  
        mutation CreateArtifactFiles(
            $storageLayout: ArtifactStorageLayout!
            $artifactFiles: [CreateArtifactFileSpecInput!]!
        ) {
            createArtifactFiles(input: {
                artifactFiles: $artifactFiles,
                storageLayout: $storageLayout,
            }) {
                files {
                    edges {
                        node {
                            id
                            name
                            displayName
                            uploadUrl
                            uploadHeaders
                            _MULTIPART_UPLOAD_FIELDS_
                            artifact {
                                id
                            }
                        }
                    }
                }
            }
        }
        z
            storagePath
            uploadMultipartUrls {
                uploadID
                uploadUrlParts {
                    partNumber
                    uploadUrl
                }
            }
        V2V1r=   _MULTIPART_UPLOAD_FIELDS_r   c                 S   rz  rE   rE   )rH  afrE   rE   rF   rJ  t  r}  z-Api.create_artifact_files.<locals>.<listcomp>)storageLayoutartifactFilesr  createArtifactFilesr  r  r  rJ   )r   get_use_v1_artifactsr  r  r   )r   r  r  multipart_upload_url_querystorage_layout&create_artifact_file_spec_input_fieldsr  r  r1  edger  rE   rE   rF   create_artifact_files4  s0   zApi.create_artifact_filestitler  ry   wait_durationNumberc              
   C   sD   t d}| j || d| d| j||||dd}|d d }|S )Na  
        mutation NotifyScriptableRunAlert(
            $entityName: String!,
            $projectName: String!,
            $runName: String!,
            $title: String!,
            $text: String!,
            $severity: AlertSeverity = INFO,
            $waitDuration: Duration
        ) {
            notifyScriptableRunAlert(input: {
                entityName: $entityName,
                projectName: $projectName,
                runName: $runName,
                title: $title,
                text: $text,
                severity: $severity,
                waitDuration: $waitDuration
            }) {
               success
            }
        }
        rg   ri   )r  r  rj  r  r  severitywaitDurationr  notifyScriptableRunAlertr  )r   r   r  )r   r  r  ry   r  r  r  r  rE   rE   rF   notify_scriptable_run_alert~  s    zApi.notify_scriptable_run_alert
SweepStatec                 C   s   | j |||ddd }|S )Nr   r  rg   ri   r  r>  )r  )r   r  rg   ri   r>  rE   rE   rF   get_sweep_state  s   zApi.get_sweep_statec           	      C   s   |dv sJ | j |||dd}|d  }|dkr'|dvr'td|  d|d	kr9|d
vr9td|  d|d }td}| j||||pL| d|pR| ddd d S )Nrl   r   r  r>  rn   )rn   rm   zCannot pause z sweep.rm   )rm   rn   PENDINGzSweep already r  rI   a  
        mutation UpsertSweep(
            $id: ID,
            $state: String,
            $entityName: String,
            $projectName: String
        ) {
            upsertSweep(input: {
                id: $id,
                state: $state,
                entityName: $entityName,
                projectName: $projectName
            }){
                sweep {
                    name
                }
            }
        }
        rg   ri   )rI   r>  r  r  r  )r  upperr  r  r   r   )	r   r  r>  rg   ri   s
curr_stater  r  rE   rE   rF   set_sweep_state  s&   
zApi.set_sweep_statec                 C      | j |d||d dS )zPFinish the sweep to stop running new runs and let currently running runs finish.rp   r  r>  rg   ri   Nr  r   r  rg   ri   rE   rE   rF   
stop_sweep     
zApi.stop_sweepc                 C   r  )zDCancel the sweep to kill all running runs and stop running new runs.ro   r  Nr  r  rE   rE   rF   cancel_sweep  r  zApi.cancel_sweepc                 C   r  )z5Pause the sweep to temporarily stop running new runs.rn   r  Nr  r  rE   rE   rF   pause_sweep  r  zApi.pause_sweepc                 C   r  )z.Resume the sweep to continue running new runs.rm   r  Nr  r  rE   rE   rF   resume_sweep  r  zApi.resume_sweepr  c                 C   s    t   tj|dd| ddS )z#Ask google how much we've uploaded.0zbytes */)zContent-LengthzContent-Range)r   r   )r   r   r   )r   r   r  rE   rE   rF   _status_request  s
   zApi._status_requestr  c                 C   s   dd |d D S )z8Return an array from the nested graphql relay structure.c                 S   r^  )r  rE   )rH  r  rE   rE   rF   rJ    r+  z&Api._flatten_edges.<locals>.<listcomp>r  rE   )r   r  rE   rE   rF   r    s   zApi._flatten_edgesc                 C   s,   t d}| j |d|id}|d d}|S )Nz
            mutation stopRun($id: ID!) {
                stopRun(input: {
                    id: $id
                }) {
                    clientMutationId
                    success
                }
            }
            rI   r  stopRunr  rZ  )r   r  r  r  r  rE   rE   rF   stop_run  s   zApi.stop_run	spec_typespecc           
      C   sB   t |ts
t|}td}||||||d}| ||d }	|	S )Na  
            mutation CreateCustomChart(
                $entity: String!
                $name: String!
                $displayName: String!
                $type: String!
                $access: String!
                $spec: JSONString!
            ) {
                createCustomChart(
                    input: {
                        entity: $entity
                        name: $name
                        displayName: $displayName
                        type: $type
                        access: $access
                        spec: $spec
                    }
                ) {
                    chart { id }
                }
            }
            )rg   r9   rJ   r  r  r  createCustomChart)r  rB   r   r  r   )
r   rg   r9   r   r  r  r  r  r  r1  rE   rE   rF   create_custom_chart:  s    



	zApi.create_custom_chartr   )NN)FFr   )NNN)NNNNNNNNNNNNNNNNNNN)NNNN)	NNNNNNNNN)NNNNTF)r   )NNNNNN)NNNNNNNNNNNFN)r  )NNNNTr  )NNT)r>   r?   r@   rA   r   get_http_timeoutr   get_file_pusher_timeoutr   r2   r   rC   r   r_  r`  r|   r}   r   r   r!   r  boolr   r   rY   rB   r   r   r   r   r   propertyr   r  r   r  r  r  r   rf   r   r  r&  r'  r   r6  r;  r   rC  r   r
   rS  rU  rX  r\  rh  rm  rr  rt  rv  ry  r  r  r   r  r  r  r  r  r  r  ri   r  r  r  r  r  r  r  r  r  r  r  r  LAUNCH_DEFAULT_PROJECTr  r  r  r  r!  r#  r3  r7  r:  rf  ro  ru  rw  ry  r   r  r  r  r  r   r  r  r  r  bytesr   r   r  r  staticmethodr  r  r  r(   r  r  r.  r   r   r$  r   r7  r5  r   r:  r   rV  rX  r9  rg  rm  ro  rq  r|  r  r  r  r  r  r  r  r  r	   r   r  r  r  r  r  r  r  r  r  r  r  r  rE   rE   rE   rF   r      s  
 



 "D



&*&$
0
%(6( 
L("X>"
($'@g	
?{
s" 
V!
	
 I	j- N 
@9:


'
5
D6
7&	

 ' 	b
	 D(N	S	%*V	

G1	
O2

I11r   r   )sr  r_  r   http.clientr   r   r   r|   r  r/  r  	threadingr)  r   pathlibr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r  r   r  	wandb_gqlr   r   wandb_gql.clientr   wandb_graphql.language.astr   r{   r   r   wandb.apis.normalizer   r   wandb.errorsr   r   r   r   wandb.integration.sagemakerr    wandb.old.settingsr!   wandb.proto.wandb_internal_pb2r"   wandb.sdk.artifacts._validatorsr#   wandb.sdk.internal._generatedr$   r%   (wandb.sdk.internal.thread_local_settingsr&   wandb.sdk.lib.gql_requestr'   wandb.sdk.lib.hashutilr(   r)   libr+   r,   lib.filenamesr-   r.   
lib.gitlibr/   r   r2   r  r3   r   r>   r	  r  r5   r6   r7   rH   rP   rM   rU   r[   r^   r`   r  r  rY   r  r  ru   r}   r~   setLevelr   r   localr   r   rB   r   r   rE   rE   rE   rF   <module>   s    H






"