o
    ni$                     @   s2  d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 ddl
Z
ddlmZmZ ddlm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mZ dd
lmZmZ ddlmZ ddlmZ  ddl!m"Z" ddl#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, e-e.Z/G dd dZ0G dd dZdS )uZ  Use the Public API to export or update data that you have saved to W&B.

Before using this API, you'll want to log data from your script — check the
[Quickstart](https://docs.wandb.ai/quickstart) for more details.

You might use the Public API to
 - update metadata or metrics for an experiment after it has been completed,
 - pull down your results as a dataframe for post-hoc analysis in a Jupyter notebook, or
 - check your saved model artifacts for those tagged as `ready-to-deploy`.

For more on using the Public API, check out [our guide](https://docs.wandb.com/guides/track/public-api-guide).
    N)AnyDictListOptional)Clientgql)
RetryError)envutil)public)normalize_exceptions)RETRY_TIMEDELTA)PathTypeparse_org_from_registry_path)is_artifact_registry_project)Api)_thread_local_api_settings)LAUNCH_DEFAULT_PROJECT)retryrunid)
Deprecated	deprecate)GraphQLSessionc                   @   sl   e Zd ZedZdefddZedd Ze	j
eejeejfddd	 Zed
d ZdedefddZdS )RetryingClienta$  
        query ServerInfo{
            serverInfo {
                cliVersionInfo
                latestLocalVersionInfo {
                    outOfDate
                    latestVersionString
                    versionOnThisInstanceString
                }
            }
        }
        clientc                 C   s   d | _ || _d S N)_server_info_client)selfr    r   S/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/wandb/apis/public/api.py__init__9   s   
zRetryingClient.__init__c                 C   s   t | jjjddd S )Nz/graphql /)r
   app_urlr   	transporturlreplacer   r   r   r    r$   =   s   zRetryingClient.app_url)retry_timedeltacheck_retry_fnretryable_exceptionsc                 O   s^   z
| j j|i |W S  tjjy.   d|vr-| j jj}td| d| d|d  d  w )NtimeoutzGA graphql request initiated by the public wandb API timed out (timeout=z< sec). Create a new API with an integer timeout larger than z!, e.g., `api = wandb.Api(timeout=
   z#)` to increase the graphql timeout.)	r   executerequests
exceptionsReadTimeoutr%   default_timeoutwandbtermwarn)r   argskwargsr,   r   r   r    r.   A   s   
zRetryingClient.executec                 C   s$   | j d u r| | jd| _ | j S )N
serverInfo)r   r.   
INFO_QUERYgetr(   r   r   r    server_infoS   s   
zRetryingClient.server_infomin_versionreturnc                 C   s&   ddl m} |||| jd d kS )Nr   )parse_versioncliVersionInfomax_cli_version)
wandb.utilr=   r:   )r   r;   r=   r   r   r    version_supportedY   s   z RetryingClient.version_supportedN)__name__
__module____qualname__r   r8   r   r!   propertyr$   r   	retriabler   r
   no_retry_authr   r/   RequestExceptionr.   r:   strboolrA   r   r   r   r    r   )   s     


r   c                   @   sj  e Zd ZdZedZedZedZ	edZ
edZ			ddeeeef  d	ee d
ee ddfddZdededdfddZdddddee dee dee ddfddZ				ddedddee ded dee dee ddfdd Z				dded!ed"ddee dee d#ee ded fd$d%Zdd'd(Zdd)d*Zed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dd4d5Zd6d7 Z d8d9 Z!d:d; Z"d<d= Z#d>d? Z$	@ddee dAee ddBfdCdDZ%ddedee ddEfdFdGZ&	IddJedee dAee ddKfdLdMZ'ddNdOZ(dPeddQfdRdSZ)dTeded3 fdUdVZ*dTede+d3 fdWdXZ,			Y	I	ZddJee d[eeeef  d\edAed]e-f
d^d_Z.e/dd`daZ0		ddbdcZ1ddde Z2e/ddfdgZ3e/ddee ddhfdidjZ4e/	ddkedee ddlfdmdnZ5e/	IddoedkedAee ddpfdqdrZ6e/dkededdsfdtduZ7e/ddvdwZ8e/	I	ddkededAee dxee+e  ddyf
dzd{Z9e/	&ddedee d|e-fd}d~Z:e/ddedee fddZ;e/ddee dJee ddfddZ<e/dedede+eeef  fddZ=e/ddedee de-fddZ>e/dedede-fddZ?dS )r   aH  Used for querying the wandb server.

    Examples:
        Most common way to initialize
        >>> wandb.Api()

    Args:
        overrides: (dict) You can set `base_url` if you are using a wandb server
            other than https://api.wandb.ai.
            You can also set defaults for `entity`, `project`, and `run`.
       zv
        query Viewer{
            viewer {
                id
                entity
            }
        }
        a  
        query Viewer{
            viewer {
                id
                flags
                entity
                username
                email
                admin
                apiKeys {
                    edges {
                        node {
                            id
                            name
                            description
                        }
                    }
                }
                teams {
                    edges {
                        node {
                            name
                        }
                    }
                }
            }
        }
        a  
        query SearchUsers($query: String) {
            users(query: $query) {
                edges {
                    node {
                        id
                        flags
                        entity
                        admin
                        email
                        deletedAt
                        username
                        apiKeys {
                            edges {
                                node {
                                    id
                                    name
                                    description
                                }
                            }
                        }
                        teams {
                            edges {
                                node {
                                    name
                                }
                            }
                        }
                    }
                }
            }
        }
        a  
        mutation upsertModel(
            $description: String
            $entityName: String
            $id: String
            $name: String
            $framework: String
            $access: String
            $views: JSONString
        ) {
            upsertModel(
            input: {
                description: $description
                entityName: $entityName
                id: $id
                name: $name
                framework: $framework
                access: $access
                views: $views
            }
            ) {
            project {
                id
                name
                entityName
                description
                access
                views
            }
            model {
                id
                name
                entityName
                description
                access
                views
            }
            inserted
            }
        }
    N	overridesr,   api_keyr<   c              
   C   sF  t   | _|p	i }|| _| jd u r tjd u r tj|dd | j	| d|v r:d|vr:t
d |d | jd< | jd d| jd< d | _i | _i | _i | _i | _d | _|d ur]|n| j| _d }tjskd| jf}| jdpzttjd	d
}tt| jddtjpi d| j|d| jd tj|dd| _t| j| _d S )Nbase_url)hostusernameentityzEPassing "username" to Api is deprecated. please use "entity" instead.r#   api_proxiesWANDB__PROXIES{}true)z
User-AgentzUse-Admin-PrivilegesTz
{}/graphql)headersuse_jsonr,   authr&   cookiesproxies)r%   ) InternalApisettings_api_keyrM   r   rZ   r3   loginr9   updater4   rstrip_viewer	_projects_runs_sweeps_reports_default_entity_HTTP_TIMEOUT_timeoutjsonloadsosenvironr   r   
user_agentrW   format_base_clientr   r   )r   rL   r,   rM   
_overridesrY   r[   r   r   r    r!      sR   
zApi.__init__namerQ   c                 C   s   | j | j||d dS )zCreate a new project.

        Args:
            name: (str) The name of the new project.
            entity: (str) The entity of the new project.
        )
entityNamerr   N)r   r.   CREATE_PROJECT)r   rr   rQ   r   r   r    create_project  s   zApi.create_projectrun_idprojectrQ   rw   rx   z
public.Runc                C   s"   |du r| j }tjj| |||dS )a  Create a new run.

        Args:
            run_id: (str, optional) The ID to assign to the run, if given.  The run ID is automatically generated by
                default, so in general, you do not need to specify this and should only do so at your own risk.
            project: (str, optional) If given, the project of the new run.
            entity: (str, optional) If given, the entity of the new run.

        Returns:
            The newly created `Run`.
        Nrv   )default_entityr   Runcreate)r   rw   rx   rQ   r   r   r    
create_run$  s   zApi.create_runtypezpublic.RunQueueResourceTypeprioritization_modez!public.RunQueuePrioritizationModeconfigtemplate_variableszpublic.RunQueuec              	   C   s(  |du r| j d p| j}|du rtdt|dkrtdt|dkr(td|dvr0td	|r>| }|d
vr>td|du rDi }| t| t|| tdt	d}t
d||ii}|||||}	|	d sptd|	d }
||t|d||
}|d stdtj| j|||d|
|dS )a  Create a new run queue (launch).

        Args:
            name: (str) Name of the queue to create
            type: (str) Type of resource to be used for the queue. One of "local-container", "local-process", "kubernetes", "sagemaker", or "gcp-vertex".
            entity: (str) Optional name of the entity to create the queue. If None, will use the configured or default entity.
            prioritization_mode: (str) Optional version of prioritization to use. Either "V0" or None
            config: (dict) Optional default resource configuration to be used for the queue. Use handlebars (eg. `{{var}}`) to specify template variables.
            template_variables: (dict) A dictionary of template variable schemas to be used with the config. Expected format of:
                `{
                    "var-name": {
                        "schema": {
                            "type": ("string", "number", or "integer"),
                            "default": (optional value),
                            "minimum": (optional minimum),
                            "maximum": (optional maximum),
                            "enum": [..."(options)"]
                        }
                    }
                }`

        Returns:
            The newly created `RunQueue`

        Raises:
            ValueError if any of the parameters are invalid
            wandb.Error on wandb API errors
        NrQ   8entity must be passed as a parameter, or set in settingsr   name must be non-empty@   $name must be less than 64 characterszlocal-containerzlocal-process
kubernetes	sagemakerz
gcp-vertexkresource_type must be one of 'local-container', 'local-process', 'kubernetes', 'sagemaker', or 'gcp-vertex')V0z+prioritization_mode must be 'V0' if presentrQ   rx   default_settingsr)   resource_argssuccessz(failed to create default resource configdefaultResourceConfigIDPROJECTfailed to create run queue)r   rr   rQ   r~   _access_default_resource_config_id_default_resource_config)r]   ry   
ValueErrorlenupperru   r   r\   rx   r   rj   dumpscreate_default_resource_configr3   Errorcreate_run_queuer   RunQueuer   )r   rr   r}   rQ   r~   r   r   rR   config_jsoncreate_config_result	config_idcreate_queue_resultr   r   r    r   :  sj   '	

zApi.create_run_queueresource_configresource_typeexternal_linksc              	   C   s.  |du r| j d p| j}|du rtdt|dkrtdt|dkr(td|p+d}| }|d	vr8td
|dvr@td| t| t|| tdt	d}|pUi }ddd |
 D i}|j|||d||ii|||d}	|	d sztd|	dpg }
|
D ]
}td|  qtj| j||dS )aM  Upsert a run queue (launch).

        Args:
            name: (str) Name of the queue to create
            entity: (str) Optional name of the entity to create the queue. If None, will use the configured or default entity.
            resource_config: (dict) Optional default resource configuration to be used for the queue. Use handlebars (eg. `{{var}}`) to specify template variables.
            resource_type: (str) Type of resource to be used for the queue. One of "local-container", "local-process", "kubernetes", "sagemaker", or "gcp-vertex".
            template_variables: (dict) A dictionary of template variable schemas to be used with the config. Expected format of:
                `{
                    "var-name": {
                        "schema": {
                            "type": ("string", "number", or "integer"),
                            "default": (optional value),
                            "minimum": (optional minimum),
                            "maximum": (optional maximum),
                            "enum": [..."(options)"]
                        }
                    }
                }`
            external_links: (dict) Optional dictionary of external links to be used with the queue. Expected format of:
                `{
                    "name": "url"
                }`
            prioritization_mode: (str) Optional version of prioritization to use. Either "V0" or None

        Returns:
            The upserted `RunQueue`.

        Raises:
            ValueError if any of the parameters are invalid
            wandb.Error on wandb API errors
        NrQ   r   r   r   r   r   DISABLED)r   r   z9prioritization_mode must be 'V0' or 'DISABLED' if presentr   r   r   r   linksc                 S   s   g | ]	\}}||d qS ))labelr&   r   ).0keyvaluer   r   r    
<listcomp>  s    z(Api.upsert_run_queue.<locals>.<listcomp>r   )r   r   r~   r   r   configSchemaValidationErrorszresource config validation: )r   rr   rQ   )r]   ry   r   r   r   ru   r   r\   rx   r   itemsupsert_run_queuer3   r   r9   r4   r   r   r   )r   rr   r   r   rQ   r   r   r~   rR   upsert_run_queue_resultschema_errorserrorr   r   r    r     sh   *		
	
zApi.upsert_run_queueFc                 C      t j| ||S )zCreate a new user.

        Args:
            email: (str) The email address of the user
            admin: (bool) Whether this user should be a global instance admin

        Returns:
            A `User` object
        )r   Userr{   )r   emailadminr   r   r    create_user     
zApi.create_userc              
   C   s   ddl m} |pt }|p| jdpd}|p| j}||||d| jjdddd}|	| |
  | s>| }| r6| d|||gS )	z9Sync a local directory containing tfevent files to wandb.r   )SyncManagerrx   uncategorizedFT)rx   rQ   rw   mark_syncedr$   viewverbosesync_tensorboardr#   )
wandb.syncr   r   generate_idr]   r9   ry   r   r$   addstartis_donepollrunjoin)r   root_dirrw   rx   rQ   r   sm_r   r   r    r   )  s(   


zApi.sync_tensorboardc                 C   s   | j S r   )r   r(   r   r   r    r   A  s   z
Api.clientc                 C   s   d tjS )NzW&B Public Client {})ro   r3   __version__r(   r   r   r    rn   E  s   zApi.user_agentc                 C   s\   t jrt jS | jd ur| jS tj| jd }d }|r|d }tdr)tj	d }|| _|S )NrN   WANDB_API_KEY)
r   rM   r^   r/   utilsget_netrc_authr]   rl   getenvrm   )r   rY   r   r   r   r    rM   I  s   


zApi.api_keyc                 C   s4   | j d u r| j| j}|dpi d| _ | j S )NviewerrQ   )rg   r   r.   DEFAULT_ENTITY_QUERYr9   )r   resr   r   r    ry   Z  s   
zApi.default_entitypublic.Userc                 C   s:   | j d u rt| j| j| jd| _ | j j| _| j S )Nr   )	rb   r   r   r   r.   VIEWER_QUERYr9   rQ   rg   r(   r   r   r    r   a  s   

z
Api.viewerc                 C   s
   i | _ dS )a
  Flush the local cache.

        The api object keeps a local cache of runs, so if the state of the run may
        change while executing your script you must clear the local cache with
        `api.flush()` to get the latest values associated with the run.
        N)rd   r(   r   r   r    flushj  s   
z	Api.flushc              	   C   s&  | dd}t|dkr| |S t|dkr#| |d |d S t|dkr.| |S t|dkr|d dr@| |S |d d	rL| |S |d d
rd|d vrld|d v rdtdd|d  |d< |d d\}}t	
| jtj|dd|dd|d |d S td)a  Return a run, sweep, project or report from a path.

        Examples:
            ```
            project = api.from_path("my_project")
            team_project = api.from_path("my_team/my_project")
            run = api.from_path("my_team/my_project/runs/id")
            sweep = api.from_path("my_team/my_project/sweeps/id")
            report = api.from_path("my_team/my_project/reports/My-Report-Vm11dsdf")
            ```

        Args:
            path: (str) The path to the project, run, sweep or report

        Returns:
            A `Project`, `Run`, `Sweep`, or `BetaReport` instance.

        Raises:
            wandb.Error if path is invalid or the object doesn't exist
        / r#         r         r   sweepreportz--r   -z>Invalid report path, should be team/project/reports/Name--XXXX rU   )display_nameidspeczSInvalid path, should be TEAM/PROJECT/TYPE/ID where TYPE is runs, sweeps, or reports)stripsplitr   rx   r   
startswithr   r3   r   r   
BetaReportr   urllibparseunquoter'   )r   pathpartsrr   r   r   r   r    	from_paths  s@   




zApi.from_pathc                 C   sR   | j d pd}| j d p| j}|du r||fS |dd}t|dkr'||fS |S )z8Return project and entity for project specified by path.rx   r   rQ   Nr#   r   )r]   ry   r   r   )r   r   rx   rQ   r   r   r   r    _parse_project_path  s   zApi._parse_project_pathc                 C   s   | j d pd}| j d p| j}|dddddd}d|d	 v r:|d	 dd	 }|d	 dd
 |d	< n|d	 rB|d	 }t|dkrM|dkrMn(t|dkrq|d }|rb||krb|d
 }n|d
 }t|dkrp|d
 }n|d
 }|||fS )a  Parse url, filepath, or docker paths.

        Allows paths in the following formats:
        - url: entity/project/runs/id
        - path: entity/project/id
        - docker: entity/project:id

        Entity is optional and will fall back to the current logged-in user.
        rx   r   rQ   z/runs/r#   z/sweeps/r   :r   r   r   r   )r]   ry   r'   r   r   r   )r   r   rx   rQ   r   r   r   r   r    _parse_path  s*   


zApi._parse_pathc                 C   s   | j d pd}| j d p| j}|du r||fS |d\}}}|| }|d}t|dkr5td|t|d	krB|||| fS t|d
krS||d |d	 | fS |d  |7  < |S )zGReturn project, entity and artifact name for project specified by path.rx   r   rQ   Nr   r#   r   zInvalid artifact path: {}r   r   r   r   )r]   ry   	partitionr   r   r   ro   )r   r   rx   rQ   colonalias
full_aliasr   r   r   r    _parse_artifact_path  s   
zApi._parse_artifact_path   per_pagezpublic.Projectsc                 C   sT   |du r| j d p| j}|du rtd|| jvr%tj| j||d| j|< | j| S )a  Get projects for a given entity.

        Args:
            entity: (str) Name of the entity requested.  If None, will fall back to the
                default entity passed to `Api`.  If no default entity, will raise a `ValueError`.
            per_page: (int) Sets the page size for query pagination.  None will use the default size.
                Usually there is no reason to change this.

        Returns:
            A `Projects` object which is an iterable collection of `Project` objects.
        NrQ   r   r   )r]   ry   r   rc   r   Projectsr   )r   rQ   r   r   r   r    projects  s   

zApi.projectszpublic.Projectc                 C   sb   t |r|nd}|du r| jd p| j}t |r(| jd p| j}t j||d}t| j||i S )an  Return the `Project` with the given name (and entity, if given).

        Args:
            name: (str) The project name.
            entity: (str) Name of the entity requested.  If None, will fall back to the
                default entity passed to `Api`.  If no default entity, will raise a `ValueError`.

        Returns:
            A `Project` object.
        r"   NrQ   rQ   organization)r   r]   ry   r\   _resolve_org_entity_namer   Projectr   )r   rr   rQ   orgsettings_entityr   r   r    rx     s   zApi.projectr"   2   r   zpublic.Reportsc                 C   s   |  |d \}}}|rtj|}d||t|g}nd||g}|| jvr=tj| j	t
| j	||i ||d| j|< | j| S )aI  Get reports for a given project path.

        WARNING: This api is in beta and will likely change in a future release

        Args:
            path: (str) path to project the report resides in, should be in the form: "entity/project"
            name: (str, optional) optional name of the report requested.
            per_page: (int) Sets the page size for query pagination.  None will use the default size.
                Usually there is no reason to change this.

        Returns:
            A `Reports` object which is an iterable collection of `BetaReport` objects.
        z	/fake_runr#   )rr   r   )r   r   r   r   r   rI   rf   r   Reportsr   r   )r   r   rr   r   rQ   rx   r   r   r   r   r    reports  s   

zApi.reportsc                 C   r   )zCreate a new team.

        Args:
            team: (str) The name of the team
            admin_username: (str) optional username of the admin user of the team, defaults to the current user.

        Returns:
            A `Team` object
        )r   Teamr{   )r   teamadmin_usernamer   r   r    create_team@  r   zApi.create_teamr  zpublic.Teamc                 C   s   t | j|S )zReturn the matching `Team` with the given name.

        Args:
            team: (str) The name of the team.

        Returns:
            A `Team` object.
        )r   r   r   )r   r  r   r   r    r  L  s   	zApi.teamusername_or_emailc                 C   sn   | j | jd|i}t|d d dkrdS t|d d dkr(td| t| j |d d d d S )	aj  Return a user from a username or email address.

        Note: This function only works for Local Admins, if you are trying to get your own user object, please use `api.viewer`.

        Args:
            username_or_email: (str) The username or email address of the user

        Returns:
            A `User` object or None if a user couldn't be found
        queryusersedgesr   Nr   z:Found multiple users, returning the first user matching {}node)	r   r.   USERS_QUERYr   r3   r4   ro   r   r   r   r  r   r   r   r    userW  s   zApi.userc                    s.    j  jd|i} fdd|d d D S )aj  Return all users from a partial username or email address query.

        Note: This function only works for Local Admins, if you are trying to get your own user object, please use `api.viewer`.

        Args:
            username_or_email: (str) The prefix or suffix of the user you want to find

        Returns:
            An array of `User` objects
        r  c                    s   g | ]}t  j|d  qS )r  )r   r   r   )r   edger(   r   r    r   y  s    zApi.users.<locals>.<listcomp>r  r  )r   r.   r	  r
  r   r(   r    r  m  s   

z	Api.users+created_atTfiltersorderinclude_sweepsc           	   	   C   sd   |  |\}}|p
i }|pdt| t| }| j|s-tj| j||||||d| j|< | j| S )a
  Return a set of runs from a project that match the filters provided.

        You can filter by `config.*`, `summary_metrics.*`, `tags`, `state`, `entity`, `createdAt`, etc.

        Examples:
            Find runs in my_project where config.experiment_name has been set to "foo"
            ```
            api.runs(path="my_entity/my_project", filters={"config.experiment_name": "foo"})
            ```

            Find runs in my_project where config.experiment_name has been set to "foo" or "bar"
            ```
            api.runs(
                path="my_entity/my_project",
                filters={
                    "$or": [
                        {"config.experiment_name": "foo"},
                        {"config.experiment_name": "bar"},
                    ]
                },
            )
            ```

            Find runs in my_project where config.experiment_name matches a regex (anchors are not supported)
            ```
            api.runs(
                path="my_entity/my_project",
                filters={"config.experiment_name": {"$regex": "b.*"}},
            )
            ```

            Find runs in my_project where the run name matches a regex (anchors are not supported)
            ```
            api.runs(
                path="my_entity/my_project", filters={"display_name": {"$regex": "^foo.*"}}
            )
            ```

            Find runs in my_project sorted by ascending loss
            ```
            api.runs(path="my_entity/my_project", order="+summary_metrics.loss")
            ```

        Args:
            path: (str) path to project, should be in the form: "entity/project"
            filters: (dict) queries for specific runs using the MongoDB query language.
                You can filter by run properties such as config.key, summary_metrics.key, state, entity, createdAt, etc.
                For example: `{"config.experiment_name": "foo"}` would find runs with a config entry
                    of experiment name set to "foo"
                You can compose operations to make more complicated queries,
                    see Reference for the language is at  https://docs.mongodb.com/manual/reference/operator/query
            order: (str) Order can be `created_at`, `heartbeat_at`, `config.*.value`, or `summary_metrics.*`.
                If you prepend order with a + order is ascending.
                If you prepend order with a - order is descending (default).
                The default order is run.created_at from oldest to newest.
            per_page: (int) Sets the page size for query pagination.
            include_sweeps: (bool) Whether to include the sweep runs in the results.

        Returns:
            A `Runs` object, which is an iterable collection of `Run` objects.
        r"   )r  r  r   r  )r   rI   rd   r9   r   Runsr   )	r   r   r  r  r   r  rQ   rx   r   r   r   r    runs}  s   E
	zApi.runsc                 C   >   |  |\}}}| j|st| j|||| j|< | j| S )ao  Return a single run by parsing path in the form entity/project/run_id.

        Args:
            path: (str) path to run in the form `entity/project/run_id`.
                If `api.entity` is set, this can be in the form `project/run_id`
                and if `api.project` is set this can just be the run_id.

        Returns:
            A `Run` object.
        )r   rd   r9   r   rz   r   )r   r   rQ   rx   rw   r   r   r    r        
zApi.runc              	   C   s   t j| j||||||dS )zReturn a single queued run based on the path.

        Parses paths of the form entity/project/queue_id/run_queue_item_id.
        )project_queuepriority)r   	QueuedRunr   )r   rQ   rx   
queue_namerun_queue_item_idr  r  r   r   r    
queued_run  s   zApi.queued_runc                 C   s   t | j||S )z~Return the named `RunQueue` for entity.

        To create a new `RunQueue`, use `wandb.Api().create_run_queue(...)`.
        )r   r   r   )r   rQ   rr   r   r   r    	run_queue  s
   	zApi.run_queuec                 C   r  )a  Return a sweep by parsing path in the form `entity/project/sweep_id`.

        Args:
            path: (str, optional) path to sweep in the form entity/project/sweep_id.  If `api.entity`
                is set, this can be in the form project/sweep_id and if `api.project` is set
                this can just be the sweep_id.

        Returns:
            A `Sweep` object.
        )r   re   r9   r   Sweepr   )r   r   rQ   rx   sweep_idr   r   r    r     r  z	Api.sweepzpublic.ArtifactTypesc                 C   sV   |}|  |\}}t|r#| jd p| j}t|tj}t j||d}t	
| j||S )zReturn a collection of matching artifact types.

        Args:
            project: (str, optional) If given, a project name or path to filter on.

        Returns:
            An iterable `ArtifactTypes` object.
        rQ   r   )r   r   r]   ry   r   r   r   r\   r   r   ArtifactTypesr   )r   rx   project_pathrQ   r   r   r   r   r    artifact_types  s   
zApi.artifact_types	type_namezpublic.ArtifactTypec                 C   sX   |}|  |\}}t|r#t|tj}| jd p| j}t j||d}t	
| j|||S )a  Return the matching `ArtifactType`.

        Args:
            type_name: (str) The name of the artifact type to retrieve.
            project: (str, optional) If given, a project name or path to filter on.

        Returns:
            An `ArtifactType` object.
        rQ   r   )r   r   r   r   r   r]   ry   r\   r   r   ArtifactTyper   )r   r!  rx   r  rQ   r   r   r   r   r    artifact_type.  s   zApi.artifact_typeproject_namezpublic.ArtifactCollectionsc                 C   sX   |  |\}}t|r!t|tj}| jd p| j}t j||d}t	j
| j||||dS )a  Return a collection of matching artifact collections.

        Args:
            project_name: (str) The name of the project to filter on.
            type_name: (str) The name of the artifact type to filter on.
            per_page: (int, optional) Sets the page size for query pagination.  None will use the default size.
                Usually there is no reason to change this.

        Returns:
            An iterable `ArtifactCollections` object.
        rQ   r   r   )r   r   r   r   r   r]   ry   r\   r   r   ArtifactCollectionsr   )r   r$  r!  r   rQ   rx   r   r   r   r   r    artifact_collectionsF  s   zApi.artifact_collectionszpublic.ArtifactCollectionc                 C   sX   |  |\}}}t|r"t|tj}| jd p| j}t j||d}t	
| j||||S )aV  Return a single artifact collection by type and parsing path in the form `entity/project/name`.

        Args:
            type_name: (str) The type of artifact collection to fetch.
            name: (str) An artifact collection name. May be prefixed with entity/project.

        Returns:
            An `ArtifactCollection` object.
        rQ   r   )r   r   r   r   ARTIFACTr]   ry   r\   r   r   ArtifactCollectionr   )r   r!  rr   rQ   rx   collection_namer   r   r   r   r    artifact_collectiona  s   zApi.artifact_collectionc                 C   s   t tjdd | j|||dS )z5Deprecated, use `artifacts(type_name, name)` instead.zaApi.artifact_versions(type_name, name) is deprecated, use Api.artifacts(type_name, name) instead.)
field_namewarning_messager   )r   r   api__artifact_versions	artifacts)r   r!  rr   r   r   r   r    artifact_versionsz  s
   zApi.artifact_versionstagszpublic.Artifactsc           
   	   C   s^   |  |\}}}t|r"t|tj}| jd p| j}	t j|	|d}t	j
| j||||||dS )a)  Return an `Artifacts` collection from the given parameters.

        Args:
            type_name: (str) The type of artifacts to fetch.
            name: (str) An artifact collection name. May be prefixed with entity/project.
            per_page: (int, optional) Sets the page size for query pagination.  None will use the default size.
                Usually there is no reason to change this.
            tags: (list[str], optional) Only return artifacts with all of these tags.

        Returns:
            An iterable `Artifacts` object.
        rQ   r   )r   r0  )r   r   r   r   r'  r]   ry   r\   r   r   	Artifactsr   )
r   r!  rr   r   r0  rQ   rx   r)  r   r   r   r   r    r.    s    zApi.artifactsenable_trackingc           
      C   s   |d u rt d| |\}}}t|r4|ddkr"|dd nd}| jd p+| j}t j||d}t	j
j|||| j|d}	|d urT|	j|krTt d	| d
|	j |	S )Nz,You must specify name= to fetch an artifact.r#   r   r   r"   rQ   r   )rQ   rx   rr   r   r2  ztype z( specified but this artifact is of type )r   r   r   countr   r]   ry   r\   r   r3   Artifact
_from_namer   r}   )
r   rr   r}   r2  rQ   rx   artifact_namer   r   artifactr   r   r    	_artifact  s*    zApi._artifactc                 C   s   | j ||ddS )ai  Return a single artifact by parsing path in the form `project/name` or `entity/project/name`.

        Args:
            name: (str) An artifact name. May be prefixed with project/ or entity/project/.
                    If no entity is specified in the name, the Run or API setting's entity is used.
                Valid names can be in the following forms:
                    name:version
                    name:alias
            type: (str, optional) The type of artifact to fetch.

        Returns:
            An `Artifact` object.

        Raises:
            ValueError: If the artifact name is not specified.
            ValueError: If the artifact type is specified but does not match the type of the fetched artifact.

        Note:
        This method is intended for external use only. Do not call `api.artifact()` within the wandb repository code.
        T)rr   r}   r2  )r8  r   rr   r}   r   r   r    r7    s   zApi.artifactz
public.Jobc                 C   s<   |du rt d|ddksd|vrt dt| ||S )zReturn a `Job` from the given parameters.

        Args:
            name: (str) The job name.
            path: (str, optional) If given, the root path in which to download the job artifact.

        Returns:
            A `Job` object.
        Nz&You must specify name= to fetch a job.r#   r   r   zfInvalid job specification. A job must be of the form: <entity>/<project>/<job-name>:<alias-or-version>)r   r3  r   Job)r   rr   r   r   r   r    job  s   zApi.jobc                 C   s   |du rt d|du rt dtd}z=| j|||dd}|r&|d s5td| d	| d
 g W S |d d du r@g W S |d d d d }dd |D W S  tjjy]   Y dS w )a	  Return a list of jobs, if any, for the given entity and project.

        Args:
            entity: (str) The entity for the listed job(s).
            project: (str) The project for the listed job(s).

        Returns:
            A list of matching jobs.
        Nz#Specify an entity when listing jobsz#Specify a project when listing jobsa  
        query ArtifactOfType(
            $entityName: String!,
            $projectName: String!,
            $artifactTypeName: String!,
        ) {
            project(name: $projectName, entityName: $entityName) {
                artifactType(name: $artifactTypeName) {
                    artifactCollections {
                        edges {
                            node {
                                artifacts {
                                    edges {
                                        node {
                                            id
                                            state
                                            aliases {
                                                alias
                                            }
                                            artifactSequence {
                                                name
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        r;  )projectNamers   artifactTypeNamerx   z
Project: 'z' not found in entity: 'z' or access denied.artifactTypeartifactCollectionsr  c                 S   s   g | ]}|d  d qS )r  r.  r   )r   xr   r   r    r   @  s    z!Api.list_jobs.<locals>.<listcomp>F)	r   r   r   r.   r3   	termerrorr/   r0   	HTTPError)r   rQ   rx   r  artifact_queryr.  r   r   r    	list_jobs  s>   #	
zApi.list_jobsc                 C   s,   z	|  || W dS  tjjy   Y dS w )a  Return whether an artifact version exists within a specified project and entity.

        Args:
            name: (str) An artifact name. May be prefixed with entity/project.
                If entity or project is not specified, it will be inferred from the override params if populated.
                Otherwise, entity will be pulled from the user settings and project will default to "uncategorized".
                Valid names can be in the following forms:
                    name:version
                    name:alias
            type: (str, optional) The type of artifact

        Returns:
            True if the artifact version exists, False otherwise.
        TF)r8  r3   errors	CommErrorr9  r   r   r    artifact_existsD  s   zApi.artifact_existsc                 C   s,   z	|  || W dS  tjjy   Y dS w )a;  Return whether an artifact collection exists within a specified project and entity.

        Args:
            name: (str) An artifact collection name. May be prefixed with entity/project.
                If entity or project is not specified, it will be inferred from the override params if populated.
                Otherwise, entity will be pulled from the user settings and project will default to "uncategorized".
            type: (str) The type of artifact collection

        Returns:
            True if the artifact collection exists, False otherwise.
        TF)r*  r3   rE  rF  r9  r   r   r    artifact_collection_existsZ  s   zApi.artifact_collection_exists)NNN)NNNN)F)r<   r   )Nr   r   )r"   Nr   )NNr  r   T)r"   )NN)r   )r   N)NF)@rB   rC   rD   __doc__r	   get_http_timeoutrh   r   r   r   r	  rt   r   r   rI   r   intr!   ru   r|   dictr   r   r   r   rE   r   r   rn   rM   ry   r   r   r   r   r   r   r   rx   r   r  r  r  r   r  rJ   r  r   r   r  r  r   r   r#  r&  r*  r/  r.  r8  r7  r;  rD  rG  rH  r   r   r   r    r   a   s   
$.
3

u

s
	8"


!
T

%"$Mr   )1rI  rj   loggingrl   r   typingr   r   r   r   r/   	wandb_gqlr   r   wandb_gql.clientr   r3   r	   r
   
wandb.apisr   wandb.apis.normalizer   wandb.apis.public.constr   wandb.apis.public.utilsr   r   wandb.sdk.artifacts._validatorsr   wandb.sdk.internal.internal_apir   r\   (wandb.sdk.internal.thread_local_settingsr   wandb.sdk.launch.utilsr   wandb.sdk.libr   r   wandb.sdk.lib.deprecater   r   wandb.sdk.lib.gql_requestr   	getLoggerrB   loggerr   r   r   r   r    <module>   s2    
8