o
    -wiJ                    @   s  d 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m	Z	m
Z
mZmZmZmZmZmZ ddl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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' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZB ddlCmDZD erddlEmFZFmGZGmHZHmIZImJZJmKZKmLZL ddlMmNZN eOePZQG dd dZRG dd  d Z8d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)
HTTPStatus)	TYPE_CHECKINGAnyDictIteratorListLiteralOptionalSetUnion)ValidationError)Unpack)Clientgql)
RetryError)envutil)one)public)normalize_exceptions)RETRY_TIMEDELTA)"fetch_org_entity_from_organization)
Registries)Registry)PathType!fetch_org_from_settings_or_entity
gql_compatparse_org_from_registry_path)
Deprecated)ServerFeature)is_artifact_registry_project)Api)_thread_local_api_settings)LAUNCH_DEFAULT_PROJECT)retryrunid)	deprecate)GraphQLSession)
ActionType
Automation	EventTypeIntegrationNewAutomationSlackIntegrationWebhookIntegration)WriteAutomationsKwargsc                   @   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)selfr1    r6   R/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/apis/public/api.py__init__]   s   
zRetryingClient.__init__c                 C   s   t | jjjddd S )Nz/graphql /)r   app_urlr4   	transporturlreplacer5   r6   r6   r7   r;   a   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.)	r4   executerequests
exceptionsReadTimeoutr<   default_timeoutwandbtermwarn)r5   argskwargsrC   r6   r6   r7   rE   e   s   
zRetryingClient.executec                 C   s$   | j d u r| | jd| _ | j S )N
serverInfo)r3   rE   
INFO_QUERYgetr?   r6   r6   r7   server_infoy   s   
zRetryingClient.server_infomin_versionreturnc                 C   s&   ddl m} |||| jd d kS )Nr   )parsecliVersionInfomax_cli_version)packaging.versionrT   rQ   )r5   rR   rT   r6   r6   r7   version_supported   s   z RetryingClient.version_supportedN)__name__
__module____qualname__r   rO   r   r8   propertyr;   r$   	retriabler   r   no_retry_authr   rF   RequestExceptionrE   rQ   strboolrX   r6   r6   r6   r7   r0   M   s(    


r0   c                   @   s  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deded!ed"ed# d$ed% d&eeef de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/d0Zdd1d2Zedefd3d4Zedefd5d6Zedee fd7d8Z edee fd9d:Z!edd<d=Z"d>d? Z#d@dA Z$dBdC Z%dDdE Z&dFdG Z'	Hddee dIeddJfdKdLZ(ddedee ddMfdNdOZ)	QddRedee dIeddSfdTdUZ*ddVdWZ+dXeddYfdZd[Z,d\eded; fd]d^Z-d\ede.d; fd_d`Z/			a	Q	bddRee dceeeef  ddedIedee0f
dfdgZ1e2ddhdiZ3		ddjdkZ4dldm Z5e2ddndoZ6e2ddee ddpfdqdrZ7e2	ddsedee ddtfdudvZ8e2	QddwedsedIeddxfdydzZ9e2dsededd{fd|d}Z:e2dd~dZ;e2	Q	ddsededIedee.e  ddf
ddZ<e2	.ddedee de0fddZ=e2ddedee fddZ>e2ddee dRee ddfddZ?e2dedede.eeef  fddZ@e2ddedee de0fddZAe2dedede0fddZB		ddee deeeef  deCfddZDddedee deEfddZF			ddeded dee dee dee.e  deEfddZG	ddQddee dIedeHd fddZI	ddQddee dIedeHd fddZJddQddee dIedeHd fddZKdddded ded de0fddZLdeMe fddZNdddedee ddfddZO	dddQddee dee dIedeHd fddZPe2d.dddde0deQd ddfddZRe2d.dddde0deQd ddfddĄZSe2dedef dedb fddƄZTd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	overridesrC   api_keyrS   c              
   C   s\  t   | _|p	i }| j| | jd d| jd< d|v r&|d | jd< d|v r:d|vr:td |d | jd< || _| jd u rPtj	d u rPtj
|dd d | _i | _i | _i | _i | _d | _|d urh|n| j| _d }tj	svd| jf}| jd	pt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_urlr:   organizationusernameentityzEPassing "username" to Api is deprecated. please use "entity" instead.)hostapi_proxiesWANDB__PROXIES{}true)z
User-AgentzUse-Admin-PrivilegesTz
{}/graphql)headersuse_jsonrC   authr=   cookiesproxies)r<   ) InternalApisettingsupdaterstriprJ   rK   _api_keyrd   r"   rr   loginrP   _viewer	_projects_runs_sweeps_reports_default_entity_HTTP_TIMEOUT_timeoutjsonloadsosenvironr   r'   
user_agentro   format_base_clientr0   r4   )r5   rc   rC   rd   
_overridesrq   rs   r6   r6   r7   r8     sV   
zApi.__init__namerh   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.
        )
entityNamer   N)r1   rE   CREATE_PROJECTr5   r   rh   r6   r6   r7   create_projectG  s   zApi.create_projectrun_idprojectrh   r   r   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`.
        Nr   )default_entityr   Runcreate)r5   r   r   rh   r6   r6   r7   
create_runP  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
        Nrh   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rh   r   default_settingsr@   resource_argssuccessz(failed to create default resource configdefaultResourceConfigIDPROJECTfailed to create run queue)r1   r   rh   r   _access_default_resource_config_id_default_resource_config)ru   r   
ValueErrorlenupperr   r#   rt   r   r   r   dumpscreate_default_resource_configrJ   Errorcreate_run_queuer   RunQueuer1   )r5   r   r   rh   r   r   r   rj   config_jsoncreate_config_result	config_idcreate_queue_resultr6   r6   r7   r   f  sj   '	

zApi.create_run_queuedisplay_name	spec_typevega2access)privater   specc           
      C   sT   |  }ttd}|j||||||d}	|	du s|	ddu r$td|	d d S )a  Create a custom chart preset and return its id.

        Args:
            entity: The entity (user or team) that owns the chart
            name: Unique identifier for the chart preset
            display_name: Human-readable name shown in the UI
            spec_type: Type of specification. Must be "vega2" for Vega-Lite v2 specifications.
            access: Access level for the chart:
                - "private": Chart is only accessible to the entity that created it
                - "public": Chart is publicly accessible
            spec: The Vega/Vega-Lite specification as a dictionary or JSON string

        Returns:
            The ID of the created chart preset in the format "entity/name"

        Raises:
            wandb.Error: If chart creation fails
            UnsupportedError: If the server doesn't support custom charts

        Example:
            ```python
            import wandb

            api = wandb.Api()

            # Define a simple bar chart specification
            vega_spec = {
                "$schema": "https://vega.github.io/schema/vega-lite/v6.json",
                "mark": "bar",
                "data": {"name": "wandb"},
                "encoding": {
                    "x": {"field": "${field:x}", "type": "ordinal"},
                    "y": {"field": "${field:y}", "type": "quantitative"},
                },
            }

            # Create the custom chart
            chart_id = api.create_custom_chart(
                entity="my-team",
                name="my-bar-chart",
                display_name="My Custom Bar Chart",
                spec_type="vega2",
                access="private",
                spec=vega_spec,
            )

            # Use with wandb.plot_table()
            chart = wandb.plot_table(
                vega_spec_name=chart_id,
                data_table=my_table,
                fields={"x": "category", "y": "value"},
            )
            ```
        )r@   )rh   r   r   r   r   r   Nchartzfailed to create custom chartid)r   rt   r   create_custom_chartrP   rJ   r   )
r5   rh   r   r   r   r   r   backend_accessrj   resultr6   r6   r7   r     s   @

zApi.create_custom_chart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
        Nrh   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=   r6   ).0keyvaluer6   r6   r7   
<listcomp>y  s    z(Api.upsert_run_queue.<locals>.<listcomp>r   )r   r   r   r   r   configSchemaValidationErrorszresource config validation: )r1   r   rh   )ru   r   r   r   r   r   r#   rt   r   r   itemsupsert_run_queuerJ   r   rP   rK   r   r   r1   )r5   r   r   r   rh   r   r   r   rj   upsert_run_queue_resultschema_errorserrorr6   r6   r7   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   )r5   emailadminr6   r6   r7   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   )SyncManagerr   uncategorizedFT)r   rh   r   mark_syncedr;   viewverbosesync_tensorboardr:   )
wandb.syncr   r%   generate_idru   rP   r   r1   r;   addstartis_donepollrunjoin)r5   root_dirr   r   rh   r   sm_r6   r6   r7   r     s(   


zApi.sync_tensorboardc                 C   s   | j S r2   )r4   r?   r6   r6   r7   r1     s   z
Api.clientc                 C   s   d tjS )NzW&B Public Client {})r   rJ   __version__r?   r6   r6   r7   r     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 )Nre   WANDB_API_KEY)
r"   rd   rx   rF   utilsget_netrc_authru   r   getenvr   )r5   rq   r   r6   r6   r7   rd     s   


zApi.api_keyc                 C   s4   | j d u r| j| j}|dpi d| _ | j S )Nviewerrh   )r   r4   rE   DEFAULT_ENTITY_QUERYrP   )r5   resr6   r6   r7   r     s   
zApi.default_entitypublic.Userc                 C   s:   | j d u rt| j| j| jd| _ | j j| _| j S )Nr   )	rz   r   r   r4   rE   VIEWER_QUERYrP   rh   r   r?   r6   r6   r7   r     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)r|   r?   r6   r6   r7   flush  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 rm   )displayNamer   r   zSInvalid path, should be TEAM/PROJECT/TYPE/ID where TYPE is runs, sweeps, or reports)stripsplitr   r   r   
startswithr   rJ   r   r   
BetaReportr1   urllibrT   unquoter>   )r5   pathpartsr   r   r6   r6   r7   	from_path  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.r   r   rh   Nr:   r   )ru   r   r  r   )r5   r  r   rh   r	  r6   r6   r7   _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.
        r   r   rh   z/runs/r:   z/sweeps/r   :r   r   r   r   )ru   r   r>   r  r  r   )r5   r  r   rh   r	  r   r6   r6   r7   _parse_path1  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.r   r   rh   Nr  r:   r   zInvalid artifact path: {}r   r   r   r   )ru   r   	partitionr  r   r   r   )r5   r  r   rh   colonalias
full_aliasr	  r6   r6   r7   _parse_artifact_pathS  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.  Usually there is no reason to change this.

        Returns:
            A `Projects` object which is an iterable collection of `Project` objects.
        Nrh   r   r  )ru   r   r   r{   r   Projectsr1   )r5   rh   r  r6   r6   r7   projectsg  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.
        r9   Nrh   rh   rf   )r    ru   r   rt   _resolve_org_entity_namer   Projectr1   )r5   r   rh   orgsettings_entityr6   r6   r7   r     s   zApi.projectr9   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 )a  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.  Usually there is no reason to change this.

        Returns:
            A `Reports` object which is an iterable collection of `BetaReport` objects.
        z	/fake_runr:   r   r  )r  r  rT   r  r   r`   r~   r   Reportsr1   r  )r5   r  r   r  rh   r   r   r   r6   r6   r7   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   )r5   teamadmin_usernamer6   r6   r7   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!  r1   )r5   r"  r6   r6   r7   r"    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)	r4   rE   USERS_QUERYr   rJ   rK   r   r   r   r5   r%  r   r6   r6   r7   user  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   r4   )r   edger?   r6   r7   r     s    zApi.users.<locals>.<listcomp>r'  r(  )r4   rE   r*  r+  r6   r?   r7   r'    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.

        Fields you can filter by include:
        - `createdAt`: The timestamp when the run was created. (in ISO 8601 format, e.g. "2023-01-01T12:00:00Z")
        - `displayName`: The human-readable display name of the run. (e.g. "eager-fox-1")
        - `duration`: The total runtime of the run in seconds.
        - `group`: The group name used to organize related runs together.
        - `host`: The hostname where the run was executed.
        - `jobType`: The type of job or purpose of the run.
        - `name`: The unique identifier of the run. (e.g. "a1b2cdef")
        - `state`: The current state of the run.
        - `tags`: The tags associated with the run.
        - `username`: The username of the user who initiated the run

        Additionally, you can filter by items in the run config or summary metrics.
        Such as `config.experiment_name`, `summary_metrics.loss`, etc.

        For more complex filtering, you can use MongoDB query operators.
        For details, see: https://docs.mongodb.com/manual/reference/operator/query
        The following operations are supported:
        - `$and`
        - `$or`
        - `$nor`
        - `$eq`
        - `$ne`
        - `$gt`
        - `$gte`
        - `$lt`
        - `$lte`
        - `$in`
        - `$nin`
        - `$exists`
        - `$regex`


        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 where config.experiment contains a nested field "category" with value "testing"
            ```
            api.runs(
                path="my_entity/my_project",
                filters={"config.experiment.category": "testing"},
            )
            ```

            Find runs in my_project with a loss value of 0.5 nested in a dictionary under model1 in the summary metrics
            ```
            api.runs(
                path="my_entity/my_project",
                filters={"summary_metrics.model1.loss": 0.5},
            )
            ```

            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"
            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.
        r9   )r/  r0  r  r1  )r  r`   r|   rP   r   Runsr1   )	r5   r  r/  r0  r  r1  rh   r   r   r6   r6   r7   runs  s   v
	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  r|   rP   r   r   r1   )r5   r  rh   r   r   r6   r6   r7   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   	QueuedRunr1   )r5   rh   r   
queue_namerun_queue_item_idr6  r7  r6   r6   r7   
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   r1   )r5   rh   r   r6   r6   r7   	run_queue  s
   	zApi.run_queuec                 C   r4  )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  r}   rP   r   Sweepr1   )r5   r  rh   r   sweep_idr6   r6   r7   r     r5  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.
        rh   r  )r  r    ru   r   r   r   r   rt   r  r   ArtifactTypesr1   )r5   r   project_pathrh   r  r  r6   r6   r7   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.
        rh   r  )r  r    r   r   r   ru   r   rt   r  r   ArtifactTyper1   )r5   rB  r   r@  rh   r  r  r6   r6   r7   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) Sets the page size for query pagination.  Usually there is no reason to change this.

        Returns:
            An iterable `ArtifactCollections` object.
        rh   r  r  )r  r    r   r   r   ru   r   rt   r  r   ArtifactCollectionsr1   )r5   rE  rB  r  rh   r   r  r  r6   r6   r7   artifact_collections  s   zApi.artifact_collectionszpublic.ArtifactCollectionc                 C   sh   |  |\}}}t|r"t|tj}| jd p| j}t j||d}|du r*t	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.
        rh   r  NzZCould not determine entity. Please include the entity as part of the collection name path.)r  r    r   r   ARTIFACTru   r   rt   r  r   r   ArtifactCollectionr1   )r5   rB  r   rh   r   collection_namer  r  r6   r6   r7   artifact_collection
  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)r5   rB  r   r  r6   r6   r7   artifact_versions)  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) Sets the page size for query pagination.  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.
        rh   r  )r  rQ  )r  r    r   r   rH  ru   r   rt   r  r   	Artifactsr1   )
r5   rB  r   r  rQ  rh   r   rJ  r  r  r6   r6   r7   rO  5  s    zApi.artifactsenable_trackingc           
      C   s   |d u rt d| |\}}}t|r7|ddkr"|dd n| jd }| jd p.| j}t j||d}|d u r?t dt	j
j|||| j|d	}	|d ur_|	j|kr_t d
| d|	j |	S )Nz,You must specify name= to fetch an artifact.r:   r   r   rf   rh   r  zXCould not determine entity. Please include the entity as part of the artifact name path.)rh   r   r   r1   rS  ztype z( specified but this artifact is of type )r   r  r    countr  ru   r   rt   r  rJ   Artifact
_from_namer1   r   )
r5   r   r   rS  rh   r   artifact_namerf   r  artifactr6   r6   r7   	_artifactZ  s8   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)r   r   rS  )rY  r5   r   r   r6   r6   r7   rX    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   rT  r   Job)r5   r   r  r6   r6   r7   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\  )projectNamer   artifactTypeNamer   z
Project: 'z' not found in entity: 'z' or access denied.artifactTypeartifactCollectionsr(  c                 S   s   g | ]}|d  d qS )r)  rO  r6   )r   xr6   r6   r7   r     s    z!Api.list_jobs.<locals>.<listcomp>F)	r   r   r4   rE   rJ   	termerrorrF   rG   	HTTPError)r5   rh   r   r&  artifact_queryrO  r6   r6   r7   	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.
        FT)rY  rJ   errors	CommErrorrZ  r6   r6   r7   artifact_exists  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.
        FT)rK  rJ   rf  rg  rZ  r6   r6   r7   artifact_collection_exists  s   zApi.artifact_collection_existsrf   filterc                 C   s6   t  tjstd|pt| j| j}t| j	||S )ak  Returns a Registry iterator.

        Use the iterator to search and filter registries, collections,
        or artifact versions across your organization's registry.

        Examples:
            Find all registries with the names that contain "model"
            ```python
            import wandb

            api = wandb.Api()  # specify an org if your entity belongs to multiple orgs
            api.registries(filter={"name": {"$regex": "model"}})
            ```

            Find all collections in the registries with the name "my_collection" and the tag "my_tag"
            ```python
            api.registries().collections(
                filter={"name": "my_collection", "tag": "my_tag"}
            )
            ```

            Find all artifact versions in the registries with a collection name that contains "my_collection" and a version that has the alias "best"
            ```python
            api.registries().collections(
                filter={"name": {"$regex": "my_collection"}}
            ).versions(filter={"alias": "best"})
            ```

            Find all artifact versions in the registries that contain "model" and have the tag "prod" or alias "best"
            ```python
            api.registries(filter={"name": {"$regex": "model"}}).versions(
                filter={"$or": [{"tag": "prod"}, {"alias": "best"}]}
            )
            ```

        Args:
            organization: (str, optional) The organization of the registry to fetch.
                If not specified, use the organization specified in the user's settings.
            filter: (dict, optional) MongoDB-style filter to apply to each object in the registry iterator.
                Fields available to filter for collections are
                    `name`, `description`, `created_at`, `updated_at`.
                Fields available to filter for collections are
                    `name`, `tag`, `description`, `created_at`, `updated_at`
                Fields available to filter for versions are
                    `tag`, `alias`, `created_at`, `updated_at`, `metadata`

        Returns:
            A registry iterator.
        zRegistry search API is not enabled on this wandb server version. Please upgrade your server version or contact support at support@wandb.com.)
rt   _server_supportsr   ARTIFACT_REGISTRY_SEARCHRuntimeErrorr   ru   r   r   r1   )r5   rf   rj  r6   r6   r7   
registries'  s   6zApi.registriesc                 C   sP   t  tjstd|pt| j| j}t| j	|}t
| j	|||}|  |S )a  Return a registry given a registry name.

        Args:
            name: The name of the registry. This is without the `wandb-registry-`
                prefix.
            organization: The organization of the registry.
                If no organization is set in the settings, the organization will be
                fetched from the entity if the entity only belongs to one
                organization.

        Returns:
            A registry object.

        Examples:
            Fetch and update a registry
            ```python
            import wandb

            api = wandb.Api()
            registry = api.registry(name="my-registry", organization="my-org")
            registry.description = "This is an updated description"
            registry.save()
            ```
        zapi.registry() is not enabled on this wandb server version. Please upgrade your server version or contact support at support@wandb.com.)rt   rk  r   rl  rm  r   ru   r   r   r1   r   load)r5   r   rf   
org_entityregistryr6   r6   r7   rq  h  s   zApi.registry
visibility)rf   
restricteddescriptionrA  c                 C   s   t  tjstd|pt| j| j}z	| j||d}W n t	y(   d}Y nw |r6t	d|d|dt
| j|||||S )a  Create a new registry.

        Args:
            name: The name of the registry. Name must be unique within the organization.
            visibility: The visibility of the registry.
                organization: Anyone in the organization can view this registry. You can
                    edit their roles later from the settings in the UI.
                restricted: Only invited members via the UI can access this registry.
                    Public sharing is disabled.
            organization: The organization of the registry.
                If no organization is set in the settings, the organization will be
                fetched from the entity if the entity only belongs to one organization.
            description: The description of the registry.
            artifact_types: The accepted artifact types of the registry. A type is no
                more than 128 characters and do not include characters `/` or `:`. If
                not specified, all types are accepted.
                Allowed types added to the registry cannot be removed later.

        Returns:
            A registry object.

        Examples:
            ```python
            import wandb

            api = wandb.Api()
            registry = api.create_registry(
                name="my-registry",
                visibility="restricted",
                organization="my-org",
                description="This is a test registry",
                artifact_types=["model"],
            )
            ```
        zcreate_registry api is not enabled on this wandb server version. Please upgrade your server version or contact support at support@wandb.com.)r   rf   Nz	Registry z  already exists in organization z, please use a different name.)rt   rk  r   +INCLUDE_ARTIFACT_TYPES_IN_REGISTRY_CREATIONrm  r   ru   r   rq  r   r   r   r1   )r5   r   rr  rf   rt  rA  existing_registryr6   r6   r7   create_registry  s4   +zApi.create_registryr  r+   c                C   *   ddl m} d|p| ji}|| j||dS )a  Return an iterator of all integrations for an entity.

        Args:
            entity: The entity (e.g. team name) for which to
                fetch integrations.  If not provided, the user's default entity
                will be used.
            per_page: Number of integrations to fetch per page.
                Defaults to 50.  Usually there is no reason to change this.

        Yields:
            Iterator[SlackIntegration | WebhookIntegration]: An iterator of any supported integrations.
        r   )Integrationsr   r1   	variablesr  )wandb.apis.public.integrationsry  r   r1   )r5   rh   r  ry  paramsr6   r6   r7   integrations  s   zApi.integrationsr.   c                C   rx  )az  Returns an iterator of webhook integrations for an entity.

        Args:
            entity: The entity (e.g. team name) for which to
                fetch integrations.  If not provided, the user's default entity
                will be used.
            per_page: Number of integrations to fetch per page.
                Defaults to 50.  Usually there is no reason to change this.

        Yields:
            Iterator[WebhookIntegration]: An iterator of webhook integrations.

        Examples:
            Get all registered webhook integrations for the team "my-team":
            ```python
            import wandb

            api = wandb.Api()
            webhook_integrations = api.webhook_integrations(entity="my-team")
            ```

            Find only webhook integrations that post requests to "https://my-fake-url.com":
            ```python
            webhook_integrations = api.webhook_integrations(entity="my-team")
            my_webhooks = [
                ig
                for ig in webhook_integrations
                if ig.url_endpoint.startswith("https://my-fake-url.com")
            ]
            ```
        r   )WebhookIntegrationsr   rz  )r|  r  r   r1   )r5   rh   r  r  r}  r6   r6   r7   webhook_integrations  
   "zApi.webhook_integrations)rh   r  r-   c                C   rx  )ao  Returns an iterator of Slack integrations for an entity.

        Args:
            entity: The entity (e.g. team name) for which to
                fetch integrations.  If not provided, the user's default entity
                will be used.
            per_page: Number of integrations to fetch per page.
                Defaults to 50.  Usually there is no reason to change this.

        Yields:
            Iterator[SlackIntegration]: An iterator of Slack integrations.

        Examples:
            Get all registered Slack integrations for the team "my-team":
            ```python
            import wandb

            api = wandb.Api()
            slack_integrations = api.slack_integrations(entity="my-team")
            ```

            Find only Slack integrations that post to channel names starting with "team-alerts-":
            ```python
            slack_integrations = api.slack_integrations(entity="my-team")
            team_alert_integrations = [
                ig
                for ig in slack_integrations
                if ig.channel_name.startswith("team-alerts-")
            ]
            ```
        r   )SlackIntegrationsr   rz  )r|  r  r   r1   )r5   rh   r  r  r}  r6   r6   r7   slack_integrations  r  zApi.slack_integrationseventactionr  r*   r  r(   c                C   sb   ddl m}m} t }|du p||v p|d|j }|du p,||v p,|d|j }|o0|S )zIReturns whether the server recognizes the automation event and/or action.r   )ALWAYS_SUPPORTED_ACTIONSALWAYS_SUPPORTED_EVENTSNAUTOMATION_EVENT_AUTOMATION_ACTION_)wandb.automations._utilsr  r  rt   rk  r   )r5   r  r  r  r  rj   supports_eventsupports_actionr6   r6   r7   _supports_automationA  s   zApi._supports_automationc                    sb   ddl m} ddlm}m}m}m} |j|j|j	|j|j
|j|j|ji t fdd|D S )a  Returns the names of unsupported automation-related fragments.

        Older servers won't recognize newer GraphQL types, so a valid request may
        unnecessarily error out because it won't recognize fragments defined on those types.

        So e.g. if a server does not support `NO_OP` action types, then the following need to be
        removed from the body of the GraphQL request:

            - Fragment definition:
                ```
                fragment NoOpActionFields on NoOpTriggeredAction {
                    noOp
                }
                ```

            - Fragment spread in selection set:
                ```
                {
                    ...NoOpActionFields
                    # ... other fields ...
                }
                ```
        r   )r(   )GenericWebhookActionFieldsNoOpActionFieldsNotificationActionFieldsQueueJobActionFieldsc                 3   s.    | ]}j |d s | rV  qdS )r  N)r  rP   )r   r  fragment_namesr   r5   r6   r7   	<genexpr>  s    

z4Api._omitted_automation_fragments.<locals>.<genexpr>)wandb.automationsr(   wandb.automations._generatedr  r  r  r  NO_OPrY   	QUEUE_JOBNOTIFICATIONGENERIC_WEBHOOKset)r5   r(   r  r  r  r  r6   r  r7   _omitted_automation_fragmentsZ  s   
z!Api._omitted_automation_fragments)rh   r)   c                C   s    t | j||dtdtddS )a  Returns the only Automation matching the parameters.

        Args:
            name: The name of the automation to fetch.
            entity: The entity to fetch the automation for.

        Raises:
            ValueError: If zero or multiple Automations match the search criteria.

        Examples:
            Get an existing automation named "my-automation":

            ```python
            import wandb

            api = wandb.Api()
            automation = api.automation(name="my-automation")
            ```

            Get an existing automation named "other-automation", from the entity "my-team":

            ```python
            automation = api.automation(name="other-automation", entity="my-team")
            ```
        )rh   r   zNo automations foundzMultiple automations found)	too_shorttoo_long)r   automationsr   r   r6   r6   r7   
automation  s
   zApi.automationr  c                #   s    ddl m} ddlm}m} d|i}|du r|}n|}|  }	t||	d}
|| j|||
d} dur<t fdd	|}|E dH  dS )
a  Returns an iterator over all Automations that match the given parameters.

        If no parameters are provided, the returned iterator will contain all
        Automations that the user has access to.

        Args:
            entity: The entity to fetch the automations for.
            name: The name of the automation to fetch.
            per_page: The number of automations to fetch per page.
                Defaults to 50.  Usually there is no reason to change this.

        Returns:
            A list of automations.

        Examples:
            Fetch all existing automations for the entity "my-team":

            ```python
            import wandb

            api = wandb.Api()
            automations = api.automations(entity="my-team")
            ```
        r   )Automations)GET_AUTOMATIONS_BY_ENTITY_GQLGET_AUTOMATIONS_GQLr   Nomit_fragments)r1   r{  r  _queryc                    s
   | j  kS r2   r   )ra  r  r6   r7   <lambda>  s   
 z!Api.automations.<locals>.<lambda>)	wandb.apis.public.automationsr  r  r  r  r  r   r1   rj  )r5   rh   r   r  r  r  r  r{  gql_strr  r&  iteratorr6   r  r7   r    s   
zApi.automations)fetch_existingobjr,   r  rM   r/   c             
   K   s  ddl m} ddlm}m} ddlm} ||fi |}| j|j }	|j	 }
ds4t
d|	d|
d|  }t||d	}d
|jddi}|j}z
| jj||d}W n9 tjy } z,t|jj}|tju r|r~td|d | j|dW  Y d}~S t
d|dd d}~ww z||j}W n ty } z
d|}t||d}~ww |du s|jdu rd|}t|||jS )a  Create a new Automation.

        Args:
            obj:
                The automation to create.
            fetch_existing:
                If True, and a conflicting automation already exists, attempt
                to fetch the existing automation instead of raising an error.
            **kwargs:
                Any additional values to assign to the automation before
                creating it.  If given, these will override any values that may
                already be set on the automation:
                - `name`: The name of the automation.
                - `description`: The description of the automation.
                - `enabled`: Whether the automation is enabled.
                - `scope`: The scope of the automation.
                - `event`: The event that triggers the automation.
                - `action`: The action that is triggered by the automation.

        Returns:
            The saved Automation.

        Examples:
            Create a new automation named "my-automation" that sends a Slack notification
            when a run within a specific project logs a metric exceeding a custom threshold:

            ```python
            import wandb
            from wandb.automations import OnRunMetric, RunEvent, SendNotification

            api = wandb.Api()

            project = api.project("my-project", entity="my-team")

            # Use the first Slack integration for the team
            slack_hook = next(api.slack_integrations(entity="my-team"))

            event = OnRunMetric(
                scope=project,
                filter=RunEvent.metric("custom-metric") > 10,
            )
            action = SendNotification.from_integration(slack_hook)

            automation = api.create_automation(
                event >> action,
                name="my-automation",
                description="Send a Slack message whenever 'custom-metric' exceeds 10.",
            )
            ```
        r   )r)   )CREATE_AUTOMATION_GQLCreateAutomation)prepare_to_creater  Automation event or action ( -> }) is not supported on this wandb server version. Please upgrade your server version, or contact support at support@wandb.com.r  r}  Texclude_nonevariable_valuesAutomation z exists. Fetching it instead.r  Nz5 exists. Unable to create another with the same name.z+Invalid response while creating automation z)Empty response while creating automation )r  r)   r  r  r  r  r  r  triggering_event_typetriggered_action_typer   r  r   
model_dumpr   r1   rE   rF   rc  r   responsestatus_codeCONFLICTrJ   termlogr  model_validater   r   rm  trigger)r5   r  r  rM   r)   r  r  r  	gql_inputr  r  r  mutationr{  r   dataestatusr   msgr6   r6   r7   create_automation  sT   :




zApi.create_automation)create_missingr  c             
   K   s  ddl m}m} ddlm}m} ddlm} | j|j	ds!t
d||fi |}	| j|	j }
|	j }dsCtd|
j d	|j d
|  }t||d}d|	jddi}|	j}z
| jj||d}W nE tjy } z8t|jj}|tju r|rtd|d | |W  Y d}~S td|d|td|d|jj  d}~ww z| |j!}W n t"y } z
d|}t
||d}~ww |du s|j#du rd|}t
|| |j#S )a  Update an existing automation.

        Args:
            obj: The automation to update.  Must be an existing automation.
            create_missing (bool):
                If True, and the automation does not exist, create it.
            **kwargs:
                Any additional values to assign to the automation before
                updating it.  If given, these will override any values that may
                already be set on the automation:
                - `name`: The name of the automation.
                - `description`: The description of the automation.
                - `enabled`: Whether the automation is enabled.
                - `scope`: The scope of the automation.
                - `event`: The event that triggers the automation.
                - `action`: The action that is triggered by the automation.

        Returns:
            The updated automation.

        Examples:
            Disable and edit the description of an existing automation ("my-automation"):

            ```python
            import wandb

            api = wandb.Api()

            automation = api.automation(name="my-automation")
            automation.enabled = False
            automation.description = "Kept for reference, but no longer used."

            updated_automation = api.update_automation(automation)
            ```

            OR:

            ```python
            import wandb

            api = wandb.Api()

            automation = api.automation(name="my-automation")

            updated_automation = api.update_automation(
                automation,
                enabled=False,
                description="Kept for reference, but no longer used.",
            )
            ```
        r   )r(   r)   )UPDATE_AUTOMATION_GQLUpdateAutomation)prepare_to_updater  zUpdating existing automations is not enabled on this wandb server version. Please upgrade your server version, or contact support at support@wandb.com.r  r  r  r  r  r}  Tr  r  r  z not found. Creating it.Nz not found. Unable to edit it.zGot response status z: z+Invalid response while updating automation z)Empty response while updating automation )$r  r(   r)   r  r  r  r  r  r  r  rm  r  r  r   r   r  r   r  r   r1   rE   rF   rc  r   r  r  	NOT_FOUNDrJ   r  r  rb  textr  r   r   r  )r5   r  r  rM   r(   r)   r  r  r  r  r  r  r  r  r{  r   r  r  r  r   r  r6   r6   r7   update_automationR  s^   ;




zApi.update_automationc              
   C   s   ddl m}m} ddlm} ||}t|}d|i}| jj||d}z||j	}	W n t
y@ }
 z
d|}t||
d}
~
ww |	du rNd|}t||	jsXtd	||	jS )
zDelete an automation.

        Args:
            obj: The automation to delete, or its ID.

        Returns:
            True if the automation was deleted successfully.
        r   )DELETE_AUTOMATION_GQLDeleteAutomation)
extract_idr   r  z+Invalid response while deleting automation Nz)Empty response while deleting automation zFailed to delete automation: )r  r  r  r  r  r   r1   rE   r  r   r   rm  r   )r5   r  r  r  r  id_r  r{  r  r   r  r  r6   r6   r7   delete_automation  s&   



zApi.delete_automation)NNN)NNNN)F)rS   r   )Nr  r2   )r9   Nr  )NNr.  r  T)r9   )NN)r  )r  N)NF)UrY   rZ   r[   __doc__r   get_http_timeoutr   r   r   r   r*  r   r	   r   r`   r   intr8   r   r   dictr   r   r   r   r   r   r   r\   r0   r1   r   rd   r   r   r   r
  r  r  r  r  r   r   r$  r"  r,  r   r'  ra   r3  r   r   r;  r<  r   rA  rD  rG  rK  rP  rO  rY  rX  r\  re  rh  ri  r   rn  r   rq  rw  r   r~  r  r  r  r
   r  r  r  r   r  r  r  r6   r6   r6   r7   r!      s   
$.
7

p

T

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

 
 

$("$M
A*

L

*
,
4
'
8jy$r!   )Sr  r   loggingr   r  httpr   typingr   r   r   r   r   r   r	   r
   r   rF   pydanticr   typing_extensionsr   	wandb_gqlr   r   wandb_gql.clientr   rJ   r   r   wandb._iterutilsr   
wandb.apisr   wandb.apis.normalizer   wandb.apis.public.constr   #wandb.apis.public.registries._utilsr   .wandb.apis.public.registries.registries_searchr   %wandb.apis.public.registries.registryr   wandb.apis.public.utilsr   r   r   r   wandb.proto.wandb_deprecatedr   wandb.proto.wandb_internal_pb2r   wandb.sdk.artifacts._validatorsr    wandb.sdk.internal.internal_apir!   rt   (wandb.sdk.internal.thread_local_settingsr"   wandb.sdk.launch.utilsr#   wandb.sdk.libr$   r%   wandb.sdk.lib.deprecater&   wandb.sdk.lib.gql_requestr'   r  r(   r)   r*   r+   r,   r-   r.   r  r/   	getLoggerrY   loggerr0   r6   r6   r6   r7   <module>   sJ    ,$	
<